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