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