chiark / gitweb /
sysv: rework suse/debian special bootup runlevel handling
[elogind.git] / service.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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
36 #define COMMENTS "#;\n"
37 #define NEWLINES "\n\r"
38 #define LINE_MAX 4096
39
40 typedef enum RunlevelType {
41         RUNLEVEL_UP,
42         RUNLEVEL_DOWN,
43         RUNLEVEL_BASIC
44 } RunlevelType;
45
46 static const struct {
47         const char *path;
48         const char *target;
49         const RunlevelType type;
50 } rcnd_table[] = {
51         /* Standard SysV runlevels */
52         { "rc0.d",  SPECIAL_RUNLEVEL0_TARGET, RUNLEVEL_DOWN },
53         { "rc1.d",  SPECIAL_RUNLEVEL1_TARGET, RUNLEVEL_UP },
54         { "rc2.d",  SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
55         { "rc3.d",  SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
56         { "rc4.d",  SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
57         { "rc5.d",  SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
58         { "rc6.d",  SPECIAL_RUNLEVEL6_TARGET, RUNLEVEL_DOWN },
59
60         /* SuSE style boot.d */
61         { "boot.d", SPECIAL_BASIC_TARGET,     RUNLEVEL_BASIC },
62
63         /* Debian style rcS.d */
64         { "rcS.d",  SPECIAL_BASIC_TARGET,     RUNLEVEL_BASIC },
65 };
66
67 #define RUNLEVELS_UP "12345"
68 /* #define RUNLEVELS_DOWN "06" */
69 /* #define RUNLEVELS_BOOT "bBsS" */
70
71 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
72         [SERVICE_DEAD] = UNIT_INACTIVE,
73         [SERVICE_START_PRE] = UNIT_ACTIVATING,
74         [SERVICE_START] = UNIT_ACTIVATING,
75         [SERVICE_START_POST] = UNIT_ACTIVATING,
76         [SERVICE_RUNNING] = UNIT_ACTIVE,
77         [SERVICE_EXITED] = UNIT_ACTIVE,
78         [SERVICE_RELOAD] = UNIT_ACTIVE_RELOADING,
79         [SERVICE_STOP] = UNIT_DEACTIVATING,
80         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
81         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
82         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
83         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
84         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
85         [SERVICE_MAINTAINANCE] = UNIT_INACTIVE,
86         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
87 };
88
89 static void service_init(Unit *u) {
90         Service *s = SERVICE(u);
91
92         assert(u);
93         assert(u->meta.load_state == UNIT_STUB);
94
95         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
96         s->restart_usec = DEFAULT_RESTART_USEC;
97         s->timer_watch.type = WATCH_INVALID;
98         s->sysv_start_priority = -1;
99         s->socket_fd = -1;
100
101         exec_context_init(&s->exec_context);
102
103         RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
104
105         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
106 }
107
108 static void service_unwatch_control_pid(Service *s) {
109         assert(s);
110
111         if (s->control_pid <= 0)
112                 return;
113
114         unit_unwatch_pid(UNIT(s), s->control_pid);
115         s->control_pid = 0;
116 }
117
118 static void service_unwatch_main_pid(Service *s) {
119         assert(s);
120
121         if (s->main_pid <= 0)
122                 return;
123
124         unit_unwatch_pid(UNIT(s), s->main_pid);
125         s->main_pid = 0;
126 }
127
128 static void service_close_socket_fd(Service *s) {
129         assert(s);
130
131         if (s->socket_fd < 0)
132                 return;
133
134         close_nointr_nofail(s->socket_fd);
135         s->socket_fd = -1;
136 }
137
138 static void service_done(Unit *u) {
139         Service *s = SERVICE(u);
140
141         assert(s);
142
143         free(s->pid_file);
144         s->pid_file = NULL;
145
146         free(s->sysv_path);
147         s->sysv_path = NULL;
148
149         free(s->sysv_runlevels);
150         s->sysv_runlevels = NULL;
151
152         exec_context_done(&s->exec_context);
153         exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
154         s->control_command = NULL;
155
156         /* This will leak a process, but at least no memory or any of
157          * our resources */
158         service_unwatch_main_pid(s);
159         service_unwatch_control_pid(s);
160
161         if (s->bus_name)  {
162                 unit_unwatch_bus_name(UNIT(u), s->bus_name);
163                 free(s->bus_name);
164                 s->bus_name = NULL;
165         }
166
167         service_close_socket_fd(s);
168
169         unit_unwatch_timer(u, &s->timer_watch);
170 }
171
172 static int sysv_translate_name(const char *name, char **_r) {
173
174         static const char * const table[] = {
175                 "$local_fs",  SPECIAL_LOCAL_FS_TARGET,
176                 "$network",   SPECIAL_NETWORK_TARGET,
177                 "$named",     SPECIAL_NSS_LOOKUP_TARGET,
178                 "$portmap",   SPECIAL_RPCBIND_TARGET,
179                 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
180                 "$syslog",    SPECIAL_SYSLOG_TARGET,
181                 "$time",      SPECIAL_RTC_SET_TARGET
182         };
183
184         unsigned i;
185         char *r;
186
187         for (i = 0; i < ELEMENTSOF(table); i += 2)
188                 if (streq(table[i], name)) {
189                         if (!(r = strdup(table[i+1])))
190                                 return -ENOMEM;
191
192                         goto finish;
193                 }
194
195         if (*name == '$')
196                 return 0;
197
198         if (asprintf(&r, "%s.service", name) < 0)
199                 return -ENOMEM;
200
201 finish:
202
203         if (_r)
204                 *_r = r;
205
206         return 1;
207 }
208
209 static int sysv_chkconfig_order(Service *s) {
210         Meta *other;
211         int r;
212
213         assert(s);
214
215         if (s->sysv_start_priority < 0)
216                 return 0;
217
218         /* For each pair of services where at least one lacks a LSB
219          * header, we use the start priority value to order things. */
220
221         LIST_FOREACH(units_per_type, other, UNIT(s)->meta.manager->units_per_type[UNIT_SERVICE]) {
222                 Service *t;
223                 UnitDependency d;
224
225                 t = (Service*) other;
226
227                 if (s == t)
228                         continue;
229
230                 if (t->sysv_start_priority < 0)
231                         continue;
232
233                 /* If both units have modern headers we don't care
234                  * about the priorities */
235                 if ((!s->sysv_path || s->sysv_has_lsb) &&
236                     (!t->sysv_path || t->sysv_has_lsb))
237                         continue;
238
239                 if (t->sysv_start_priority < s->sysv_start_priority)
240                         d = UNIT_AFTER;
241                 else if (t->sysv_start_priority > s->sysv_start_priority)
242                         d = UNIT_BEFORE;
243                 else
244                         continue;
245
246                 /* FIXME: Maybe we should compare the name here lexicographically? */
247
248                 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
249                         return r;
250         }
251
252         return 0;
253 }
254
255 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
256         ExecCommand *c;
257
258         if (!(c = new0(ExecCommand, 1)))
259                 return NULL;
260
261         if (!(c->path = strdup(path))) {
262                 free(c);
263                 return NULL;
264         }
265
266         if (!(c->argv = strv_new(path, arg1, NULL))) {
267                 free(c->path);
268                 free(c);
269                 return NULL;
270         }
271
272         return c;
273 }
274
275 static int sysv_exec_commands(Service *s) {
276         ExecCommand *c;
277
278         assert(s);
279         assert(s->sysv_path);
280
281         if (!(c = exec_command_new(s->sysv_path, "start")))
282                 return -ENOMEM;
283         exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
284
285         if (!(c = exec_command_new(s->sysv_path, "stop")))
286                 return -ENOMEM;
287         exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
288
289         if (!(c = exec_command_new(s->sysv_path, "reload")))
290                 return -ENOMEM;
291         exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
292
293         return 0;
294 }
295
296 static int service_load_sysv_path(Service *s, const char *path) {
297         FILE *f;
298         Unit *u;
299         unsigned line = 0;
300         int r;
301         enum {
302                 NORMAL,
303                 DESCRIPTION,
304                 LSB,
305                 LSB_DESCRIPTION
306         } state = NORMAL;
307
308         assert(s);
309         assert(path);
310
311         u = UNIT(s);
312
313         if (!(f = fopen(path, "re"))) {
314                 r = errno == ENOENT ? 0 : -errno;
315                 goto finish;
316         }
317
318         s->type = SERVICE_FORKING;
319         s->restart = SERVICE_ONCE;
320
321         free(s->sysv_path);
322         if (!(s->sysv_path = strdup(path))) {
323                 r = -ENOMEM;
324                 goto finish;
325         }
326
327         while (!feof(f)) {
328                 char l[LINE_MAX], *t;
329
330                 if (!fgets(l, sizeof(l), f)) {
331                         if (feof(f))
332                                 break;
333
334                         r = -errno;
335                         log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
336                         goto finish;
337                 }
338
339                 line++;
340
341                 t = strstrip(l);
342                 if (*t != '#')
343                         continue;
344
345                 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
346                         state = LSB;
347                         s->sysv_has_lsb = true;
348                         continue;
349                 }
350
351                 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
352                         state = NORMAL;
353                         continue;
354                 }
355
356                 t++;
357                 t += strspn(t, WHITESPACE);
358
359                 if (state == NORMAL) {
360
361                         /* Try to parse Red Hat style chkconfig headers */
362
363                         if (startswith(t, "chkconfig:")) {
364                                 int start_priority;
365                                 char runlevels[16], *k;
366
367                                 state = NORMAL;
368
369                                 if (sscanf(t+10, "%15s %i %*i",
370                                            runlevels,
371                                            &start_priority) != 2) {
372
373                                         log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
374                                         continue;
375                                 }
376
377                                 /* A start priority gathered from the
378                                  * symlink farms is preferred over the
379                                  * data from the LSB header. */
380                                 if (start_priority < 0 || start_priority > 99)
381                                         log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
382                                 else if (s->sysv_start_priority < 0)
383                                         s->sysv_start_priority = start_priority;
384
385                                 char_array_0(runlevels);
386                                 k = delete_chars(runlevels, WHITESPACE "-");
387
388                                 if (k[0]) {
389                                         char *d;
390
391                                         if (!(d = strdup(k))) {
392                                                 r = -ENOMEM;
393                                                 goto finish;
394                                         }
395
396                                         free(s->sysv_runlevels);
397                                         s->sysv_runlevels = d;
398                                 }
399
400                         } else if (startswith(t, "description:")) {
401
402                                 size_t k = strlen(t);
403                                 char *d;
404
405                                 if (t[k-1] == '\\') {
406                                         state = DESCRIPTION;
407                                         t[k-1] = 0;
408                                 }
409
410                                 if (!(d = strdup(strstrip(t+12)))) {
411                                         r = -ENOMEM;
412                                         goto finish;
413                                 }
414
415                                 free(u->meta.description);
416                                 u->meta.description = d;
417
418                         } else if (startswith(t, "pidfile:")) {
419
420                                 char *fn;
421
422                                 state = NORMAL;
423
424                                 fn = strstrip(t+8);
425                                 if (!path_is_absolute(fn)) {
426                                         log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
427                                         continue;
428                                 }
429
430                                 if (!(fn = strdup(fn))) {
431                                         r = -ENOMEM;
432                                         goto finish;
433                                 }
434
435                                 free(s->pid_file);
436                                 s->pid_file = fn;
437                         }
438
439                 } else if (state == DESCRIPTION) {
440
441                         /* Try to parse Red Hat style description
442                          * continuation */
443
444                         size_t k = strlen(t);
445                         char *d;
446
447                         if (t[k-1] == '\\')
448                                 t[k-1] = 0;
449                         else
450                                 state = NORMAL;
451
452                         assert(u->meta.description);
453                         if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
454                                 r = -ENOMEM;
455                                 goto finish;
456                         }
457
458                         free(u->meta.description);
459                         u->meta.description = d;
460
461                 } else if (state == LSB || state == LSB_DESCRIPTION) {
462
463                         if (startswith(t, "Provides:")) {
464                                 char *i, *w;
465                                 size_t z;
466
467                                 state = LSB;
468
469                                 FOREACH_WORD(w, z, t+9, i) {
470                                         char *n, *m;
471
472                                         if (!(n = strndup(w, z))) {
473                                                 r = -ENOMEM;
474                                                 goto finish;
475                                         }
476
477                                         r = sysv_translate_name(n, &m);
478                                         free(n);
479
480                                         if (r < 0)
481                                                 goto finish;
482
483                                         if (r == 0)
484                                                 continue;
485
486                                         if (unit_name_to_type(m) == UNIT_SERVICE)
487                                                 r = unit_add_name(u, m);
488                                         else {
489                                                 if ((r = unit_add_dependency_by_name_inverse(u, UNIT_REQUIRES, m, NULL, true)) >= 0)
490                                                         r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
491                                         }
492
493                                         free(m);
494
495                                         if (r < 0)
496                                                 goto finish;
497                                 }
498
499                         } else if (startswith(t, "Required-Start:") ||
500                                    startswith(t, "Should-Start:")) {
501                                 char *i, *w;
502                                 size_t z;
503
504                                 state = LSB;
505
506                                 FOREACH_WORD(w, z, strchr(t, ':')+1, i) {
507                                         char *n, *m;
508
509                                         if (!(n = strndup(w, z))) {
510                                                 r = -ENOMEM;
511                                                 goto finish;
512                                         }
513
514                                         r = sysv_translate_name(n, &m);
515                                         free(n);
516
517                                         if (r < 0)
518                                                 goto finish;
519
520                                         if (r == 0)
521                                                 continue;
522
523                                         r = unit_add_dependency_by_name(u, UNIT_AFTER, m, NULL, true);
524                                         free(m);
525
526                                         if (r < 0)
527                                                 goto finish;
528                                 }
529                         } else if (startswith(t, "Default-Start:")) {
530                                 char *k, *d;
531
532                                 state = LSB;
533
534                                 k = delete_chars(t+14, WHITESPACE "-");
535
536                                 if (k[0] != 0) {
537                                         if (!(d = strdup(k))) {
538                                                 r = -ENOMEM;
539                                                 goto finish;
540                                         }
541
542                                         free(s->sysv_runlevels);
543                                         s->sysv_runlevels = d;
544                                 }
545
546                         } else if (startswith(t, "Description:")) {
547                                 char *d;
548
549                                 state = LSB_DESCRIPTION;
550
551                                 if (!(d = strdup(strstrip(t+12)))) {
552                                         r = -ENOMEM;
553                                         goto finish;
554                                 }
555
556                                 free(u->meta.description);
557                                 u->meta.description = d;
558
559                         } else if (startswith(t, "Short-Description:") &&
560                                    !u->meta.description) {
561                                 char *d;
562
563                                 /* We use the short description only
564                                  * if no long description is set. */
565
566                                 state = LSB;
567
568                                 if (!(d = strdup(strstrip(t+18)))) {
569                                         r = -ENOMEM;
570                                         goto finish;
571                                 }
572
573                                 u->meta.description = d;
574
575                         } else if (state == LSB_DESCRIPTION) {
576
577                                 if (startswith(l, "#\t") || startswith(l, "#  ")) {
578                                         char *d;
579
580                                         assert(u->meta.description);
581                                         if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
582                                                 r = -ENOMEM;
583                                                 goto finish;
584                                         }
585
586                                         free(u->meta.description);
587                                         u->meta.description = d;
588                                 } else
589                                         state = LSB;
590                         }
591                 }
592         }
593
594         /* If init scripts have no LSB header, then we enforce the
595          * ordering via the chkconfig priorities. We try to determine
596          * a priority for *all* init scripts here, since they are
597          * needed as soon as at least one non-LSB script is used. */
598
599         if (s->sysv_start_priority < 0)
600                 log_warning("%s has neither a chkconfig header nor a directory link, cannot order unit!", u->meta.id);
601
602         if ((r = sysv_exec_commands(s)) < 0)
603                 goto finish;
604
605         if (!s->sysv_runlevels || chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
606                 /* If there a runlevels configured for this service
607                  * but none of the standard ones, then we assume this
608                  * is some special kind of service (which might be
609                  * needed for early boot) and don't create any links
610                  * to it. */
611
612                 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0 ||
613                     (r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
614                         goto finish;
615
616         } else
617                 /* Don't timeout special services during boot (like fsck) */
618                 s->timeout_usec = 0;
619
620         /* Special setting for all SysV services */
621         s->valid_no_process = true;
622         s->kill_mode = KILL_PROCESS_GROUP;
623
624         u->meta.load_state = UNIT_LOADED;
625         r = 0;
626
627 finish:
628
629         if (f)
630                 fclose(f);
631
632         return r;
633 }
634
635 static int service_load_sysv_name(Service *s, const char *name) {
636         char **p;
637
638         assert(s);
639         assert(name);
640
641         STRV_FOREACH(p, UNIT(s)->meta.manager->sysvinit_path) {
642                 char *path;
643                 int r;
644
645                 if (asprintf(&path, "%s/%s", *p, name) < 0)
646                         return -ENOMEM;
647
648                 assert(endswith(path, ".service"));
649                 path[strlen(path)-8] = 0;
650
651                 r = service_load_sysv_path(s, path);
652
653                 if (r >= 0 && UNIT(s)->meta.load_state == UNIT_STUB) {
654                         /* Try Debian style .sh source'able init scripts */
655                         strcat(path, ".sh");
656                         r = service_load_sysv_path(s, path);
657                 }
658
659                 free(path);
660
661                 if (r >= 0 && UNIT(s)->meta.load_state == UNIT_STUB) {
662                         /* Try Suse style boot.xxxx init scripts */
663
664                         if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
665                                 return -ENOMEM;
666
667                         path[strlen(path)-8] = 0;
668                         r = service_load_sysv_path(s, path);
669                         free(path);
670                 }
671
672                 if (r < 0)
673                         return r;
674
675                 if ((UNIT(s)->meta.load_state != UNIT_STUB))
676                         break;
677         }
678
679         return 0;
680 }
681
682 static int service_load_sysv(Service *s) {
683         const char *t;
684         Iterator i;
685         int r;
686
687         assert(s);
688
689         /* Load service data from SysV init scripts, preferably with
690          * LSB headers ... */
691
692         if (strv_isempty(UNIT(s)->meta.manager->sysvinit_path))
693                 return 0;
694
695         if ((t = UNIT(s)->meta.id))
696                 if ((r = service_load_sysv_name(s, t)) < 0)
697                         return r;
698
699         if (UNIT(s)->meta.load_state == UNIT_STUB)
700                 SET_FOREACH(t, UNIT(s)->meta.names, i) {
701                         if (t == UNIT(s)->meta.id)
702                                 continue;
703
704                         if ((r == service_load_sysv_name(s, t)) < 0)
705                                 return r;
706
707                         if (UNIT(s)->meta.load_state != UNIT_STUB)
708                                 break;
709                 }
710
711         return 0;
712 }
713
714 static int service_add_bus_name(Service *s) {
715         char *n;
716         int r;
717
718         assert(s);
719         assert(s->bus_name);
720
721         if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
722                 return 0;
723
724         r = unit_merge_by_name(UNIT(s), n);
725         free(n);
726
727         return r;
728 }
729
730 static int service_verify(Service *s) {
731         assert(s);
732
733         if (UNIT(s)->meta.load_state != UNIT_LOADED)
734                 return 0;
735
736         if (!s->exec_command[SERVICE_EXEC_START]) {
737                 log_error("%s lacks ExecStart setting. Refusing.", UNIT(s)->meta.id);
738                 return -EINVAL;
739         }
740
741         if (s->type == SERVICE_DBUS && !s->bus_name) {
742                 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->meta.id);
743                 return -EINVAL;
744         }
745
746         return 0;
747 }
748
749 static int service_load(Unit *u) {
750         int r;
751         Service *s = SERVICE(u);
752
753         assert(s);
754
755         /* Load a .service file */
756         if ((r = unit_load_fragment(u)) < 0)
757                 return r;
758
759         /* Load a classic init script as a fallback, if we couldn't find anything */
760         if (u->meta.load_state == UNIT_STUB)
761                 if ((r = service_load_sysv(s)) < 0)
762                         return r;
763
764         /* Still nothing found? Then let's give up */
765         if (u->meta.load_state == UNIT_STUB)
766                 return -ENOENT;
767
768         /* We were able to load something, then let's add in the
769          * dropin directories. */
770         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
771                 return r;
772
773         /* This is a new unit? Then let's add in some extras */
774         if (u->meta.load_state == UNIT_LOADED) {
775                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
776                         return r;
777
778                 if ((r = unit_add_default_cgroup(u)) < 0)
779                         return r;
780
781                 if ((r = sysv_chkconfig_order(s)) < 0)
782                         return r;
783
784                 if (s->bus_name) {
785                         if ((r = service_add_bus_name(s)) < 0)
786                                 return r;
787
788                         if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
789                             return r;
790                 }
791         }
792
793         return service_verify(s);
794 }
795
796 static void service_dump(Unit *u, FILE *f, const char *prefix) {
797
798         ServiceExecCommand c;
799         Service *s = SERVICE(u);
800         const char *prefix2;
801         char *p2;
802
803         assert(s);
804
805         p2 = strappend(prefix, "\t");
806         prefix2 = p2 ? p2 : prefix;
807
808         fprintf(f,
809                 "%sService State: %s\n"
810                 "%sPermissionsStartOnly: %s\n"
811                 "%sRootDirectoryStartOnly: %s\n"
812                 "%sValidNoProcess: %s\n"
813                 "%sKillMode: %s\n"
814                 "%sType: %s\n",
815                 prefix, service_state_to_string(s->state),
816                 prefix, yes_no(s->permissions_start_only),
817                 prefix, yes_no(s->root_directory_start_only),
818                 prefix, yes_no(s->valid_no_process),
819                 prefix, kill_mode_to_string(s->kill_mode),
820                 prefix, service_type_to_string(s->type));
821
822         if (s->control_pid > 0)
823                 fprintf(f,
824                         "%sControl PID: %llu\n",
825                         prefix, (unsigned long long) s->control_pid);
826
827         if (s->main_pid > 0)
828                 fprintf(f,
829                         "%sMain PID: %llu\n",
830                         prefix, (unsigned long long) s->main_pid);
831
832         if (s->pid_file)
833                 fprintf(f,
834                         "%sPIDFile: %s\n",
835                         prefix, s->pid_file);
836
837         if (s->bus_name)
838                 fprintf(f,
839                         "%sBusName: %s\n"
840                         "%sBus Name Good: %s\n",
841                         prefix, s->bus_name,
842                         prefix, yes_no(s->bus_name_good));
843
844         exec_context_dump(&s->exec_context, f, prefix);
845
846         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
847
848                 if (!s->exec_command[c])
849                         continue;
850
851                 fprintf(f, "%s-> %s:\n",
852                         prefix, service_exec_command_to_string(c));
853
854                 exec_command_dump_list(s->exec_command[c], f, prefix2);
855         }
856
857         if (s->sysv_path)
858                 fprintf(f,
859                         "%sSysV Init Script Path: %s\n"
860                         "%sSysV Init Script has LSB Header: %s\n",
861                         prefix, s->sysv_path,
862                         prefix, yes_no(s->sysv_has_lsb));
863
864         if (s->sysv_start_priority >= 0)
865                 fprintf(f,
866                         "%sSysVStartPriority: %i\n",
867                         prefix, s->sysv_start_priority);
868
869         if (s->sysv_runlevels)
870                 fprintf(f, "%sSysVRunLevels: %s\n",
871                         prefix, s->sysv_runlevels);
872
873         free(p2);
874 }
875
876 static int service_load_pid_file(Service *s) {
877         char *k;
878         unsigned long p;
879         int r;
880
881         assert(s);
882
883         if (s->main_pid_known)
884                 return 0;
885
886         assert(s->main_pid <= 0);
887
888         if (!s->pid_file)
889                 return -ENOENT;
890
891         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
892                 return r;
893
894         if ((r = safe_atolu(k, &p)) < 0) {
895                 free(k);
896                 return r;
897         }
898
899         if ((unsigned long) (pid_t) p != p)
900                 return -ERANGE;
901
902         if (kill((pid_t) p, 0) < 0 && errno != EPERM) {
903                 log_warning("PID %llu read from file %s does not exist. Your service or init script might be broken.",
904                             (unsigned long long) p, s->pid_file);
905                 return -ESRCH;
906         }
907
908         if ((r = unit_watch_pid(UNIT(s), (pid_t) p)) < 0)
909                 /* FIXME: we need to do something here */
910                 return r;
911
912         s->main_pid = (pid_t) p;
913         s->main_pid_known = true;
914
915         return 0;
916 }
917
918 static int service_get_sockets(Service *s, Set **_set) {
919         Set *set;
920         Iterator i;
921         char *t;
922         int r;
923
924         assert(s);
925         assert(_set);
926
927         /* Collects all Socket objects that belong to this
928          * service. Note that a service might have multiple sockets
929          * via multiple names. */
930
931         if (!(set = set_new(NULL, NULL)))
932                 return -ENOMEM;
933
934         SET_FOREACH(t, UNIT(s)->meta.names, i) {
935                 char *k;
936                 Unit *p;
937
938                 /* Look for all socket objects that go by any of our
939                  * units and collect their fds */
940
941                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
942                         r = -ENOMEM;
943                         goto fail;
944                 }
945
946                 p = manager_get_unit(UNIT(s)->meta.manager, k);
947                 free(k);
948
949                 if (!p)
950                         continue;
951
952                 if ((r = set_put(set, p)) < 0)
953                         goto fail;
954         }
955
956         *_set = set;
957         return 0;
958
959 fail:
960         set_free(set);
961         return r;
962 }
963
964 static int service_notify_sockets_dead(Service *s) {
965         Iterator i;
966         Set *set;
967         Socket *sock;
968         int r;
969
970         assert(s);
971
972         /* Notifies all our sockets when we die */
973         if ((r = service_get_sockets(s, &set)) < 0)
974                 return r;
975
976         SET_FOREACH(sock, set, i)
977                 socket_notify_service_dead(sock);
978
979         set_free(set);
980
981         return 0;
982 }
983
984 static void service_set_state(Service *s, ServiceState state) {
985         ServiceState old_state;
986         assert(s);
987
988         old_state = s->state;
989         s->state = state;
990
991         if (state != SERVICE_START_PRE &&
992             state != SERVICE_START &&
993             state != SERVICE_START_POST &&
994             state != SERVICE_RELOAD &&
995             state != SERVICE_STOP &&
996             state != SERVICE_STOP_SIGTERM &&
997             state != SERVICE_STOP_SIGKILL &&
998             state != SERVICE_STOP_POST &&
999             state != SERVICE_FINAL_SIGTERM &&
1000             state != SERVICE_FINAL_SIGKILL &&
1001             state != SERVICE_AUTO_RESTART)
1002                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1003
1004         if (state != SERVICE_START &&
1005             state != SERVICE_START_POST &&
1006             state != SERVICE_RUNNING &&
1007             state != SERVICE_RELOAD &&
1008             state != SERVICE_STOP &&
1009             state != SERVICE_STOP_SIGTERM &&
1010             state != SERVICE_STOP_SIGKILL)
1011                 service_unwatch_main_pid(s);
1012
1013         if (state != SERVICE_START_PRE &&
1014             state != SERVICE_START &&
1015             state != SERVICE_START_POST &&
1016             state != SERVICE_RELOAD &&
1017             state != SERVICE_STOP &&
1018             state != SERVICE_STOP_SIGTERM &&
1019             state != SERVICE_STOP_SIGKILL &&
1020             state != SERVICE_STOP_POST &&
1021             state != SERVICE_FINAL_SIGTERM &&
1022             state != SERVICE_FINAL_SIGKILL) {
1023                 service_unwatch_control_pid(s);
1024                 s->control_command = NULL;
1025                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1026         }
1027
1028         if (state == SERVICE_DEAD ||
1029             state == SERVICE_STOP ||
1030             state == SERVICE_STOP_SIGTERM ||
1031             state == SERVICE_STOP_SIGKILL ||
1032             state == SERVICE_STOP_POST ||
1033             state == SERVICE_FINAL_SIGTERM ||
1034             state == SERVICE_FINAL_SIGKILL ||
1035             state == SERVICE_MAINTAINANCE ||
1036             state == SERVICE_AUTO_RESTART)
1037                 service_notify_sockets_dead(s);
1038
1039         if (state != SERVICE_START_PRE &&
1040             state != SERVICE_START &&
1041             !(state == SERVICE_DEAD && UNIT(s)->meta.job))
1042                 service_close_socket_fd(s);
1043
1044         if (old_state != state)
1045                 log_debug("%s changed %s -> %s", UNIT(s)->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1046
1047         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1048 }
1049
1050 static int service_coldplug(Unit *u) {
1051         Service *s = SERVICE(u);
1052         int r;
1053
1054         assert(s);
1055         assert(s->state == SERVICE_DEAD);
1056
1057         if (s->deserialized_state != s->state) {
1058
1059                 if (s->deserialized_state == SERVICE_START_PRE ||
1060                     s->deserialized_state == SERVICE_START ||
1061                     s->deserialized_state == SERVICE_START_POST ||
1062                     s->deserialized_state == SERVICE_RELOAD ||
1063                     s->deserialized_state == SERVICE_STOP ||
1064                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1065                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1066                     s->deserialized_state == SERVICE_STOP_POST ||
1067                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1068                     s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1069                     s->deserialized_state == SERVICE_AUTO_RESTART) {
1070
1071                         if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1072                                 usec_t k;
1073
1074                                 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1075
1076                                 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1077                                         return r;
1078                         }
1079                 }
1080
1081                 if ((s->deserialized_state == SERVICE_START &&
1082                      (s->type == SERVICE_FORKING ||
1083                       s->type == SERVICE_DBUS)) ||
1084                     s->deserialized_state == SERVICE_START_POST ||
1085                     s->deserialized_state == SERVICE_RUNNING ||
1086                     s->deserialized_state == SERVICE_RELOAD ||
1087                     s->deserialized_state == SERVICE_STOP ||
1088                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1089                     s->deserialized_state == SERVICE_STOP_SIGKILL)
1090                         if (s->main_pid > 0)
1091                                 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1092                                         return r;
1093
1094                 if (s->deserialized_state == SERVICE_START_PRE ||
1095                     s->deserialized_state == SERVICE_START ||
1096                     s->deserialized_state == SERVICE_START_POST ||
1097                     s->deserialized_state == SERVICE_RELOAD ||
1098                     s->deserialized_state == SERVICE_STOP ||
1099                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1100                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1101                     s->deserialized_state == SERVICE_STOP_POST ||
1102                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1103                     s->deserialized_state == SERVICE_FINAL_SIGKILL)
1104                         if (s->control_pid > 0)
1105                                 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1106                                         return r;
1107
1108                 service_set_state(s, s->deserialized_state);
1109         }
1110
1111         return 0;
1112 }
1113
1114 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1115         Iterator i;
1116         int r;
1117         int *rfds = NULL;
1118         unsigned rn_fds = 0;
1119         Set *set;
1120         Socket *sock;
1121
1122         assert(s);
1123         assert(fds);
1124         assert(n_fds);
1125
1126         if ((r = service_get_sockets(s, &set)) < 0)
1127                 return r;
1128
1129         SET_FOREACH(sock, set, i) {
1130                 int *cfds;
1131                 unsigned cn_fds;
1132
1133                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1134                         goto fail;
1135
1136                 if (!cfds)
1137                         continue;
1138
1139                 if (!rfds) {
1140                         rfds = cfds;
1141                         rn_fds = cn_fds;
1142                 } else {
1143                         int *t;
1144
1145                         if (!(t = new(int, rn_fds+cn_fds))) {
1146                                 free(cfds);
1147                                 r = -ENOMEM;
1148                                 goto fail;
1149                         }
1150
1151                         memcpy(t, rfds, rn_fds);
1152                         memcpy(t+rn_fds, cfds, cn_fds);
1153                         free(rfds);
1154                         free(cfds);
1155
1156                         rfds = t;
1157                         rn_fds = rn_fds+cn_fds;
1158                 }
1159         }
1160
1161         *fds = rfds;
1162         *n_fds = rn_fds;
1163
1164         set_free(set);
1165
1166         return 0;
1167
1168 fail:
1169         set_free(set);
1170         free(rfds);
1171
1172         return r;
1173 }
1174
1175 static int service_spawn(
1176                 Service *s,
1177                 ExecCommand *c,
1178                 bool timeout,
1179                 bool pass_fds,
1180                 bool apply_permissions,
1181                 bool apply_chroot,
1182                 pid_t *_pid) {
1183
1184         pid_t pid;
1185         int r;
1186         int *fds = NULL;
1187         unsigned n_fds = 0;
1188         char **argv;
1189
1190         assert(s);
1191         assert(c);
1192         assert(_pid);
1193
1194         if (pass_fds) {
1195                 if (s->socket_fd >= 0) {
1196                         fds = &s->socket_fd;
1197                         n_fds = 1;
1198                 } else if ((r = service_collect_fds(s, &fds, &n_fds)) < 0)
1199                         goto fail;
1200         }
1201
1202         if (timeout && s->timeout_usec) {
1203                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1204                         goto fail;
1205         } else
1206                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1207
1208         if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1209                 r = -ENOMEM;
1210                 goto fail;
1211         }
1212
1213         r = exec_spawn(c,
1214                        argv,
1215                        &s->exec_context,
1216                        fds, n_fds,
1217                        s->meta.manager->environment,
1218                        apply_permissions,
1219                        apply_chroot,
1220                        UNIT(s)->meta.manager->confirm_spawn,
1221                        UNIT(s)->meta.cgroup_bondings,
1222                        &pid);
1223
1224         strv_free(argv);
1225         if (r < 0)
1226                 goto fail;
1227
1228         if (fds) {
1229                 if (s->socket_fd >= 0)
1230                         service_close_socket_fd(s);
1231                 else
1232                         free(fds);
1233         }
1234
1235         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1236                 /* FIXME: we need to do something here */
1237                 goto fail;
1238
1239         *_pid = pid;
1240
1241         return 0;
1242
1243 fail:
1244         free(fds);
1245
1246         if (timeout)
1247                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1248
1249         return r;
1250 }
1251
1252 static int main_pid_good(Service *s) {
1253         assert(s);
1254
1255         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1256          * don't know */
1257
1258         /* If we know the pid file, then lets just check if it is
1259          * still valid */
1260         if (s->main_pid_known)
1261                 return s->main_pid > 0;
1262
1263         /* We don't know the pid */
1264         return -EAGAIN;
1265 }
1266
1267 static int control_pid_good(Service *s) {
1268         assert(s);
1269
1270         return s->control_pid > 0;
1271 }
1272
1273 static int cgroup_good(Service *s) {
1274         int r;
1275
1276         assert(s);
1277
1278         if (s->valid_no_process)
1279                 return -EAGAIN;
1280
1281         if ((r = cgroup_bonding_is_empty_list(UNIT(s)->meta.cgroup_bondings)) < 0)
1282                 return r;
1283
1284         return !r;
1285 }
1286
1287 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1288         int r;
1289         assert(s);
1290
1291         if (!success)
1292                 s->failure = true;
1293
1294         if (allow_restart &&
1295             s->allow_restart &&
1296             (s->restart == SERVICE_RESTART_ALWAYS ||
1297              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1298
1299                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1300                         goto fail;
1301
1302                 service_set_state(s, SERVICE_AUTO_RESTART);
1303         } else
1304                 service_set_state(s, s->failure ? SERVICE_MAINTAINANCE : SERVICE_DEAD);
1305
1306         return;
1307
1308 fail:
1309         log_warning("%s failed to run install restart timer: %s", UNIT(s)->meta.id, strerror(-r));
1310         service_enter_dead(s, false, false);
1311 }
1312
1313 static void service_enter_signal(Service *s, ServiceState state, bool success);
1314
1315 static void service_enter_stop_post(Service *s, bool success) {
1316         int r;
1317         assert(s);
1318
1319         if (!success)
1320                 s->failure = true;
1321
1322         service_unwatch_control_pid(s);
1323
1324         s->control_command_id = SERVICE_EXEC_STOP_POST;
1325         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1326                 if ((r = service_spawn(s,
1327                                        s->control_command,
1328                                        true,
1329                                        false,
1330                                        !s->permissions_start_only,
1331                                        !s->root_directory_start_only,
1332                                        &s->control_pid)) < 0)
1333                         goto fail;
1334
1335
1336                 service_set_state(s, SERVICE_STOP_POST);
1337         } else
1338                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1339
1340         return;
1341
1342 fail:
1343         log_warning("%s failed to run stop-post executable: %s", UNIT(s)->meta.id, strerror(-r));
1344         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1345 }
1346
1347 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1348         int r;
1349         bool sent = false;
1350
1351         assert(s);
1352
1353         if (!success)
1354                 s->failure = true;
1355
1356         if (s->kill_mode != KILL_NONE) {
1357                 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1358
1359                 if (s->kill_mode == KILL_CONTROL_GROUP) {
1360
1361                         if ((r = cgroup_bonding_kill_list(UNIT(s)->meta.cgroup_bondings, sig)) < 0) {
1362                                 if (r != -EAGAIN && r != -ESRCH)
1363                                         goto fail;
1364                         } else
1365                                 sent = true;
1366                 }
1367
1368                 if (!sent) {
1369                         r = 0;
1370
1371                         if (s->main_pid > 0) {
1372                                 if (kill(s->kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1373                                         r = -errno;
1374                                 else
1375                                         sent = true;
1376                         }
1377
1378                         if (s->control_pid > 0) {
1379                                 if (kill(s->kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1380                                         r = -errno;
1381                                 else
1382                                         sent = true;
1383                         }
1384
1385                         if (r < 0)
1386                                 goto fail;
1387                 }
1388         }
1389
1390         if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1391                 if (s->timeout_usec > 0)
1392                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1393                                 goto fail;
1394
1395                 service_set_state(s, state);
1396         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1397                 service_enter_stop_post(s, true);
1398         else
1399                 service_enter_dead(s, true, true);
1400
1401         return;
1402
1403 fail:
1404         log_warning("%s failed to kill processes: %s", UNIT(s)->meta.id, strerror(-r));
1405
1406         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1407                 service_enter_stop_post(s, false);
1408         else
1409                 service_enter_dead(s, false, true);
1410 }
1411
1412 static void service_enter_stop(Service *s, bool success) {
1413         int r;
1414         assert(s);
1415
1416         if (!success)
1417                 s->failure = true;
1418
1419         service_unwatch_control_pid(s);
1420
1421         s->control_command_id = SERVICE_EXEC_STOP;
1422         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1423                 if ((r = service_spawn(s,
1424                                        s->control_command,
1425                                        true,
1426                                        false,
1427                                        !s->permissions_start_only,
1428                                        !s->root_directory_start_only,
1429                                        &s->control_pid)) < 0)
1430                         goto fail;
1431
1432                 service_set_state(s, SERVICE_STOP);
1433         } else
1434                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1435
1436         return;
1437
1438 fail:
1439         log_warning("%s failed to run stop executable: %s", UNIT(s)->meta.id, strerror(-r));
1440         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1441 }
1442
1443 static void service_enter_running(Service *s, bool success) {
1444         assert(s);
1445
1446         if (!success)
1447                 s->failure = true;
1448
1449         if (main_pid_good(s) != 0 &&
1450             cgroup_good(s) != 0 &&
1451             (s->bus_name_good || s->type != SERVICE_DBUS))
1452                 service_set_state(s, SERVICE_RUNNING);
1453         else if (s->valid_no_process)
1454                 service_set_state(s, SERVICE_EXITED);
1455         else
1456                 service_enter_stop(s, true);
1457 }
1458
1459 static void service_enter_start_post(Service *s) {
1460         int r;
1461         assert(s);
1462
1463         service_unwatch_control_pid(s);
1464
1465         s->control_command_id = SERVICE_EXEC_START_POST;
1466         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1467                 if ((r = service_spawn(s,
1468                                        s->control_command,
1469                                        true,
1470                                        false,
1471                                        !s->permissions_start_only,
1472                                        !s->root_directory_start_only,
1473                                        &s->control_pid)) < 0)
1474                         goto fail;
1475
1476
1477                 service_set_state(s, SERVICE_START_POST);
1478         } else
1479                 service_enter_running(s, true);
1480
1481         return;
1482
1483 fail:
1484         log_warning("%s failed to run start-post executable: %s", UNIT(s)->meta.id, strerror(-r));
1485         service_enter_stop(s, false);
1486 }
1487
1488 static void service_enter_start(Service *s) {
1489         pid_t pid;
1490         int r;
1491
1492         assert(s);
1493
1494         assert(s->exec_command[SERVICE_EXEC_START]);
1495         assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1496
1497         if (s->type == SERVICE_FORKING)
1498                 service_unwatch_control_pid(s);
1499         else
1500                 service_unwatch_main_pid(s);
1501
1502         if ((r = service_spawn(s,
1503                                s->exec_command[SERVICE_EXEC_START],
1504                                s->type == SERVICE_FORKING || s->type == SERVICE_DBUS,
1505                                true,
1506                                true,
1507                                true,
1508                                &pid)) < 0)
1509                 goto fail;
1510
1511         if (s->type == SERVICE_SIMPLE) {
1512                 /* For simple services we immediately start
1513                  * the START_POST binaries. */
1514
1515                 s->main_pid = pid;
1516                 s->main_pid_known = true;
1517
1518                 service_enter_start_post(s);
1519
1520         } else  if (s->type == SERVICE_FORKING) {
1521
1522                 /* For forking services we wait until the start
1523                  * process exited. */
1524
1525                 s->control_pid = pid;
1526
1527                 s->control_command_id = SERVICE_EXEC_START;
1528                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1529                 service_set_state(s, SERVICE_START);
1530
1531         } else if (s->type == SERVICE_FINISH ||
1532                    s->type == SERVICE_DBUS) {
1533
1534                 /* For finishing services we wait until the start
1535                  * process exited, too, but it is our main process. */
1536
1537                 /* For D-Bus services we know the main pid right away,
1538                  * but wait for the bus name to appear on the bus. */
1539
1540                 s->main_pid = pid;
1541                 s->main_pid_known = true;
1542
1543                 service_set_state(s, SERVICE_START);
1544         } else
1545                 assert_not_reached("Unknown service type");
1546
1547         return;
1548
1549 fail:
1550         log_warning("%s failed to run start exectuable: %s", UNIT(s)->meta.id, strerror(-r));
1551         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1552 }
1553
1554 static void service_enter_start_pre(Service *s) {
1555         int r;
1556
1557         assert(s);
1558
1559         service_unwatch_control_pid(s);
1560
1561         s->control_command_id = SERVICE_EXEC_START_PRE;
1562         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1563                 if ((r = service_spawn(s,
1564                                        s->control_command,
1565                                        true,
1566                                        false,
1567                                        !s->permissions_start_only,
1568                                        !s->root_directory_start_only,
1569                                        &s->control_pid)) < 0)
1570                         goto fail;
1571
1572                 service_set_state(s, SERVICE_START_PRE);
1573         } else
1574                 service_enter_start(s);
1575
1576         return;
1577
1578 fail:
1579         log_warning("%s failed to run start-pre executable: %s", UNIT(s)->meta.id, strerror(-r));
1580         service_enter_dead(s, false, true);
1581 }
1582
1583 static void service_enter_restart(Service *s) {
1584         int r;
1585         assert(s);
1586
1587         service_enter_dead(s, true, false);
1588
1589         if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL)) < 0)
1590                 goto fail;
1591
1592         log_debug("%s scheduled restart job.", UNIT(s)->meta.id);
1593         return;
1594
1595 fail:
1596
1597         log_warning("%s failed to schedule restart job: %s", UNIT(s)->meta.id, strerror(-r));
1598         service_enter_dead(s, false, false);
1599 }
1600
1601 static void service_enter_reload(Service *s) {
1602         int r;
1603
1604         assert(s);
1605
1606         service_unwatch_control_pid(s);
1607
1608         s->control_command_id = SERVICE_EXEC_RELOAD;
1609         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1610                 if ((r = service_spawn(s,
1611                                        s->control_command,
1612                                        true,
1613                                        false,
1614                                        !s->permissions_start_only,
1615                                        !s->root_directory_start_only,
1616                                        &s->control_pid)) < 0)
1617                         goto fail;
1618
1619                 service_set_state(s, SERVICE_RELOAD);
1620         } else
1621                 service_enter_running(s, true);
1622
1623         return;
1624
1625 fail:
1626         log_warning("%s failed to run reload executable: %s", UNIT(s)->meta.id, strerror(-r));
1627         service_enter_stop(s, false);
1628 }
1629
1630 static void service_run_next(Service *s, bool success) {
1631         int r;
1632
1633         assert(s);
1634         assert(s->control_command);
1635         assert(s->control_command->command_next);
1636
1637         if (!success)
1638                 s->failure = true;
1639
1640         s->control_command = s->control_command->command_next;
1641
1642         service_unwatch_control_pid(s);
1643
1644         if ((r = service_spawn(s,
1645                                s->control_command,
1646                                true,
1647                                false,
1648                                !s->permissions_start_only,
1649                                !s->root_directory_start_only,
1650                                &s->control_pid)) < 0)
1651                 goto fail;
1652
1653         return;
1654
1655 fail:
1656         log_warning("%s failed to run spawn next executable: %s", UNIT(s)->meta.id, strerror(-r));
1657
1658         if (s->state == SERVICE_START_PRE)
1659                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1660         else if (s->state == SERVICE_STOP)
1661                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1662         else if (s->state == SERVICE_STOP_POST)
1663                 service_enter_dead(s, false, true);
1664         else
1665                 service_enter_stop(s, false);
1666 }
1667
1668 static int service_start(Unit *u) {
1669         Service *s = SERVICE(u);
1670
1671         assert(s);
1672
1673         /* We cannot fulfill this request right now, try again later
1674          * please! */
1675         if (s->state == SERVICE_STOP ||
1676             s->state == SERVICE_STOP_SIGTERM ||
1677             s->state == SERVICE_STOP_SIGKILL ||
1678             s->state == SERVICE_STOP_POST ||
1679             s->state == SERVICE_FINAL_SIGTERM ||
1680             s->state == SERVICE_FINAL_SIGKILL)
1681                 return -EAGAIN;
1682
1683         /* Already on it! */
1684         if (s->state == SERVICE_START_PRE ||
1685             s->state == SERVICE_START ||
1686             s->state == SERVICE_START_POST)
1687                 return 0;
1688
1689         assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTAINANCE || s->state == SERVICE_AUTO_RESTART);
1690
1691         /* Make sure we don't enter a busy loop of some kind. */
1692         if (!ratelimit_test(&s->ratelimit)) {
1693                 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1694                 return -EAGAIN;
1695         }
1696
1697         s->failure = false;
1698         s->main_pid_known = false;
1699         s->allow_restart = true;
1700
1701         service_enter_start_pre(s);
1702         return 0;
1703 }
1704
1705 static int service_stop(Unit *u) {
1706         Service *s = SERVICE(u);
1707
1708         assert(s);
1709
1710         /* Cannot do this now */
1711         if (s->state == SERVICE_START_PRE ||
1712             s->state == SERVICE_START ||
1713             s->state == SERVICE_START_POST ||
1714             s->state == SERVICE_RELOAD)
1715                 return -EAGAIN;
1716
1717         /* Already on it */
1718         if (s->state == SERVICE_STOP ||
1719             s->state == SERVICE_STOP_SIGTERM ||
1720             s->state == SERVICE_STOP_SIGKILL ||
1721             s->state == SERVICE_STOP_POST ||
1722             s->state == SERVICE_FINAL_SIGTERM ||
1723             s->state == SERVICE_FINAL_SIGKILL)
1724                 return 0;
1725
1726         if (s->state == SERVICE_AUTO_RESTART) {
1727                 service_set_state(s, SERVICE_DEAD);
1728                 return 0;
1729         }
1730
1731         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1732
1733         /* This is a user request, so don't do restarts on this
1734          * shutdown. */
1735         s->allow_restart = false;
1736
1737         service_enter_stop(s, true);
1738         return 0;
1739 }
1740
1741 static int service_reload(Unit *u) {
1742         Service *s = SERVICE(u);
1743
1744         assert(s);
1745
1746         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1747
1748         service_enter_reload(s);
1749         return 0;
1750 }
1751
1752 static bool service_can_reload(Unit *u) {
1753         Service *s = SERVICE(u);
1754
1755         assert(s);
1756
1757         return !!s->exec_command[SERVICE_EXEC_RELOAD];
1758 }
1759
1760 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1761         Service *s = SERVICE(u);
1762
1763         assert(u);
1764         assert(f);
1765         assert(fds);
1766
1767         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1768         unit_serialize_item(u, f, "failure", yes_no(s->failure));
1769
1770         if (s->control_pid > 0)
1771                 unit_serialize_item_format(u, f, "control-pid", "%u", (unsigned) (s->control_pid));
1772
1773         if (s->main_pid > 0)
1774                 unit_serialize_item_format(u, f, "main-pid", "%u", (unsigned) (s->main_pid));
1775
1776         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1777
1778         /* There's a minor uncleanliness here: if there are multiple
1779          * commands attached here, we will start from the first one
1780          * again */
1781         if (s->control_command_id >= 0)
1782                 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
1783
1784         if (s->socket_fd >= 0) {
1785                 int copy;
1786
1787                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1788                         return copy;
1789
1790                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1791         }
1792
1793         return 0;
1794 }
1795
1796 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1797         Service *s = SERVICE(u);
1798         int r;
1799
1800         assert(u);
1801         assert(key);
1802         assert(value);
1803         assert(fds);
1804
1805         if (streq(key, "state")) {
1806                 ServiceState state;
1807
1808                 if ((state = service_state_from_string(value)) < 0)
1809                         log_debug("Failed to parse state value %s", value);
1810                 else
1811                         s->deserialized_state = state;
1812         } else if (streq(key, "failure")) {
1813                 int b;
1814
1815                 if ((b = parse_boolean(value)) < 0)
1816                         log_debug("Failed to parse failure value %s", value);
1817                 else
1818                         s->failure = b || s->failure;
1819         } else if (streq(key, "control-pid")) {
1820                 unsigned pid;
1821
1822                 if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
1823                         log_debug("Failed to parse control-pid value %s", value);
1824                 else
1825                         s->control_pid = (pid_t) pid;
1826         } else if (streq(key, "main-pid")) {
1827                 unsigned pid;
1828
1829                 if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
1830                         log_debug("Failed to parse main-pid value %s", value);
1831                 else
1832                         s->main_pid = (pid_t) pid;
1833         } else if (streq(key, "main-pid-known")) {
1834                 int b;
1835
1836                 if ((b = parse_boolean(value)) < 0)
1837                         log_debug("Failed to parse main-pid-known value %s", value);
1838                 else
1839                         s->main_pid_known = b;
1840         } else if (streq(key, "control-command")) {
1841                 ServiceExecCommand id;
1842
1843                 if ((id = service_exec_command_from_string(value)) < 0)
1844                         log_debug("Failed to parse exec-command value %s", value);
1845                 else {
1846                         s->control_command_id = id;
1847                         s->control_command = s->exec_command[id];
1848                 }
1849         } else if (streq(key, "socket-fd")) {
1850                 int fd;
1851
1852                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1853                         log_debug("Failed to parse socket-fd value %s", value);
1854                 else {
1855
1856                         if (s->socket_fd >= 0)
1857                                 close_nointr_nofail(s->socket_fd);
1858                         s->socket_fd = fdset_remove(fds, fd);
1859                 }
1860         } else
1861                 log_debug("Unknown serialization key '%s'", key);
1862
1863         return 0;
1864 }
1865
1866 static UnitActiveState service_active_state(Unit *u) {
1867         assert(u);
1868
1869         return state_translation_table[SERVICE(u)->state];
1870 }
1871
1872 static const char *service_sub_state_to_string(Unit *u) {
1873         assert(u);
1874
1875         return service_state_to_string(SERVICE(u)->state);
1876 }
1877
1878 static bool service_check_gc(Unit *u) {
1879         Service *s = SERVICE(u);
1880
1881         assert(s);
1882
1883         return !!s->sysv_path;
1884 }
1885
1886 static bool service_check_snapshot(Unit *u) {
1887         Service *s = SERVICE(u);
1888
1889         assert(s);
1890
1891         return !s->got_socket_fd;
1892 }
1893
1894 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1895         Service *s = SERVICE(u);
1896         bool success;
1897
1898         assert(s);
1899         assert(pid >= 0);
1900
1901         success = code == CLD_EXITED && status == 0;
1902         s->failure = s->failure || !success;
1903
1904         if (s->main_pid == pid) {
1905
1906                 exec_status_fill(&s->main_exec_status, pid, code, status);
1907                 s->main_pid = 0;
1908
1909                 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_FINISH) {
1910                         assert(s->exec_command[SERVICE_EXEC_START]);
1911                         s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
1912                 }
1913
1914                 log_debug("%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
1915
1916                 /* The service exited, so the service is officially
1917                  * gone. */
1918
1919                 switch (s->state) {
1920
1921                 case SERVICE_START_POST:
1922                 case SERVICE_RELOAD:
1923                 case SERVICE_STOP:
1924                         /* Need to wait until the operation is
1925                          * done */
1926                         break;
1927
1928                 case SERVICE_START:
1929                         assert(s->type == SERVICE_FINISH);
1930
1931                         /* This was our main goal, so let's go on */
1932                         if (success)
1933                                 service_enter_start_post(s);
1934                         else
1935                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1936                         break;
1937
1938                 case SERVICE_RUNNING:
1939                         service_enter_running(s, success);
1940                         break;
1941
1942                 case SERVICE_STOP_SIGTERM:
1943                 case SERVICE_STOP_SIGKILL:
1944
1945                         if (!control_pid_good(s))
1946                                 service_enter_stop_post(s, success);
1947
1948                         /* If there is still a control process, wait for that first */
1949                         break;
1950
1951                 default:
1952                         assert_not_reached("Uh, main process died at wrong time.");
1953                 }
1954
1955         } else if (s->control_pid == pid) {
1956
1957                 if (s->control_command)
1958                         exec_status_fill(&s->control_command->exec_status, pid, code, status);
1959
1960                 s->control_pid = 0;
1961
1962                 log_debug("%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1963
1964                 /* If we are shutting things down anyway we
1965                  * don't care about failing commands. */
1966
1967                 if (s->control_command && s->control_command->command_next && success) {
1968
1969                         /* There is another command to *
1970                          * execute, so let's do that. */
1971
1972                         log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
1973                         service_run_next(s, success);
1974
1975                 } else {
1976                         /* No further commands for this step, so let's
1977                          * figure out what to do next */
1978
1979                         s->control_command = NULL;
1980                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1981
1982                         log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
1983
1984                         switch (s->state) {
1985
1986                         case SERVICE_START_PRE:
1987                                 if (success)
1988                                         service_enter_start(s);
1989                                 else
1990                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1991                                 break;
1992
1993                         case SERVICE_START:
1994                                 assert(s->type == SERVICE_FORKING);
1995
1996                                 /* Let's try to load the pid
1997                                  * file here if we can. We
1998                                  * ignore the return value,
1999                                  * since the PID file might
2000                                  * actually be created by a
2001                                  * START_POST script */
2002
2003                                 if (success) {
2004                                         if (s->pid_file)
2005                                                 service_load_pid_file(s);
2006
2007                                         service_enter_start_post(s);
2008                                 } else
2009                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2010
2011                                 break;
2012
2013                         case SERVICE_START_POST:
2014                                 if (success && s->pid_file && !s->main_pid_known) {
2015                                         int r;
2016
2017                                         /* Hmm, let's see if we can
2018                                          * load the pid now after the
2019                                          * start-post scripts got
2020                                          * executed. */
2021
2022                                         if ((r = service_load_pid_file(s)) < 0)
2023                                                 log_warning("%s: failed to load PID file %s: %s", UNIT(s)->meta.id, s->pid_file, strerror(-r));
2024                                 }
2025
2026                                 /* Fall through */
2027
2028                         case SERVICE_RELOAD:
2029                                 if (success)
2030                                         service_enter_running(s, true);
2031                                 else
2032                                         service_enter_stop(s, false);
2033
2034                                 break;
2035
2036                         case SERVICE_STOP:
2037                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2038                                 break;
2039
2040                         case SERVICE_STOP_SIGTERM:
2041                         case SERVICE_STOP_SIGKILL:
2042                                 if (main_pid_good(s) <= 0)
2043                                         service_enter_stop_post(s, success);
2044
2045                                 /* If there is still a service
2046                                  * process around, wait until
2047                                  * that one quit, too */
2048                                 break;
2049
2050                         case SERVICE_STOP_POST:
2051                         case SERVICE_FINAL_SIGTERM:
2052                         case SERVICE_FINAL_SIGKILL:
2053                                 service_enter_dead(s, success, true);
2054                                 break;
2055
2056                         default:
2057                                 assert_not_reached("Uh, control process died at wrong time.");
2058                         }
2059                 }
2060         } else
2061                 assert_not_reached("Got SIGCHLD for unkown PID");
2062 }
2063
2064 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2065         Service *s = SERVICE(u);
2066
2067         assert(s);
2068         assert(elapsed == 1);
2069
2070         assert(w == &s->timer_watch);
2071
2072         switch (s->state) {
2073
2074         case SERVICE_START_PRE:
2075         case SERVICE_START:
2076                 log_warning("%s operation timed out. Terminating.", u->meta.id);
2077                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2078                 break;
2079
2080         case SERVICE_START_POST:
2081         case SERVICE_RELOAD:
2082                 log_warning("%s operation timed out. Stopping.", u->meta.id);
2083                 service_enter_stop(s, false);
2084                 break;
2085
2086         case SERVICE_STOP:
2087                 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2088                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2089                 break;
2090
2091         case SERVICE_STOP_SIGTERM:
2092                 log_warning("%s stopping timed out. Killing.", u->meta.id);
2093                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2094                 break;
2095
2096         case SERVICE_STOP_SIGKILL:
2097                 /* Uh, wie sent a SIGKILL and it is still not gone?
2098                  * Must be something we cannot kill, so let's just be
2099                  * weirded out and continue */
2100
2101                 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2102                 service_enter_stop_post(s, false);
2103                 break;
2104
2105         case SERVICE_STOP_POST:
2106                 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2107                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2108                 break;
2109
2110         case SERVICE_FINAL_SIGTERM:
2111                 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2112                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2113                 break;
2114
2115         case SERVICE_FINAL_SIGKILL:
2116                 log_warning("%s still around after SIGKILL (2). Entering maintainance mode.", u->meta.id);
2117                 service_enter_dead(s, false, true);
2118                 break;
2119
2120         case SERVICE_AUTO_RESTART:
2121                 log_debug("%s holdoff time over, scheduling restart.", u->meta.id);
2122                 service_enter_restart(s);
2123                 break;
2124
2125         default:
2126                 assert_not_reached("Timeout at wrong time.");
2127         }
2128 }
2129
2130 static void service_cgroup_notify_event(Unit *u) {
2131         Service *s = SERVICE(u);
2132
2133         assert(u);
2134
2135         log_debug("%s: cgroup is empty", u->meta.id);
2136
2137         switch (s->state) {
2138
2139                 /* Waiting for SIGCHLD is usually more interesting,
2140                  * because it includes return codes/signals. Which is
2141                  * why we ignore the cgroup events for most cases,
2142                  * except when we don't know pid which to expect the
2143                  * SIGCHLD for. */
2144
2145         case SERVICE_RUNNING:
2146                 service_enter_running(s, true);
2147                 break;
2148
2149         default:
2150                 ;
2151         }
2152 }
2153
2154 static int service_enumerate(Manager *m) {
2155         char **p;
2156         unsigned i;
2157         DIR *d = NULL;
2158         char *path = NULL, *fpath = NULL, *name = NULL;
2159         int r;
2160
2161         assert(m);
2162
2163         STRV_FOREACH(p, m->sysvrcnd_path)
2164                 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2165                         struct dirent *de;
2166
2167                         free(path);
2168                         path = NULL;
2169                         if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2170                                 r = -ENOMEM;
2171                                 goto finish;
2172                         }
2173
2174                         if (d)
2175                                 closedir(d);
2176
2177                         if (!(d = opendir(path))) {
2178                                 if (errno != ENOENT)
2179                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
2180
2181                                 continue;
2182                         }
2183
2184                         while ((de = readdir(d))) {
2185                                 Unit *service;
2186                                 int a, b;
2187
2188                                 if (ignore_file(de->d_name))
2189                                         continue;
2190
2191                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2192                                         continue;
2193
2194                                 if (strlen(de->d_name) < 4)
2195                                         continue;
2196
2197                                 a = undecchar(de->d_name[1]);
2198                                 b = undecchar(de->d_name[2]);
2199
2200                                 if (a < 0 || b < 0)
2201                                         continue;
2202
2203                                 free(fpath);
2204                                 fpath = NULL;
2205                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2206                                         r = -ENOMEM;
2207                                         goto finish;
2208                                 }
2209
2210                                 if (access(fpath, X_OK) < 0) {
2211
2212                                         if (errno != ENOENT)
2213                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2214
2215                                         continue;
2216                                 }
2217
2218                                 free(name);
2219                                 if (!(name = new(char, strlen(de->d_name) - 3 + 8 + 1))) {
2220                                         r = -ENOMEM;
2221                                         goto finish;
2222                                 }
2223
2224                                 if (startswith(de->d_name+3, "boot."))
2225                                         /* Drop SuSE-style boot. prefix */
2226                                         strcpy(stpcpy(name, de->d_name + 3 + 5), ".service");
2227                                 else if (endswith(de->d_name+3, ".sh"))
2228                                         /* Drop Debian-style .sh suffix */
2229                                         strcpy(stpcpy(name, de->d_name + 3) - 3, ".service");
2230                                 else
2231                                         /* Normal init scripts */
2232                                         strcpy(stpcpy(name, de->d_name + 3), ".service");
2233
2234                                 if ((r = manager_load_unit_prepare(m, name, NULL, &service)) < 0) {
2235                                         log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2236                                         continue;
2237                                 }
2238
2239                                 if (de->d_name[0] == 'S' &&
2240                                     (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_BASIC))
2241                                         SERVICE(service)->sysv_start_priority =
2242                                                 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2243
2244                                 manager_dispatch_load_queue(m);
2245                                 service = unit_follow_merge(service);
2246
2247                                 if (de->d_name[0] == 'S') {
2248                                         Unit *runlevel_target;
2249
2250                                         if ((r = manager_load_unit(m, rcnd_table[i].target, NULL, &runlevel_target)) < 0)
2251                                                 goto finish;
2252
2253                                         if ((r = unit_add_dependency(runlevel_target, UNIT_WANTS, service, true)) < 0)
2254                                                 goto finish;
2255
2256                                         if ((r = unit_add_dependency(service, UNIT_BEFORE, runlevel_target, true)) < 0)
2257                                                 goto finish;
2258
2259                                 } else if (de->d_name[0] == 'K' && rcnd_table[i].type == RUNLEVEL_DOWN) {
2260                                         Unit *shutdown_target;
2261
2262                                         /* We honour K links only for
2263                                          * halt/reboot. For the normal
2264                                          * runlevels we assume the
2265                                          * stop jobs will be
2266                                          * implicitly added by the
2267                                          * core logic. Also, we don't
2268                                          * really distuingish here
2269                                          * between the runlevels 0 and
2270                                          * 6 and just add them to the
2271                                          * special shutdown target. */
2272
2273                                         if ((r = manager_load_unit(m, SPECIAL_SHUTDOWN_TARGET, NULL, &shutdown_target)) < 0)
2274                                                 goto finish;
2275
2276                                         if ((r = unit_add_dependency(service, UNIT_CONFLICTS, shutdown_target, true)) < 0)
2277                                                 goto finish;
2278
2279                                         if ((r = unit_add_dependency(service, UNIT_BEFORE, shutdown_target, true)) < 0)
2280                                                 goto finish;
2281                                 }
2282                         }
2283                 }
2284
2285         r = 0;
2286
2287 finish:
2288         free(path);
2289         free(fpath);
2290         free(name);
2291
2292         if (d)
2293                 closedir(d);
2294
2295         return r;
2296 }
2297
2298 static void service_bus_name_owner_change(
2299                 Unit *u,
2300                 const char *name,
2301                 const char *old_owner,
2302                 const char *new_owner) {
2303
2304         Service *s = SERVICE(u);
2305
2306         assert(s);
2307         assert(name);
2308
2309         assert(streq(s->bus_name, name));
2310         assert(old_owner || new_owner);
2311
2312         if (old_owner && new_owner)
2313                 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2314         else if (old_owner)
2315                 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2316         else
2317                 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2318
2319         s->bus_name_good = !!new_owner;
2320
2321         if (s->type == SERVICE_DBUS) {
2322
2323                 /* service_enter_running() will figure out what to
2324                  * do */
2325                 if (s->state == SERVICE_RUNNING)
2326                         service_enter_running(s, true);
2327                 else if (s->state == SERVICE_START && new_owner)
2328                         service_enter_start_post(s);
2329
2330         } else if (new_owner &&
2331                    s->main_pid <= 0 &&
2332                    (s->state == SERVICE_START ||
2333                     s->state == SERVICE_START_POST ||
2334                     s->state == SERVICE_RUNNING ||
2335                     s->state == SERVICE_RELOAD)) {
2336
2337                 /* Try to acquire PID from bus service */
2338                 log_debug("Trying to acquire PID from D-Bus name...");
2339
2340                 bus_query_pid(u->meta.manager, name);
2341         }
2342 }
2343
2344 static void service_bus_query_pid_done(
2345                 Unit *u,
2346                 const char *name,
2347                 pid_t pid) {
2348
2349         Service *s = SERVICE(u);
2350
2351         assert(s);
2352         assert(name);
2353
2354         log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2355
2356         if (s->main_pid <= 0 &&
2357             (s->state == SERVICE_START ||
2358              s->state == SERVICE_START_POST ||
2359              s->state == SERVICE_RUNNING ||
2360              s->state == SERVICE_RELOAD))
2361                 s->main_pid = pid;
2362 }
2363
2364 int service_set_socket_fd(Service *s, int fd) {
2365         assert(s);
2366         assert(fd >= 0);
2367
2368         /* This is called by the socket code when instantiating a new
2369          * service for a stream socket and the socket needs to be
2370          * configured. */
2371
2372         if (UNIT(s)->meta.load_state != UNIT_LOADED)
2373                 return -EINVAL;
2374
2375         if (s->socket_fd >= 0)
2376                 return -EBUSY;
2377
2378         if (s->state != SERVICE_DEAD)
2379                 return -EAGAIN;
2380
2381         s->socket_fd = fd;
2382         s->got_socket_fd = true;
2383         return 0;
2384 }
2385
2386 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2387         [SERVICE_DEAD] = "dead",
2388         [SERVICE_START_PRE] = "start-pre",
2389         [SERVICE_START] = "start",
2390         [SERVICE_START_POST] = "start-post",
2391         [SERVICE_RUNNING] = "running",
2392         [SERVICE_EXITED] = "exited",
2393         [SERVICE_RELOAD] = "reload",
2394         [SERVICE_STOP] = "stop",
2395         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2396         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2397         [SERVICE_STOP_POST] = "stop-post",
2398         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2399         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2400         [SERVICE_MAINTAINANCE] = "maintainance",
2401         [SERVICE_AUTO_RESTART] = "auto-restart",
2402 };
2403
2404 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2405
2406 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2407         [SERVICE_ONCE] = "once",
2408         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2409         [SERVICE_RESTART_ALWAYS] = "restart-always",
2410 };
2411
2412 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2413
2414 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2415         [SERVICE_FORKING] = "forking",
2416         [SERVICE_SIMPLE] = "simple",
2417         [SERVICE_FINISH] = "finish",
2418         [SERVICE_DBUS] = "dbus"
2419 };
2420
2421 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2422
2423 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2424         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2425         [SERVICE_EXEC_START] = "ExecStart",
2426         [SERVICE_EXEC_START_POST] = "ExecStartPost",
2427         [SERVICE_EXEC_RELOAD] = "ExecReload",
2428         [SERVICE_EXEC_STOP] = "ExecStop",
2429         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2430 };
2431
2432 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2433
2434 const UnitVTable service_vtable = {
2435         .suffix = ".service",
2436
2437         .init = service_init,
2438         .done = service_done,
2439         .load = service_load,
2440
2441         .coldplug = service_coldplug,
2442
2443         .dump = service_dump,
2444
2445         .start = service_start,
2446         .stop = service_stop,
2447         .reload = service_reload,
2448
2449         .can_reload = service_can_reload,
2450
2451         .serialize = service_serialize,
2452         .deserialize_item = service_deserialize_item,
2453
2454         .active_state = service_active_state,
2455         .sub_state_to_string = service_sub_state_to_string,
2456
2457         .check_gc = service_check_gc,
2458         .check_snapshot = service_check_snapshot,
2459
2460         .sigchld_event = service_sigchld_event,
2461         .timer_event = service_timer_event,
2462
2463         .cgroup_notify_empty = service_cgroup_notify_event,
2464
2465         .bus_name_owner_change = service_bus_name_owner_change,
2466         .bus_query_pid_done = service_bus_query_pid_done,
2467
2468         .bus_message_handler = bus_service_message_handler,
2469
2470         .enumerate = service_enumerate
2471 };