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