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