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