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