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