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