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