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