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