chiark / gitweb /
Fix RemainAfterExit services keeping a hold on console
[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         /* For remain_after_exit services, let's see if we can "release" the
1523          * hold on the console, since unit_notify() only does that in case of
1524          * change of state */
1525         if (state == SERVICE_EXITED && s->remain_after_exit &&
1526             UNIT(s)->manager->n_on_console > 0) {
1527                 ExecContext *ec = unit_get_exec_context(UNIT(s));
1528                 if (ec && exec_context_may_touch_console(ec)) {
1529                         Manager *m = UNIT(s)->manager;
1530
1531                         m->n_on_console --;
1532                         if (m->n_on_console == 0)
1533                                 /* unset no_console_output flag, since the console is free */
1534                                 m->no_console_output = false;
1535                 }
1536         }
1537
1538         if (old_state != state)
1539                 log_debug_unit(UNIT(s)->id,
1540                                "%s changed %s -> %s", UNIT(s)->id,
1541                                service_state_to_string(old_state),
1542                                service_state_to_string(state));
1543
1544         unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
1545         s->reload_result = SERVICE_SUCCESS;
1546 }
1547
1548 static int service_coldplug(Unit *u) {
1549         Service *s = SERVICE(u);
1550         int r;
1551
1552         assert(s);
1553         assert(s->state == SERVICE_DEAD);
1554
1555         if (s->deserialized_state != s->state) {
1556
1557                 if (s->deserialized_state == SERVICE_START_PRE ||
1558                     s->deserialized_state == SERVICE_START ||
1559                     s->deserialized_state == SERVICE_START_POST ||
1560                     s->deserialized_state == SERVICE_RELOAD ||
1561                     s->deserialized_state == SERVICE_STOP ||
1562                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1563                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1564                     s->deserialized_state == SERVICE_STOP_POST ||
1565                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1566                     s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1567                     s->deserialized_state == SERVICE_AUTO_RESTART) {
1568
1569                         if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_start_usec > 0) {
1570                                 usec_t k;
1571
1572                                 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_start_usec;
1573
1574                                 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, k, &s->timer_watch);
1575                                 if (r < 0)
1576                                         return r;
1577                         }
1578                 }
1579
1580                 if ((s->deserialized_state == SERVICE_START &&
1581                      (s->type == SERVICE_FORKING ||
1582                       s->type == SERVICE_DBUS ||
1583                       s->type == SERVICE_ONESHOT ||
1584                       s->type == SERVICE_NOTIFY)) ||
1585                     s->deserialized_state == SERVICE_START_POST ||
1586                     s->deserialized_state == SERVICE_RUNNING ||
1587                     s->deserialized_state == SERVICE_RELOAD ||
1588                     s->deserialized_state == SERVICE_STOP ||
1589                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1590                     s->deserialized_state == SERVICE_STOP_SIGKILL)
1591                         if (s->main_pid > 0) {
1592                                 r = unit_watch_pid(UNIT(s), s->main_pid);
1593                                 if (r < 0)
1594                                         return r;
1595                         }
1596
1597                 if (s->deserialized_state == SERVICE_START_PRE ||
1598                     s->deserialized_state == SERVICE_START ||
1599                     s->deserialized_state == SERVICE_START_POST ||
1600                     s->deserialized_state == SERVICE_RELOAD ||
1601                     s->deserialized_state == SERVICE_STOP ||
1602                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1603                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1604                     s->deserialized_state == SERVICE_STOP_POST ||
1605                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1606                     s->deserialized_state == SERVICE_FINAL_SIGKILL)
1607                         if (s->control_pid > 0) {
1608                                 r = unit_watch_pid(UNIT(s), s->control_pid);
1609                                 if (r < 0)
1610                                         return r;
1611                         }
1612
1613                 if (s->deserialized_state == SERVICE_START_POST ||
1614                     s->deserialized_state == SERVICE_RUNNING)
1615                         service_handle_watchdog(s);
1616
1617                 service_set_state(s, s->deserialized_state);
1618         }
1619         return 0;
1620 }
1621
1622 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1623         Iterator i;
1624         int r;
1625         int *rfds = NULL;
1626         unsigned rn_fds = 0;
1627         Unit *u;
1628
1629         assert(s);
1630         assert(fds);
1631         assert(n_fds);
1632
1633         if (s->socket_fd >= 0)
1634                 return 0;
1635
1636         SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1637                 int *cfds;
1638                 unsigned cn_fds;
1639                 Socket *sock;
1640
1641                 if (u->type != UNIT_SOCKET)
1642                         continue;
1643
1644                 sock = SOCKET(u);
1645
1646                 r = socket_collect_fds(sock, &cfds, &cn_fds);
1647                 if (r < 0)
1648                         goto fail;
1649
1650                 if (!cfds)
1651                         continue;
1652
1653                 if (!rfds) {
1654                         rfds = cfds;
1655                         rn_fds = cn_fds;
1656                 } else {
1657                         int *t;
1658
1659                         t = new(int, rn_fds+cn_fds);
1660                         if (!t) {
1661                                 free(cfds);
1662                                 r = -ENOMEM;
1663                                 goto fail;
1664                         }
1665
1666                         memcpy(t, rfds, rn_fds * sizeof(int));
1667                         memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1668                         free(rfds);
1669                         free(cfds);
1670
1671                         rfds = t;
1672                         rn_fds = rn_fds+cn_fds;
1673                 }
1674         }
1675
1676         *fds = rfds;
1677         *n_fds = rn_fds;
1678
1679         return 0;
1680
1681 fail:
1682         free(rfds);
1683
1684         return r;
1685 }
1686
1687 static int service_spawn(
1688                 Service *s,
1689                 ExecCommand *c,
1690                 bool timeout,
1691                 bool pass_fds,
1692                 bool apply_permissions,
1693                 bool apply_chroot,
1694                 bool apply_tty_stdin,
1695                 bool set_notify_socket,
1696                 bool is_control,
1697                 pid_t *_pid) {
1698
1699         pid_t pid;
1700         int r;
1701         int *fds = NULL;
1702         _cleanup_free_ int *fdsbuf = NULL;
1703         unsigned n_fds = 0, n_env = 0;
1704         _cleanup_strv_free_ char
1705                 **argv = NULL, **final_env = NULL, **our_env = NULL;
1706         const char *path;
1707
1708         assert(s);
1709         assert(c);
1710         assert(_pid);
1711
1712         unit_realize_cgroup(UNIT(s));
1713
1714         if (pass_fds ||
1715             s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1716             s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1717             s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1718
1719                 if (s->socket_fd >= 0) {
1720                         fds = &s->socket_fd;
1721                         n_fds = 1;
1722                 } else {
1723                         r = service_collect_fds(s, &fdsbuf, &n_fds);
1724                         if (r < 0)
1725                                 goto fail;
1726
1727                         fds = fdsbuf;
1728                 }
1729         }
1730
1731         if (timeout && s->timeout_start_usec) {
1732                 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true,
1733                                      s->timeout_start_usec, &s->timer_watch);
1734                 if (r < 0)
1735                         goto fail;
1736         } else
1737                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1738
1739         r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1740         if (r < 0)
1741                 goto fail;
1742
1743         our_env = new0(char*, 5);
1744         if (!our_env) {
1745                 r = -ENOMEM;
1746                 goto fail;
1747         }
1748
1749         if (set_notify_socket)
1750                 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1751                         r = -ENOMEM;
1752                         goto fail;
1753                 }
1754
1755         if (s->main_pid > 0)
1756                 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1757                         r = -ENOMEM;
1758                         goto fail;
1759                 }
1760
1761         if (s->watchdog_usec > 0)
1762                 if (asprintf(our_env + n_env++, "WATCHDOG_USEC=%llu", (unsigned long long) s->watchdog_usec) < 0) {
1763                         r = -ENOMEM;
1764                         goto fail;
1765                 }
1766
1767         if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
1768                 if (asprintf(our_env + n_env++, "MANAGERPID=%lu", (unsigned long) getpid()) < 0) {
1769                         r = -ENOMEM;
1770                         goto fail;
1771                 }
1772
1773         final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1774         if (!final_env) {
1775                 r = -ENOMEM;
1776                 goto fail;
1777         }
1778
1779         if (is_control && UNIT(s)->cgroup_path) {
1780                 path = strappenda(UNIT(s)->cgroup_path, "/control");
1781                 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1782         } else
1783                 path = UNIT(s)->cgroup_path;
1784
1785         r = exec_spawn(c,
1786                        argv,
1787                        &s->exec_context,
1788                        fds, n_fds,
1789                        final_env,
1790                        apply_permissions,
1791                        apply_chroot,
1792                        apply_tty_stdin,
1793                        UNIT(s)->manager->confirm_spawn,
1794                        UNIT(s)->manager->cgroup_supported,
1795                        path,
1796                        UNIT(s)->id,
1797                        s->type == SERVICE_IDLE ? UNIT(s)->manager->idle_pipe : NULL,
1798                        &pid);
1799         if (r < 0)
1800                 goto fail;
1801
1802         r = unit_watch_pid(UNIT(s), pid);
1803         if (r < 0)
1804                 /* FIXME: we need to do something here */
1805                 goto fail;
1806
1807         *_pid = pid;
1808
1809         return 0;
1810
1811 fail:
1812         if (timeout)
1813                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1814
1815         return r;
1816 }
1817
1818 static int main_pid_good(Service *s) {
1819         assert(s);
1820
1821         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1822          * don't know */
1823
1824         /* If we know the pid file, then lets just check if it is
1825          * still valid */
1826         if (s->main_pid_known) {
1827
1828                 /* If it's an alien child let's check if it is still
1829                  * alive ... */
1830                 if (s->main_pid_alien && s->main_pid > 0)
1831                         return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1832
1833                 /* .. otherwise assume we'll get a SIGCHLD for it,
1834                  * which we really should wait for to collect exit
1835                  * status and code */
1836                 return s->main_pid > 0;
1837         }
1838
1839         /* We don't know the pid */
1840         return -EAGAIN;
1841 }
1842
1843 _pure_ static int control_pid_good(Service *s) {
1844         assert(s);
1845
1846         return s->control_pid > 0;
1847 }
1848
1849 static int cgroup_good(Service *s) {
1850         int r;
1851
1852         assert(s);
1853
1854         if (!UNIT(s)->cgroup_path)
1855                 return 0;
1856
1857         r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
1858         if (r < 0)
1859                 return r;
1860
1861         return !r;
1862 }
1863
1864 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1865         int r;
1866         assert(s);
1867
1868         if (f != SERVICE_SUCCESS)
1869                 s->result = f;
1870
1871         service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1872
1873         if (allow_restart &&
1874             !s->forbid_restart &&
1875             (s->restart == SERVICE_RESTART_ALWAYS ||
1876              (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1877              (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1878              (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
1879              (s->restart == SERVICE_RESTART_ON_ABORT && (s->result == SERVICE_FAILURE_SIGNAL ||
1880                                                          s->result == SERVICE_FAILURE_CORE_DUMP))) &&
1881             (s->result != SERVICE_FAILURE_EXIT_CODE ||
1882              !set_contains(s->restart_ignore_status.code, INT_TO_PTR(s->main_exec_status.status))) &&
1883             (s->result != SERVICE_FAILURE_SIGNAL ||
1884              !set_contains(s->restart_ignore_status.signal, INT_TO_PTR(s->main_exec_status.status)))
1885                 ) {
1886
1887                 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->restart_usec, &s->timer_watch);
1888                 if (r < 0)
1889                         goto fail;
1890
1891                 service_set_state(s, SERVICE_AUTO_RESTART);
1892         }
1893
1894         s->forbid_restart = false;
1895
1896         /* we want fresh tmpdirs in case service is started again immediately */
1897         exec_context_tmp_dirs_done(&s->exec_context);
1898
1899         /* Try to delete the pid file. At this point it will be
1900          * out-of-date, and some software might be confused by it, so
1901          * let's remove it. */
1902         if (s->pid_file)
1903                 unlink_noerrno(s->pid_file);
1904
1905         return;
1906
1907 fail:
1908         log_warning_unit(UNIT(s)->id,
1909                          "%s failed to run install restart timer: %s",
1910                          UNIT(s)->id, strerror(-r));
1911         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1912 }
1913
1914 static void service_enter_stop_post(Service *s, ServiceResult f) {
1915         int r;
1916         assert(s);
1917
1918         if (f != SERVICE_SUCCESS)
1919                 s->result = f;
1920
1921         service_unwatch_control_pid(s);
1922
1923         s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1924         if (s->control_command) {
1925                 s->control_command_id = SERVICE_EXEC_STOP_POST;
1926
1927                 r = service_spawn(s,
1928                                   s->control_command,
1929                                   true,
1930                                   false,
1931                                   !s->permissions_start_only,
1932                                   !s->root_directory_start_only,
1933                                   true,
1934                                   false,
1935                                   true,
1936                                   &s->control_pid);
1937                 if (r < 0)
1938                         goto fail;
1939
1940
1941                 service_set_state(s, SERVICE_STOP_POST);
1942         } else
1943                 service_enter_dead(s, SERVICE_SUCCESS, true);
1944
1945         return;
1946
1947 fail:
1948         log_warning_unit(UNIT(s)->id,
1949                          "%s failed to run 'stop-post' task: %s",
1950                          UNIT(s)->id, strerror(-r));
1951         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1952 }
1953
1954 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1955         int r;
1956
1957         assert(s);
1958
1959         if (f != SERVICE_SUCCESS)
1960                 s->result = f;
1961
1962         r = unit_kill_context(
1963                         UNIT(s),
1964                         &s->kill_context,
1965                         state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM,
1966                         s->main_pid,
1967                         s->control_pid,
1968                         s->main_pid_alien);
1969         if (r < 0)
1970                 goto fail;
1971
1972         if (r > 0) {
1973                 if (s->timeout_stop_usec > 0) {
1974                         r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true,
1975                                              s->timeout_stop_usec, &s->timer_watch);
1976                         if (r < 0)
1977                                 goto fail;
1978                 }
1979
1980                 service_set_state(s, state);
1981         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1982                 service_enter_stop_post(s, SERVICE_SUCCESS);
1983         else
1984                 service_enter_dead(s, SERVICE_SUCCESS, true);
1985
1986         return;
1987
1988 fail:
1989         log_warning_unit(UNIT(s)->id,
1990                          "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1991
1992         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1993                 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1994         else
1995                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1996 }
1997
1998 static void service_enter_stop(Service *s, ServiceResult f) {
1999         int r;
2000
2001         assert(s);
2002
2003         if (f != SERVICE_SUCCESS)
2004                 s->result = f;
2005
2006         service_unwatch_control_pid(s);
2007
2008         s->control_command = s->exec_command[SERVICE_EXEC_STOP];
2009         if (s->control_command) {
2010                 s->control_command_id = SERVICE_EXEC_STOP;
2011
2012                 r = service_spawn(s,
2013                                   s->control_command,
2014                                   true,
2015                                   false,
2016                                   !s->permissions_start_only,
2017                                   !s->root_directory_start_only,
2018                                   false,
2019                                   false,
2020                                   true,
2021                                   &s->control_pid);
2022                 if (r < 0)
2023                         goto fail;
2024
2025                 service_set_state(s, SERVICE_STOP);
2026         } else
2027                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2028
2029         return;
2030
2031 fail:
2032         log_warning_unit(UNIT(s)->id,
2033                          "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
2034         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2035 }
2036
2037 static void service_enter_running(Service *s, ServiceResult f) {
2038         int main_pid_ok, cgroup_ok;
2039         assert(s);
2040
2041         if (f != SERVICE_SUCCESS)
2042                 s->result = f;
2043
2044         main_pid_ok = main_pid_good(s);
2045         cgroup_ok = cgroup_good(s);
2046
2047         if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
2048             (s->bus_name_good || s->type != SERVICE_DBUS))
2049                 service_set_state(s, SERVICE_RUNNING);
2050         else if (s->remain_after_exit)
2051                 service_set_state(s, SERVICE_EXITED);
2052         else
2053                 service_enter_stop(s, SERVICE_SUCCESS);
2054 }
2055
2056 static void service_enter_start_post(Service *s) {
2057         int r;
2058         assert(s);
2059
2060         service_unwatch_control_pid(s);
2061
2062         if (s->watchdog_usec > 0)
2063                 service_reset_watchdog(s);
2064
2065         s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
2066         if (s->control_command) {
2067                 s->control_command_id = SERVICE_EXEC_START_POST;
2068
2069                 r = service_spawn(s,
2070                                   s->control_command,
2071                                   true,
2072                                   false,
2073                                   !s->permissions_start_only,
2074                                   !s->root_directory_start_only,
2075                                   false,
2076                                   false,
2077                                   true,
2078                                   &s->control_pid);
2079                 if (r < 0)
2080                         goto fail;
2081
2082                 service_set_state(s, SERVICE_START_POST);
2083         } else
2084                 service_enter_running(s, SERVICE_SUCCESS);
2085
2086         return;
2087
2088 fail:
2089         log_warning_unit(UNIT(s)->id,
2090                          "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
2091         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2092 }
2093
2094 static void service_kill_control_processes(Service *s) {
2095         char *p;
2096
2097         if (!UNIT(s)->cgroup_path)
2098                 return;
2099
2100         p = strappenda(UNIT(s)->cgroup_path, "/control");
2101         cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
2102 }
2103
2104 static void service_enter_start(Service *s) {
2105         ExecCommand *c;
2106         pid_t pid;
2107         int r;
2108
2109         assert(s);
2110
2111         assert(s->exec_command[SERVICE_EXEC_START]);
2112         assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2113
2114         service_unwatch_control_pid(s);
2115         service_unwatch_main_pid(s);
2116
2117         /* We want to ensure that nobody leaks processes from
2118          * START_PRE here, so let's go on a killing spree, People
2119          * should not spawn long running processes from START_PRE. */
2120         service_kill_control_processes(s);
2121
2122         if (s->type == SERVICE_FORKING) {
2123                 s->control_command_id = SERVICE_EXEC_START;
2124                 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2125
2126                 s->main_command = NULL;
2127         } else {
2128                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2129                 s->control_command = NULL;
2130
2131                 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2132         }
2133
2134         r = service_spawn(s,
2135                           c,
2136                           s->type == SERVICE_FORKING || s->type == SERVICE_DBUS ||
2137                             s->type == SERVICE_NOTIFY || s->type == SERVICE_ONESHOT,
2138                           true,
2139                           true,
2140                           true,
2141                           true,
2142                           s->notify_access != NOTIFY_NONE,
2143                           false,
2144                           &pid);
2145         if (r < 0)
2146                 goto fail;
2147
2148         if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
2149                 /* For simple services we immediately start
2150                  * the START_POST binaries. */
2151
2152                 service_set_main_pid(s, pid);
2153                 service_enter_start_post(s);
2154
2155         } else  if (s->type == SERVICE_FORKING) {
2156
2157                 /* For forking services we wait until the start
2158                  * process exited. */
2159
2160                 s->control_pid = pid;
2161                 service_set_state(s, SERVICE_START);
2162
2163         } else if (s->type == SERVICE_ONESHOT ||
2164                    s->type == SERVICE_DBUS ||
2165                    s->type == SERVICE_NOTIFY) {
2166
2167                 /* For oneshot services we wait until the start
2168                  * process exited, too, but it is our main process. */
2169
2170                 /* For D-Bus services we know the main pid right away,
2171                  * but wait for the bus name to appear on the
2172                  * bus. Notify services are similar. */
2173
2174                 service_set_main_pid(s, pid);
2175                 service_set_state(s, SERVICE_START);
2176         } else
2177                 assert_not_reached("Unknown service type");
2178
2179         return;
2180
2181 fail:
2182         log_warning_unit(UNIT(s)->id,
2183                          "%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
2184         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2185 }
2186
2187 static void service_enter_start_pre(Service *s) {
2188         int r;
2189
2190         assert(s);
2191
2192         service_unwatch_control_pid(s);
2193
2194         s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
2195         if (s->control_command) {
2196                 /* Before we start anything, let's clear up what might
2197                  * be left from previous runs. */
2198                 service_kill_control_processes(s);
2199
2200                 s->control_command_id = SERVICE_EXEC_START_PRE;
2201
2202                 r = service_spawn(s,
2203                                   s->control_command,
2204                                   true,
2205                                   false,
2206                                   !s->permissions_start_only,
2207                                   !s->root_directory_start_only,
2208                                   true,
2209                                   false,
2210                                   true,
2211                                   &s->control_pid);
2212                 if (r < 0)
2213                         goto fail;
2214
2215                 service_set_state(s, SERVICE_START_PRE);
2216         } else
2217                 service_enter_start(s);
2218
2219         return;
2220
2221 fail:
2222         log_warning_unit(UNIT(s)->id,
2223                          "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
2224         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2225 }
2226
2227 static void service_enter_restart(Service *s) {
2228         int r;
2229         DBusError error;
2230
2231         assert(s);
2232         dbus_error_init(&error);
2233
2234         if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
2235                 /* Don't restart things if we are going down anyway */
2236                 log_info_unit(UNIT(s)->id,
2237                               "Stop job pending for unit, delaying automatic restart.");
2238
2239                 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->restart_usec, &s->timer_watch);
2240                 if (r < 0)
2241                         goto fail;
2242
2243                 return;
2244         }
2245
2246         /* Any units that are bound to this service must also be
2247          * restarted. We use JOB_RESTART (instead of the more obvious
2248          * JOB_START) here so that those dependency jobs will be added
2249          * as well. */
2250         r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
2251         if (r < 0)
2252                 goto fail;
2253
2254         /* Note that we stay in the SERVICE_AUTO_RESTART state here,
2255          * it will be canceled as part of the service_stop() call that
2256          * is executed as part of JOB_RESTART. */
2257
2258         log_debug_unit(UNIT(s)->id,
2259                        "%s scheduled restart job.", UNIT(s)->id);
2260         return;
2261
2262 fail:
2263         log_warning_unit(UNIT(s)->id,
2264                          "%s failed to schedule restart job: %s",
2265                          UNIT(s)->id, bus_error(&error, -r));
2266         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
2267
2268         dbus_error_free(&error);
2269 }
2270
2271 static void service_enter_reload(Service *s) {
2272         int r;
2273
2274         assert(s);
2275
2276         service_unwatch_control_pid(s);
2277
2278         s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
2279         if (s->control_command) {
2280                 s->control_command_id = SERVICE_EXEC_RELOAD;
2281
2282                 r = service_spawn(s,
2283                                   s->control_command,
2284                                   true,
2285                                   false,
2286                                   !s->permissions_start_only,
2287                                   !s->root_directory_start_only,
2288                                   false,
2289                                   false,
2290                                   true,
2291                                   &s->control_pid);
2292                 if (r < 0)
2293                         goto fail;
2294
2295                 service_set_state(s, SERVICE_RELOAD);
2296         } else
2297                 service_enter_running(s, SERVICE_SUCCESS);
2298
2299         return;
2300
2301 fail:
2302         log_warning_unit(UNIT(s)->id,
2303                          "%s failed to run 'reload' task: %s",
2304                          UNIT(s)->id, strerror(-r));
2305         s->reload_result = SERVICE_FAILURE_RESOURCES;
2306         service_enter_running(s, SERVICE_SUCCESS);
2307 }
2308
2309 static void service_run_next_control(Service *s) {
2310         int r;
2311
2312         assert(s);
2313         assert(s->control_command);
2314         assert(s->control_command->command_next);
2315
2316         assert(s->control_command_id != SERVICE_EXEC_START);
2317
2318         s->control_command = s->control_command->command_next;
2319         service_unwatch_control_pid(s);
2320
2321         r = service_spawn(s,
2322                           s->control_command,
2323                           true,
2324                           false,
2325                           !s->permissions_start_only,
2326                           !s->root_directory_start_only,
2327                           s->control_command_id == SERVICE_EXEC_START_PRE ||
2328                           s->control_command_id == SERVICE_EXEC_STOP_POST,
2329                           false,
2330                           true,
2331                           &s->control_pid);
2332         if (r < 0)
2333                 goto fail;
2334
2335         return;
2336
2337 fail:
2338         log_warning_unit(UNIT(s)->id,
2339                          "%s failed to run next control task: %s",
2340                          UNIT(s)->id, strerror(-r));
2341
2342         if (s->state == SERVICE_START_PRE)
2343                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2344         else if (s->state == SERVICE_STOP)
2345                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2346         else if (s->state == SERVICE_STOP_POST)
2347                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2348         else if (s->state == SERVICE_RELOAD) {
2349                 s->reload_result = SERVICE_FAILURE_RESOURCES;
2350                 service_enter_running(s, SERVICE_SUCCESS);
2351         } else
2352                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2353 }
2354
2355 static void service_run_next_main(Service *s) {
2356         pid_t pid;
2357         int r;
2358
2359         assert(s);
2360         assert(s->main_command);
2361         assert(s->main_command->command_next);
2362         assert(s->type == SERVICE_ONESHOT);
2363
2364         s->main_command = s->main_command->command_next;
2365         service_unwatch_main_pid(s);
2366
2367         r = service_spawn(s,
2368                           s->main_command,
2369                           true,
2370                           true,
2371                           true,
2372                           true,
2373                           true,
2374                           s->notify_access != NOTIFY_NONE,
2375                           false,
2376                           &pid);
2377         if (r < 0)
2378                 goto fail;
2379
2380         service_set_main_pid(s, pid);
2381
2382         return;
2383
2384 fail:
2385         log_warning_unit(UNIT(s)->id,
2386                          "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
2387         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2388 }
2389
2390 static int service_start_limit_test(Service *s) {
2391         assert(s);
2392
2393         if (ratelimit_test(&s->start_limit))
2394                 return 0;
2395
2396         switch (s->start_limit_action) {
2397
2398         case SERVICE_START_LIMIT_NONE:
2399                 log_warning_unit(UNIT(s)->id,
2400                                  "%s start request repeated too quickly, refusing to start.",
2401                                  UNIT(s)->id);
2402                 break;
2403
2404         case SERVICE_START_LIMIT_REBOOT: {
2405                 DBusError error;
2406                 int r;
2407
2408                 dbus_error_init(&error);
2409
2410                 log_warning_unit(UNIT(s)->id,
2411                                  "%s start request repeated too quickly, rebooting.", UNIT(s)->id);
2412
2413                 r = manager_add_job_by_name(UNIT(s)->manager, JOB_START,
2414                                             SPECIAL_REBOOT_TARGET, JOB_REPLACE,
2415                                             true, &error, NULL);
2416                 if (r < 0) {
2417                         log_error_unit(UNIT(s)->id,
2418                                        "Failed to reboot: %s.", bus_error(&error, r));
2419                         dbus_error_free(&error);
2420                 }
2421
2422                 break;
2423         }
2424
2425         case SERVICE_START_LIMIT_REBOOT_FORCE:
2426                 log_warning_unit(UNIT(s)->id,
2427                                  "%s start request repeated too quickly, forcibly rebooting.", UNIT(s)->id);
2428                 UNIT(s)->manager->exit_code = MANAGER_REBOOT;
2429                 break;
2430
2431         case SERVICE_START_LIMIT_REBOOT_IMMEDIATE:
2432                 log_warning_unit(UNIT(s)->id,
2433                                  "%s start request repeated too quickly, rebooting immediately.", UNIT(s)->id);
2434                 sync();
2435                 reboot(RB_AUTOBOOT);
2436                 break;
2437
2438         default:
2439                 log_error_unit(UNIT(s)->id,
2440                                "start limit action=%i", s->start_limit_action);
2441                 assert_not_reached("Unknown StartLimitAction.");
2442         }
2443
2444         return -ECANCELED;
2445 }
2446
2447 static int service_start(Unit *u) {
2448         Service *s = SERVICE(u);
2449         int r;
2450
2451         assert(s);
2452
2453         /* We cannot fulfill this request right now, try again later
2454          * please! */
2455         if (s->state == SERVICE_STOP ||
2456             s->state == SERVICE_STOP_SIGTERM ||
2457             s->state == SERVICE_STOP_SIGKILL ||
2458             s->state == SERVICE_STOP_POST ||
2459             s->state == SERVICE_FINAL_SIGTERM ||
2460             s->state == SERVICE_FINAL_SIGKILL)
2461                 return -EAGAIN;
2462
2463         /* Already on it! */
2464         if (s->state == SERVICE_START_PRE ||
2465             s->state == SERVICE_START ||
2466             s->state == SERVICE_START_POST)
2467                 return 0;
2468
2469         /* A service that will be restarted must be stopped first to
2470          * trigger BindsTo and/or OnFailure dependencies. If a user
2471          * does not want to wait for the holdoff time to elapse, the
2472          * service should be manually restarted, not started. We
2473          * simply return EAGAIN here, so that any start jobs stay
2474          * queued, and assume that the auto restart timer will
2475          * eventually trigger the restart. */
2476         if (s->state == SERVICE_AUTO_RESTART)
2477                 return -EAGAIN;
2478
2479         assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
2480
2481         /* Make sure we don't enter a busy loop of some kind. */
2482         r = service_start_limit_test(s);
2483         if (r < 0) {
2484                 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
2485                 return r;
2486         }
2487
2488         s->result = SERVICE_SUCCESS;
2489         s->reload_result = SERVICE_SUCCESS;
2490         s->main_pid_known = false;
2491         s->main_pid_alien = false;
2492         s->forbid_restart = false;
2493
2494         service_enter_start_pre(s);
2495         return 0;
2496 }
2497
2498 static int service_stop(Unit *u) {
2499         Service *s = SERVICE(u);
2500
2501         assert(s);
2502
2503         /* Don't create restart jobs from here. */
2504         s->forbid_restart = true;
2505
2506         /* Already on it */
2507         if (s->state == SERVICE_STOP ||
2508             s->state == SERVICE_STOP_SIGTERM ||
2509             s->state == SERVICE_STOP_SIGKILL ||
2510             s->state == SERVICE_STOP_POST ||
2511             s->state == SERVICE_FINAL_SIGTERM ||
2512             s->state == SERVICE_FINAL_SIGKILL)
2513                 return 0;
2514
2515         /* A restart will be scheduled or is in progress. */
2516         if (s->state == SERVICE_AUTO_RESTART) {
2517                 service_set_state(s, SERVICE_DEAD);
2518                 return 0;
2519         }
2520
2521         /* If there's already something running we go directly into
2522          * kill mode. */
2523         if (s->state == SERVICE_START_PRE ||
2524             s->state == SERVICE_START ||
2525             s->state == SERVICE_START_POST ||
2526             s->state == SERVICE_RELOAD) {
2527                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2528                 return 0;
2529         }
2530
2531         assert(s->state == SERVICE_RUNNING ||
2532                s->state == SERVICE_EXITED);
2533
2534         service_enter_stop(s, SERVICE_SUCCESS);
2535         return 0;
2536 }
2537
2538 static int service_reload(Unit *u) {
2539         Service *s = SERVICE(u);
2540
2541         assert(s);
2542
2543         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2544
2545         service_enter_reload(s);
2546         return 0;
2547 }
2548
2549 _pure_ static bool service_can_reload(Unit *u) {
2550         Service *s = SERVICE(u);
2551
2552         assert(s);
2553
2554         return !!s->exec_command[SERVICE_EXEC_RELOAD];
2555 }
2556
2557 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2558         Service *s = SERVICE(u);
2559
2560         assert(u);
2561         assert(f);
2562         assert(fds);
2563
2564         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2565         unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2566         unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2567
2568         if (s->control_pid > 0)
2569                 unit_serialize_item_format(u, f, "control-pid", "%lu",
2570                                            (unsigned long) s->control_pid);
2571
2572         if (s->main_pid_known && s->main_pid > 0)
2573                 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2574
2575         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2576
2577         if (s->status_text)
2578                 unit_serialize_item(u, f, "status-text", s->status_text);
2579
2580         /* FIXME: There's a minor uncleanliness here: if there are
2581          * multiple commands attached here, we will start from the
2582          * first one again */
2583         if (s->control_command_id >= 0)
2584                 unit_serialize_item(u, f, "control-command",
2585                                     service_exec_command_to_string(s->control_command_id));
2586
2587         if (s->socket_fd >= 0) {
2588                 int copy;
2589
2590                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2591                         return copy;
2592
2593                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2594         }
2595
2596         if (s->main_exec_status.pid > 0) {
2597                 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu",
2598                                            (unsigned long) s->main_exec_status.pid);
2599                 dual_timestamp_serialize(f, "main-exec-status-start",
2600                                          &s->main_exec_status.start_timestamp);
2601                 dual_timestamp_serialize(f, "main-exec-status-exit",
2602                                          &s->main_exec_status.exit_timestamp);
2603
2604                 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2605                         unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
2606                                                    s->main_exec_status.code);
2607                         unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
2608                                                    s->main_exec_status.status);
2609                 }
2610         }
2611         if (dual_timestamp_is_set(&s->watchdog_timestamp))
2612                 dual_timestamp_serialize(f, "watchdog-timestamp",
2613                                          &s->watchdog_timestamp);
2614
2615         if (s->exec_context.tmp_dir)
2616                 unit_serialize_item(u, f, "tmp-dir", s->exec_context.tmp_dir);
2617
2618         if (s->exec_context.var_tmp_dir)
2619                 unit_serialize_item(u, f, "var-tmp-dir", s->exec_context.var_tmp_dir);
2620
2621         if (s->forbid_restart)
2622                 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
2623
2624         return 0;
2625 }
2626
2627 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2628         Service *s = SERVICE(u);
2629
2630         assert(u);
2631         assert(key);
2632         assert(value);
2633         assert(fds);
2634
2635         if (streq(key, "state")) {
2636                 ServiceState state;
2637
2638                 state = service_state_from_string(value);
2639                 if (state < 0)
2640                         log_debug_unit(u->id, "Failed to parse state value %s", value);
2641                 else
2642                         s->deserialized_state = state;
2643         } else if (streq(key, "result")) {
2644                 ServiceResult f;
2645
2646                 f = service_result_from_string(value);
2647                 if (f < 0)
2648                         log_debug_unit(u->id, "Failed to parse result value %s", value);
2649                 else if (f != SERVICE_SUCCESS)
2650                         s->result = f;
2651
2652         } else if (streq(key, "reload-result")) {
2653                 ServiceResult f;
2654
2655                 f = service_result_from_string(value);
2656                 if (f < 0)
2657                         log_debug_unit(u->id, "Failed to parse reload result value %s", value);
2658                 else if (f != SERVICE_SUCCESS)
2659                         s->reload_result = f;
2660
2661         } else if (streq(key, "control-pid")) {
2662                 pid_t pid;
2663
2664                 if (parse_pid(value, &pid) < 0)
2665                         log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
2666                 else
2667                         s->control_pid = pid;
2668         } else if (streq(key, "main-pid")) {
2669                 pid_t pid;
2670
2671                 if (parse_pid(value, &pid) < 0)
2672                         log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
2673                 else {
2674                         service_set_main_pid(s, pid);
2675                         unit_watch_pid(UNIT(s), pid);
2676                 }
2677         } else if (streq(key, "main-pid-known")) {
2678                 int b;
2679
2680                 b = parse_boolean(value);
2681                 if (b < 0)
2682                         log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
2683                 else
2684                         s->main_pid_known = b;
2685         } else if (streq(key, "status-text")) {
2686                 char *t;
2687
2688                 t = strdup(value);
2689                 if (!t)
2690                         log_oom();
2691                 else {
2692                         free(s->status_text);
2693                         s->status_text = t;
2694                 }
2695
2696         } else if (streq(key, "control-command")) {
2697                 ServiceExecCommand id;
2698
2699                 id = service_exec_command_from_string(value);
2700                 if (id < 0)
2701                         log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
2702                 else {
2703                         s->control_command_id = id;
2704                         s->control_command = s->exec_command[id];
2705                 }
2706         } else if (streq(key, "socket-fd")) {
2707                 int fd;
2708
2709                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2710                         log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
2711                 else {
2712
2713                         if (s->socket_fd >= 0)
2714                                 close_nointr_nofail(s->socket_fd);
2715                         s->socket_fd = fdset_remove(fds, fd);
2716                 }
2717         } else if (streq(key, "main-exec-status-pid")) {
2718                 pid_t pid;
2719
2720                 if (parse_pid(value, &pid) < 0)
2721                         log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
2722                 else
2723                         s->main_exec_status.pid = pid;
2724         } else if (streq(key, "main-exec-status-code")) {
2725                 int i;
2726
2727                 if (safe_atoi(value, &i) < 0)
2728                         log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
2729                 else
2730                         s->main_exec_status.code = i;
2731         } else if (streq(key, "main-exec-status-status")) {
2732                 int i;
2733
2734                 if (safe_atoi(value, &i) < 0)
2735                         log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
2736                 else
2737                         s->main_exec_status.status = i;
2738         } else if (streq(key, "main-exec-status-start"))
2739                 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2740         else if (streq(key, "main-exec-status-exit"))
2741                 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2742         else if (streq(key, "watchdog-timestamp"))
2743                 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2744         else if (streq(key, "tmp-dir")) {
2745                 char *t;
2746
2747                 t = strdup(value);
2748                 if (!t)
2749                         return log_oom();
2750
2751                 s->exec_context.tmp_dir = t;
2752         } else if (streq(key, "var-tmp-dir")) {
2753                 char *t;
2754
2755                 t = strdup(value);
2756                 if (!t)
2757                         return log_oom();
2758
2759                 s->exec_context.var_tmp_dir = t;
2760         } else if (streq(key, "forbid-restart")) {
2761                 int b;
2762
2763                 b = parse_boolean(value);
2764                 if (b < 0)
2765                         log_debug_unit(u->id, "Failed to parse forbid-restart value %s", value);
2766                 else
2767                         s->forbid_restart = b;
2768         } else
2769                 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
2770
2771         return 0;
2772 }
2773
2774 _pure_ static UnitActiveState service_active_state(Unit *u) {
2775         const UnitActiveState *table;
2776
2777         assert(u);
2778
2779         table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2780
2781         return table[SERVICE(u)->state];
2782 }
2783
2784 static const char *service_sub_state_to_string(Unit *u) {
2785         assert(u);
2786
2787         return service_state_to_string(SERVICE(u)->state);
2788 }
2789
2790 static bool service_check_gc(Unit *u) {
2791         Service *s = SERVICE(u);
2792
2793         assert(s);
2794
2795         /* Never clean up services that still have a process around,
2796          * even if the service is formally dead. */
2797         if (cgroup_good(s) > 0 ||
2798             main_pid_good(s) > 0 ||
2799             control_pid_good(s) > 0)
2800                 return true;
2801
2802 #ifdef HAVE_SYSV_COMPAT
2803         if (s->is_sysv)
2804                 return true;
2805 #endif
2806
2807         return false;
2808 }
2809
2810 _pure_ static bool service_check_snapshot(Unit *u) {
2811         Service *s = SERVICE(u);
2812
2813         assert(s);
2814
2815         return !s->got_socket_fd;
2816 }
2817
2818 static int service_retry_pid_file(Service *s) {
2819         int r;
2820
2821         assert(s->pid_file);
2822         assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2823
2824         r = service_load_pid_file(s, false);
2825         if (r < 0)
2826                 return r;
2827
2828         service_unwatch_pid_file(s);
2829
2830         service_enter_running(s, SERVICE_SUCCESS);
2831         return 0;
2832 }
2833
2834 static int service_watch_pid_file(Service *s) {
2835         int r;
2836
2837         log_debug_unit(UNIT(s)->id,
2838                        "Setting watch for %s's PID file %s",
2839                        UNIT(s)->id, s->pid_file_pathspec->path);
2840         r = path_spec_watch(s->pid_file_pathspec, UNIT(s));
2841         if (r < 0)
2842                 goto fail;
2843
2844         /* the pidfile might have appeared just before we set the watch */
2845         log_debug_unit(UNIT(s)->id,
2846                        "Trying to read %s's PID file %s in case it changed",
2847                        UNIT(s)->id, s->pid_file_pathspec->path);
2848         service_retry_pid_file(s);
2849
2850         return 0;
2851 fail:
2852         log_error_unit(UNIT(s)->id,
2853                        "Failed to set a watch for %s's PID file %s: %s",
2854                        UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2855         service_unwatch_pid_file(s);
2856         return r;
2857 }
2858
2859 static int service_demand_pid_file(Service *s) {
2860         PathSpec *ps;
2861
2862         assert(s->pid_file);
2863         assert(!s->pid_file_pathspec);
2864
2865         ps = new0(PathSpec, 1);
2866         if (!ps)
2867                 return -ENOMEM;
2868
2869         ps->path = strdup(s->pid_file);
2870         if (!ps->path) {
2871                 free(ps);
2872                 return -ENOMEM;
2873         }
2874
2875         path_kill_slashes(ps->path);
2876
2877         /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2878          * keep their PID file open all the time. */
2879         ps->type = PATH_MODIFIED;
2880         ps->inotify_fd = -1;
2881
2882         s->pid_file_pathspec = ps;
2883
2884         return service_watch_pid_file(s);
2885 }
2886
2887 static void service_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
2888         Service *s = SERVICE(u);
2889
2890         assert(s);
2891         assert(fd >= 0);
2892         assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2893         assert(s->pid_file_pathspec);
2894         assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2895
2896         log_debug_unit(u->id, "inotify event for %s", u->id);
2897
2898         if (path_spec_fd_event(s->pid_file_pathspec, events) < 0)
2899                 goto fail;
2900
2901         if (service_retry_pid_file(s) == 0)
2902                 return;
2903
2904         if (service_watch_pid_file(s) < 0)
2905                 goto fail;
2906
2907         return;
2908 fail:
2909         service_unwatch_pid_file(s);
2910         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2911 }
2912
2913 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2914         Service *s = SERVICE(u);
2915         ServiceResult f;
2916
2917         assert(s);
2918         assert(pid >= 0);
2919
2920         if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2921                                      is_clean_exit_lsb(code, status, &s->success_status))
2922                 f = SERVICE_SUCCESS;
2923         else if (code == CLD_EXITED)
2924                 f = SERVICE_FAILURE_EXIT_CODE;
2925         else if (code == CLD_KILLED)
2926                 f = SERVICE_FAILURE_SIGNAL;
2927         else if (code == CLD_DUMPED)
2928                 f = SERVICE_FAILURE_CORE_DUMP;
2929         else
2930                 assert_not_reached("Unknown code");
2931
2932         if (s->main_pid == pid) {
2933                 /* Forking services may occasionally move to a new PID.
2934                  * As long as they update the PID file before exiting the old
2935                  * PID, they're fine. */
2936                 if (service_load_pid_file(s, false) == 0)
2937                         return;
2938
2939                 s->main_pid = 0;
2940                 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2941
2942                 if (s->main_command) {
2943                         /* If this is not a forking service than the
2944                          * main process got started and hence we copy
2945                          * the exit status so that it is recorded both
2946                          * as main and as control process exit
2947                          * status */
2948
2949                         s->main_command->exec_status = s->main_exec_status;
2950
2951                         if (s->main_command->ignore)
2952                                 f = SERVICE_SUCCESS;
2953                 } else if (s->exec_command[SERVICE_EXEC_START]) {
2954
2955                         /* If this is a forked process, then we should
2956                          * ignore the return value if this was
2957                          * configured for the starter process */
2958
2959                         if (s->exec_command[SERVICE_EXEC_START]->ignore)
2960                                 f = SERVICE_SUCCESS;
2961                 }
2962
2963                 log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2964                            u->id,
2965                            "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
2966                                   u->id, sigchld_code_to_string(code), status,
2967                                   strna(code == CLD_EXITED
2968                                         ? exit_status_to_string(status, EXIT_STATUS_FULL)
2969                                         : signal_to_string(status)),
2970                            "EXIT_CODE=%s", sigchld_code_to_string(code),
2971                            "EXIT_STATUS=%i", status,
2972                            NULL);
2973
2974                 if (f != SERVICE_SUCCESS)
2975                         s->result = f;
2976
2977                 if (s->main_command &&
2978                     s->main_command->command_next &&
2979                     f == SERVICE_SUCCESS) {
2980
2981                         /* There is another command to *
2982                          * execute, so let's do that. */
2983
2984                         log_debug_unit(u->id,
2985                                        "%s running next main command for state %s",
2986                                        u->id, service_state_to_string(s->state));
2987                         service_run_next_main(s);
2988
2989                 } else {
2990
2991                         /* The service exited, so the service is officially
2992                          * gone. */
2993                         s->main_command = NULL;
2994
2995                         switch (s->state) {
2996
2997                         case SERVICE_START_POST:
2998                         case SERVICE_RELOAD:
2999                         case SERVICE_STOP:
3000                                 /* Need to wait until the operation is
3001                                  * done */
3002                                 break;
3003
3004                         case SERVICE_START:
3005                                 if (s->type == SERVICE_ONESHOT) {
3006                                         /* This was our main goal, so let's go on */
3007                                         if (f == SERVICE_SUCCESS)
3008                                                 service_enter_start_post(s);
3009                                         else
3010                                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3011                                         break;
3012                                 }
3013
3014                                 /* Fall through */
3015
3016                         case SERVICE_RUNNING:
3017                                 service_enter_running(s, f);
3018                                 break;
3019
3020                         case SERVICE_STOP_SIGTERM:
3021                         case SERVICE_STOP_SIGKILL:
3022
3023                                 if (!control_pid_good(s))
3024                                         service_enter_stop_post(s, f);
3025
3026                                 /* If there is still a control process, wait for that first */
3027                                 break;
3028
3029                         default:
3030                                 assert_not_reached("Uh, main process died at wrong time.");
3031                         }
3032                 }
3033
3034         } else if (s->control_pid == pid) {
3035                 s->control_pid = 0;
3036
3037                 if (s->control_command) {
3038                         exec_status_exit(&s->control_command->exec_status,
3039                                          &s->exec_context, pid, code, status);
3040
3041                         if (s->control_command->ignore)
3042                                 f = SERVICE_SUCCESS;
3043                 }
3044
3045                 log_full_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
3046                               "%s: control process exited, code=%s status=%i",
3047                               u->id, sigchld_code_to_string(code), status);
3048
3049                 if (f != SERVICE_SUCCESS)
3050                         s->result = f;
3051
3052                 /* Immediately get rid of the cgroup, so that the
3053                  * kernel doesn't delay the cgroup empty messages for
3054                  * the service cgroup any longer than necessary */
3055                 service_kill_control_processes(s);
3056
3057                 if (s->control_command &&
3058                     s->control_command->command_next &&
3059                     f == SERVICE_SUCCESS) {
3060
3061                         /* There is another command to *
3062                          * execute, so let's do that. */
3063
3064                         log_debug_unit(u->id,
3065                                        "%s running next control command for state %s",
3066                                        u->id, service_state_to_string(s->state));
3067                         service_run_next_control(s);
3068
3069                 } else {
3070                         /* No further commands for this step, so let's
3071                          * figure out what to do next */
3072
3073                         s->control_command = NULL;
3074                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
3075
3076                         log_debug_unit(u->id,
3077                                        "%s got final SIGCHLD for state %s",
3078                                        u->id, service_state_to_string(s->state));
3079
3080                         switch (s->state) {
3081
3082                         case SERVICE_START_PRE:
3083                                 if (f == SERVICE_SUCCESS)
3084                                         service_enter_start(s);
3085                                 else
3086                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3087                                 break;
3088
3089                         case SERVICE_START:
3090                                 if (s->type != SERVICE_FORKING)
3091                                         /* Maybe spurious event due to a reload that changed the type? */
3092                                         break;
3093
3094                                 if (f != SERVICE_SUCCESS) {
3095                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3096                                         break;
3097                                 }
3098
3099                                 if (s->pid_file) {
3100                                         bool has_start_post;
3101                                         int r;
3102
3103                                         /* Let's try to load the pid file here if we can.
3104                                          * The PID file might actually be created by a START_POST
3105                                          * script. In that case don't worry if the loading fails. */
3106
3107                                         has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
3108                                         r = service_load_pid_file(s, !has_start_post);
3109                                         if (!has_start_post && r < 0) {
3110                                                 r = service_demand_pid_file(s);
3111                                                 if (r < 0 || !cgroup_good(s))
3112                                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3113                                                 break;
3114                                         }
3115                                 } else
3116                                         service_search_main_pid(s);
3117
3118                                 service_enter_start_post(s);
3119                                 break;
3120
3121                         case SERVICE_START_POST:
3122                                 if (f != SERVICE_SUCCESS) {
3123                                         service_enter_stop(s, f);
3124                                         break;
3125                                 }
3126
3127                                 if (s->pid_file) {
3128                                         int r;
3129
3130                                         r = service_load_pid_file(s, true);
3131                                         if (r < 0) {
3132                                                 r = service_demand_pid_file(s);
3133                                                 if (r < 0 || !cgroup_good(s))
3134                                                         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3135                                                 break;
3136                                         }
3137                                 } else
3138                                         service_search_main_pid(s);
3139
3140                                 service_enter_running(s, SERVICE_SUCCESS);
3141                                 break;
3142
3143                         case SERVICE_RELOAD:
3144                                 if (f == SERVICE_SUCCESS) {
3145                                         service_load_pid_file(s, true);
3146                                         service_search_main_pid(s);
3147                                 }
3148
3149                                 s->reload_result = f;
3150                                 service_enter_running(s, SERVICE_SUCCESS);
3151                                 break;
3152
3153                         case SERVICE_STOP:
3154                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3155                                 break;
3156
3157                         case SERVICE_STOP_SIGTERM:
3158                         case SERVICE_STOP_SIGKILL:
3159                                 if (main_pid_good(s) <= 0)
3160                                         service_enter_stop_post(s, f);
3161
3162                                 /* If there is still a service
3163                                  * process around, wait until
3164                                  * that one quit, too */
3165                                 break;
3166
3167                         case SERVICE_STOP_POST:
3168                         case SERVICE_FINAL_SIGTERM:
3169                         case SERVICE_FINAL_SIGKILL:
3170                                 service_enter_dead(s, f, true);
3171                                 break;
3172
3173                         default:
3174                                 assert_not_reached("Uh, control process died at wrong time.");
3175                         }
3176                 }
3177         }
3178
3179         /* Notify clients about changed exit status */
3180         unit_add_to_dbus_queue(u);
3181 }
3182
3183 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
3184         Service *s = SERVICE(u);
3185
3186         assert(s);
3187         assert(elapsed == 1);
3188
3189         if (w == &s->watchdog_watch) {
3190                 service_handle_watchdog(s);
3191                 return;
3192         }
3193
3194         assert(w == &s->timer_watch);
3195
3196         switch (s->state) {
3197
3198         case SERVICE_START_PRE:
3199         case SERVICE_START:
3200                 log_warning_unit(u->id,
3201                                  "%s operation timed out. Terminating.", u->id);
3202                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3203                 break;
3204
3205         case SERVICE_START_POST:
3206                 log_warning_unit(u->id,
3207                                  "%s operation timed out. Stopping.", u->id);
3208                 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
3209                 break;
3210
3211         case SERVICE_RELOAD:
3212                 log_warning_unit(u->id,
3213                                  "%s operation timed out. Stopping.", u->id);
3214                 s->reload_result = SERVICE_FAILURE_TIMEOUT;
3215                 service_enter_running(s, SERVICE_SUCCESS);
3216                 break;
3217
3218         case SERVICE_STOP:
3219                 log_warning_unit(u->id,
3220                                  "%s stopping timed out. Terminating.", u->id);
3221                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3222                 break;
3223
3224         case SERVICE_STOP_SIGTERM:
3225                 if (s->kill_context.send_sigkill) {
3226                         log_warning_unit(u->id,
3227                                          "%s stopping timed out. Killing.", u->id);
3228                         service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3229                 } else {
3230                         log_warning_unit(u->id,
3231                                          "%s stopping timed out. Skipping SIGKILL.", u->id);
3232                         service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3233                 }
3234
3235                 break;
3236
3237         case SERVICE_STOP_SIGKILL:
3238                 /* Uh, we sent a SIGKILL and it is still not gone?
3239                  * Must be something we cannot kill, so let's just be
3240                  * weirded out and continue */
3241
3242                 log_warning_unit(u->id,
3243                                  "%s still around after SIGKILL. Ignoring.", u->id);
3244                 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3245                 break;
3246
3247         case SERVICE_STOP_POST:
3248                 log_warning_unit(u->id,
3249                                  "%s stopping timed out (2). Terminating.", u->id);
3250                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3251                 break;
3252
3253         case SERVICE_FINAL_SIGTERM:
3254                 if (s->kill_context.send_sigkill) {
3255                         log_warning_unit(u->id,
3256                                          "%s stopping timed out (2). Killing.", u->id);
3257                         service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3258                 } else {
3259                         log_warning_unit(u->id,
3260                                          "%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.",
3261                                          u->id);
3262                         service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3263                 }
3264
3265                 break;
3266
3267         case SERVICE_FINAL_SIGKILL:
3268                 log_warning_unit(u->id,
3269                                  "%s still around after SIGKILL (2). Entering failed mode.", u->id);
3270                 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
3271                 break;
3272
3273         case SERVICE_AUTO_RESTART:
3274                 log_info_unit(u->id,
3275                               "%s holdoff time over, scheduling restart.", u->id);
3276                 service_enter_restart(s);
3277                 break;
3278
3279         default:
3280                 assert_not_reached("Timeout at wrong time.");
3281         }
3282 }
3283
3284 static void service_notify_cgroup_empty_event(Unit *u) {
3285         Service *s = SERVICE(u);
3286
3287         assert(u);
3288
3289         log_debug_unit(u->id, "%s: cgroup is empty", u->id);
3290
3291         switch (s->state) {
3292
3293                 /* Waiting for SIGCHLD is usually more interesting,
3294                  * because it includes return codes/signals. Which is
3295                  * why we ignore the cgroup events for most cases,
3296                  * except when we don't know pid which to expect the
3297                  * SIGCHLD for. */
3298
3299         case SERVICE_START:
3300         case SERVICE_START_POST:
3301                 /* If we were hoping for the daemon to write its PID file,
3302                  * we can give up now. */
3303                 if (s->pid_file_pathspec) {
3304                         log_warning_unit(u->id,
3305                                          "%s never wrote its PID file. Failing.", UNIT(s)->id);
3306                         service_unwatch_pid_file(s);
3307                         if (s->state == SERVICE_START)
3308                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3309                         else
3310                                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3311                 }
3312                 break;
3313
3314         case SERVICE_RUNNING:
3315                 /* service_enter_running() will figure out what to do */
3316                 service_enter_running(s, SERVICE_SUCCESS);
3317                 break;
3318
3319         case SERVICE_STOP_SIGTERM:
3320         case SERVICE_STOP_SIGKILL:
3321
3322                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3323                         service_enter_stop_post(s, SERVICE_SUCCESS);
3324
3325                 break;
3326
3327         case SERVICE_FINAL_SIGTERM:
3328         case SERVICE_FINAL_SIGKILL:
3329                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3330                         service_enter_dead(s, SERVICE_SUCCESS, true);
3331
3332                 break;
3333
3334         default:
3335                 ;
3336         }
3337 }
3338
3339 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
3340         Service *s = SERVICE(u);
3341         const char *e;
3342
3343         assert(u);
3344
3345         if (s->notify_access == NOTIFY_NONE) {
3346                 log_warning_unit(u->id,
3347                                  "%s: Got notification message from PID %lu, but reception is disabled.",
3348                                  u->id, (unsigned long) pid);
3349                 return;
3350         }
3351
3352         if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3353                 log_warning_unit(u->id,
3354                                  "%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
3355                                  u->id, (unsigned long) pid, (unsigned long) s->main_pid);
3356                 return;
3357         }
3358
3359         log_debug_unit(u->id,
3360                        "%s: Got message", u->id);
3361
3362         /* Interpret MAINPID= */
3363         if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3364             (s->state == SERVICE_START ||
3365              s->state == SERVICE_START_POST ||
3366              s->state == SERVICE_RUNNING ||
3367              s->state == SERVICE_RELOAD)) {
3368
3369                 if (parse_pid(e + 8, &pid) < 0)
3370                         log_warning_unit(u->id,
3371                                          "Failed to parse notification message %s", e);
3372                 else {
3373                         log_debug_unit(u->id,
3374                                        "%s: got %s", u->id, e);
3375                         service_set_main_pid(s, pid);
3376                         unit_watch_pid(UNIT(s), pid);
3377                 }
3378         }
3379
3380         /* Interpret READY= */
3381         if (s->type == SERVICE_NOTIFY &&
3382             s->state == SERVICE_START &&
3383             strv_find(tags, "READY=1")) {
3384                 log_debug_unit(u->id,
3385                                "%s: got READY=1", u->id);
3386
3387                 service_enter_start_post(s);
3388         }
3389
3390         /* Interpret STATUS= */
3391         e = strv_find_prefix(tags, "STATUS=");
3392         if (e) {
3393                 char *t;
3394
3395                 if (e[7]) {
3396
3397                         if (!utf8_is_valid(e+7)) {
3398                                 log_warning_unit(u->id,
3399                                                  "Status message in notification is not UTF-8 clean.");
3400                                 return;
3401                         }
3402
3403                         t = strdup(e+7);
3404                         if (!t) {
3405                                 log_error_unit(u->id,
3406                                                "Failed to allocate string.");
3407                                 return;
3408                         }
3409
3410                         log_debug_unit(u->id,
3411                                        "%s: got %s", u->id, e);
3412
3413                         free(s->status_text);
3414                         s->status_text = t;
3415                 } else {
3416                         free(s->status_text);
3417                         s->status_text = NULL;
3418                 }
3419
3420         }
3421         if (strv_find(tags, "WATCHDOG=1")) {
3422                 log_debug_unit(u->id,
3423                                "%s: got WATCHDOG=1", u->id);
3424                 if (dual_timestamp_is_set(&s->watchdog_timestamp))
3425                         service_reset_watchdog(s);
3426         }
3427
3428         /* Notify clients about changed status or main pid */
3429         unit_add_to_dbus_queue(u);
3430 }
3431
3432 #ifdef HAVE_SYSV_COMPAT
3433
3434 static int service_enumerate(Manager *m) {
3435         char **p;
3436         unsigned i;
3437         _cleanup_closedir_ DIR *d = NULL;
3438         _cleanup_free_ char *path = NULL, *fpath = NULL, *name = NULL;
3439         Set *runlevel_services[ELEMENTSOF(rcnd_table)] = {};
3440         _cleanup_set_free_ Set *shutdown_services = NULL;
3441         Unit *service;
3442         Iterator j;
3443         int r;
3444
3445         assert(m);
3446
3447         if (m->running_as != SYSTEMD_SYSTEM)
3448                 return 0;
3449
3450         STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3451                 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3452                         struct dirent *de;
3453
3454                         free(path);
3455                         path = strjoin(*p, "/", rcnd_table[i].path, NULL);
3456                         if (!path) {
3457                                 r = -ENOMEM;
3458                                 goto finish;
3459                         }
3460
3461                         if (d)
3462                                 closedir(d);
3463
3464                         d = opendir(path);
3465                         if (!d) {
3466                                 if (errno != ENOENT)
3467                                         log_warning("opendir(%s) failed: %s", path, strerror(errno));
3468
3469                                 continue;
3470                         }
3471
3472                         while ((de = readdir(d))) {
3473                                 int a, b;
3474
3475                                 if (ignore_file(de->d_name))
3476                                         continue;
3477
3478                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3479                                         continue;
3480
3481                                 if (strlen(de->d_name) < 4)
3482                                         continue;
3483
3484                                 a = undecchar(de->d_name[1]);
3485                                 b = undecchar(de->d_name[2]);
3486
3487                                 if (a < 0 || b < 0)
3488                                         continue;
3489
3490                                 free(fpath);
3491                                 fpath = strjoin(path, "/", de->d_name, NULL);
3492                                 if (!fpath) {
3493                                         r = -ENOMEM;
3494                                         goto finish;
3495                                 }
3496
3497                                 if (access(fpath, X_OK) < 0) {
3498
3499                                         if (errno != ENOENT)
3500                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3501
3502                                         continue;
3503                                 }
3504
3505                                 free(name);
3506                                 name = sysv_translate_name(de->d_name + 3);
3507                                 if (!name) {
3508                                         r = log_oom();
3509                                         goto finish;
3510                                 }
3511
3512                                 r = manager_load_unit_prepare(m, name, NULL, NULL, &service);
3513                                 if (r < 0) {
3514                                         log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3515                                         continue;
3516                                 }
3517
3518                                 if (de->d_name[0] == 'S')  {
3519
3520                                         if (rcnd_table[i].type == RUNLEVEL_UP) {
3521                                                 SERVICE(service)->sysv_start_priority_from_rcnd =
3522                                                         MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3523
3524                                                 SERVICE(service)->sysv_enabled = true;
3525                                         }
3526
3527                                         r = set_ensure_allocated(&runlevel_services[i],
3528                                                                  trivial_hash_func, trivial_compare_func);
3529                                         if (r < 0)
3530                                                 goto finish;
3531
3532                                         r = set_put(runlevel_services[i], service);
3533                                         if (r < 0)
3534                                                 goto finish;
3535
3536                                 } else if (de->d_name[0] == 'K' &&
3537                                            (rcnd_table[i].type == RUNLEVEL_DOWN)) {
3538
3539                                         r = set_ensure_allocated(&shutdown_services,
3540                                                                  trivial_hash_func, trivial_compare_func);
3541                                         if (r < 0)
3542                                                 goto finish;
3543
3544                                         r = set_put(shutdown_services, service);
3545                                         if (r < 0)
3546                                                 goto finish;
3547                                 }
3548                         }
3549                 }
3550
3551         /* Now we loaded all stubs and are aware of the lowest
3552         start-up priority for all services, not let's actually load
3553         the services, this will also tell us which services are
3554         actually native now */
3555         manager_dispatch_load_queue(m);
3556
3557         /* If this is a native service, rely on native ways to pull in
3558          * a service, don't pull it in via sysv rcN.d links. */
3559         for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3560                 SET_FOREACH(service, runlevel_services[i], j) {
3561                         service = unit_follow_merge(service);
3562
3563                         if (service->fragment_path)
3564                                 continue;
3565
3566                         r = unit_add_two_dependencies_by_name_inverse(
3567                                 service, UNIT_AFTER, UNIT_WANTS,
3568                                 rcnd_table[i].target, NULL, true);
3569                         if (r < 0)
3570                                 goto finish;
3571                 }
3572
3573         /* We honour K links only for halt/reboot. For the normal
3574          * runlevels we assume the stop jobs will be implicitly added
3575          * by the core logic. Also, we don't really distinguish here
3576          * between the runlevels 0 and 6 and just add them to the
3577          * special shutdown target. */
3578         SET_FOREACH(service, shutdown_services, j) {
3579                 service = unit_follow_merge(service);
3580
3581                 if (service->fragment_path)
3582                         continue;
3583
3584                 r = unit_add_two_dependencies_by_name(
3585                         service, UNIT_BEFORE, UNIT_CONFLICTS,
3586                         SPECIAL_SHUTDOWN_TARGET, NULL, true);
3587                 if (r < 0)
3588                         goto finish;
3589         }
3590
3591         r = 0;
3592
3593 finish:
3594
3595         for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3596                 set_free(runlevel_services[i]);
3597
3598         return r;
3599 }
3600 #endif
3601
3602 static void service_bus_name_owner_change(
3603                 Unit *u,
3604                 const char *name,
3605                 const char *old_owner,
3606                 const char *new_owner) {
3607
3608         Service *s = SERVICE(u);
3609
3610         assert(s);
3611         assert(name);
3612
3613         assert(streq(s->bus_name, name));
3614         assert(old_owner || new_owner);
3615
3616         if (old_owner && new_owner)
3617                 log_debug_unit(u->id,
3618                                "%s's D-Bus name %s changed owner from %s to %s",
3619                                u->id, name, old_owner, new_owner);
3620         else if (old_owner)
3621                 log_debug_unit(u->id,
3622                                "%s's D-Bus name %s no longer registered by %s",
3623                                u->id, name, old_owner);
3624         else
3625                 log_debug_unit(u->id,
3626                                "%s's D-Bus name %s now registered by %s",
3627                                u->id, name, new_owner);
3628
3629         s->bus_name_good = !!new_owner;
3630
3631         if (s->type == SERVICE_DBUS) {
3632
3633                 /* service_enter_running() will figure out what to
3634                  * do */
3635                 if (s->state == SERVICE_RUNNING)
3636                         service_enter_running(s, SERVICE_SUCCESS);
3637                 else if (s->state == SERVICE_START && new_owner)
3638                         service_enter_start_post(s);
3639
3640         } else if (new_owner &&
3641                    s->main_pid <= 0 &&
3642                    (s->state == SERVICE_START ||
3643                     s->state == SERVICE_START_POST ||
3644                     s->state == SERVICE_RUNNING ||
3645                     s->state == SERVICE_RELOAD)) {
3646
3647                 /* Try to acquire PID from bus service */
3648                 log_debug_unit(u->id,
3649                                "Trying to acquire PID from D-Bus name...");
3650
3651                 bus_query_pid(u->manager, name);
3652         }
3653 }
3654
3655 static void service_bus_query_pid_done(
3656                 Unit *u,
3657                 const char *name,
3658                 pid_t pid) {
3659
3660         Service *s = SERVICE(u);
3661
3662         assert(s);
3663         assert(name);
3664
3665         log_debug_unit(u->id,
3666                        "%s's D-Bus name %s is now owned by process %u",
3667                        u->id, name, (unsigned) pid);
3668
3669         if (s->main_pid <= 0 &&
3670             (s->state == SERVICE_START ||
3671              s->state == SERVICE_START_POST ||
3672              s->state == SERVICE_RUNNING ||
3673              s->state == SERVICE_RELOAD)){
3674                 service_set_main_pid(s, pid);
3675                 unit_watch_pid(UNIT(s), pid);
3676         }
3677 }
3678
3679 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3680
3681         assert(s);
3682         assert(fd >= 0);
3683
3684         /* This is called by the socket code when instantiating a new
3685          * service for a stream socket and the socket needs to be
3686          * configured. */
3687
3688         if (UNIT(s)->load_state != UNIT_LOADED)
3689                 return -EINVAL;
3690
3691         if (s->socket_fd >= 0)
3692                 return -EBUSY;
3693
3694         if (s->state != SERVICE_DEAD)
3695                 return -EAGAIN;
3696
3697         s->socket_fd = fd;
3698         s->got_socket_fd = true;
3699
3700         unit_ref_set(&s->accept_socket, UNIT(sock));
3701
3702         return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3703 }
3704
3705 static void service_reset_failed(Unit *u) {
3706         Service *s = SERVICE(u);
3707
3708         assert(s);
3709
3710         if (s->state == SERVICE_FAILED)
3711                 service_set_state(s, SERVICE_DEAD);
3712
3713         s->result = SERVICE_SUCCESS;
3714         s->reload_result = SERVICE_SUCCESS;
3715
3716         RATELIMIT_RESET(s->start_limit);
3717 }
3718
3719 static int service_kill(Unit *u, KillWho who, int signo, DBusError *error) {
3720         Service *s = SERVICE(u);
3721
3722         return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
3723 }
3724
3725 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3726         [SERVICE_DEAD] = "dead",
3727         [SERVICE_START_PRE] = "start-pre",
3728         [SERVICE_START] = "start",
3729         [SERVICE_START_POST] = "start-post",
3730         [SERVICE_RUNNING] = "running",
3731         [SERVICE_EXITED] = "exited",
3732         [SERVICE_RELOAD] = "reload",
3733         [SERVICE_STOP] = "stop",
3734         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3735         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3736         [SERVICE_STOP_POST] = "stop-post",
3737         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3738         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3739         [SERVICE_FAILED] = "failed",
3740         [SERVICE_AUTO_RESTART] = "auto-restart",
3741 };
3742
3743 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3744
3745 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3746         [SERVICE_RESTART_NO] = "no",
3747         [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3748         [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3749         [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
3750         [SERVICE_RESTART_ON_ABORT] = "on-abort",
3751         [SERVICE_RESTART_ALWAYS] = "always"
3752 };
3753
3754 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3755
3756 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3757         [SERVICE_SIMPLE] = "simple",
3758         [SERVICE_FORKING] = "forking",
3759         [SERVICE_ONESHOT] = "oneshot",
3760         [SERVICE_DBUS] = "dbus",
3761         [SERVICE_NOTIFY] = "notify",
3762         [SERVICE_IDLE] = "idle"
3763 };
3764
3765 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3766
3767 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3768         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3769         [SERVICE_EXEC_START] = "ExecStart",
3770         [SERVICE_EXEC_START_POST] = "ExecStartPost",
3771         [SERVICE_EXEC_RELOAD] = "ExecReload",
3772         [SERVICE_EXEC_STOP] = "ExecStop",
3773         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3774 };
3775
3776 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3777
3778 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3779         [NOTIFY_NONE] = "none",
3780         [NOTIFY_MAIN] = "main",
3781         [NOTIFY_ALL] = "all"
3782 };
3783
3784 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3785
3786 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3787         [SERVICE_SUCCESS] = "success",
3788         [SERVICE_FAILURE_RESOURCES] = "resources",
3789         [SERVICE_FAILURE_TIMEOUT] = "timeout",
3790         [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3791         [SERVICE_FAILURE_SIGNAL] = "signal",
3792         [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3793         [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3794         [SERVICE_FAILURE_START_LIMIT] = "start-limit"
3795 };
3796
3797 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3798
3799 static const char* const start_limit_action_table[_SERVICE_START_LIMIT_MAX] = {
3800         [SERVICE_START_LIMIT_NONE] = "none",
3801         [SERVICE_START_LIMIT_REBOOT] = "reboot",
3802         [SERVICE_START_LIMIT_REBOOT_FORCE] = "reboot-force",
3803         [SERVICE_START_LIMIT_REBOOT_IMMEDIATE] = "reboot-immediate"
3804 };
3805 DEFINE_STRING_TABLE_LOOKUP(start_limit_action, StartLimitAction);
3806
3807 const UnitVTable service_vtable = {
3808         .object_size = sizeof(Service),
3809
3810         .sections =
3811                 "Unit\0"
3812                 "Service\0"
3813                 "Install\0",
3814
3815         .private_section = "Service",
3816         .exec_context_offset = offsetof(Service, exec_context),
3817         .cgroup_context_offset = offsetof(Service, cgroup_context),
3818
3819         .init = service_init,
3820         .done = service_done,
3821         .load = service_load,
3822
3823         .coldplug = service_coldplug,
3824
3825         .dump = service_dump,
3826
3827         .start = service_start,
3828         .stop = service_stop,
3829         .reload = service_reload,
3830
3831         .can_reload = service_can_reload,
3832
3833         .kill = service_kill,
3834
3835         .serialize = service_serialize,
3836         .deserialize_item = service_deserialize_item,
3837
3838         .active_state = service_active_state,
3839         .sub_state_to_string = service_sub_state_to_string,
3840
3841         .check_gc = service_check_gc,
3842         .check_snapshot = service_check_snapshot,
3843
3844         .sigchld_event = service_sigchld_event,
3845         .timer_event = service_timer_event,
3846         .fd_event = service_fd_event,
3847
3848         .reset_failed = service_reset_failed,
3849
3850         .notify_cgroup_empty = service_notify_cgroup_empty_event,
3851         .notify_message = service_notify_message,
3852
3853         .bus_name_owner_change = service_bus_name_owner_change,
3854         .bus_query_pid_done = service_bus_query_pid_done,
3855
3856         .bus_interface = "org.freedesktop.systemd1.Service",
3857         .bus_message_handler = bus_service_message_handler,
3858         .bus_invalidating_properties =  bus_service_invalidating_properties,
3859         .bus_set_property = bus_service_set_property,
3860         .bus_commit_properties = bus_service_commit_properties,
3861
3862         .can_transient = true,
3863
3864 #ifdef HAVE_SYSV_COMPAT
3865         .enumerate = service_enumerate,
3866 #endif
3867         .status_message_formats = {
3868                 .starting_stopping = {
3869                         [0] = "Starting %s...",
3870                         [1] = "Stopping %s...",
3871                 },
3872                 .finished_start_job = {
3873                         [JOB_DONE]       = "Started %s.",
3874                         [JOB_FAILED]     = "Failed to start %s.",
3875                         [JOB_DEPENDENCY] = "Dependency failed for %s.",
3876                         [JOB_TIMEOUT]    = "Timed out starting %s.",
3877                 },
3878                 .finished_stop_job = {
3879                         [JOB_DONE]       = "Stopped %s.",
3880                         [JOB_FAILED]     = "Stopped (with error) %s.",
3881                         [JOB_TIMEOUT]    = "Timed out stopping %s.",
3882                 },
3883         },
3884 };