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