chiark / gitweb /
manager: merge /etc/xdg/systemd/session and /etc/systemd/session
[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 ((r = sysv_exec_commands(s)) < 0)
595                 goto finish;
596
597         if (!s->sysv_runlevels || chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
598                 /* If there a runlevels configured for this service
599                  * but none of the standard ones, then we assume this
600                  * is some special kind of service (which might be
601                  * needed for early boot) and don't create any links
602                  * to it. */
603
604                 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0 ||
605                     (r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
606                         goto finish;
607
608         } else
609                 /* Don't timeout special services during boot (like fsck) */
610                 s->timeout_usec = 0;
611
612         /* Special setting for all SysV services */
613         s->valid_no_process = true;
614         s->kill_mode = KILL_PROCESS_GROUP;
615
616         u->meta.load_state = UNIT_LOADED;
617         r = 0;
618
619 finish:
620
621         if (f)
622                 fclose(f);
623
624         return r;
625 }
626
627 static int service_load_sysv_name(Service *s, const char *name) {
628         char **p;
629
630         assert(s);
631         assert(name);
632
633         STRV_FOREACH(p, UNIT(s)->meta.manager->sysvinit_path) {
634                 char *path;
635                 int r;
636
637                 if (asprintf(&path, "%s/%s", *p, name) < 0)
638                         return -ENOMEM;
639
640                 assert(endswith(path, ".service"));
641                 path[strlen(path)-8] = 0;
642
643                 r = service_load_sysv_path(s, path);
644
645                 if (r >= 0 && UNIT(s)->meta.load_state == UNIT_STUB) {
646                         /* Try Debian style .sh source'able init scripts */
647                         strcat(path, ".sh");
648                         r = service_load_sysv_path(s, path);
649                 }
650
651                 free(path);
652
653                 if (r >= 0 && UNIT(s)->meta.load_state == UNIT_STUB) {
654                         /* Try Suse style boot.xxxx init scripts */
655
656                         if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
657                                 return -ENOMEM;
658
659                         path[strlen(path)-8] = 0;
660                         r = service_load_sysv_path(s, path);
661                         free(path);
662                 }
663
664                 if (r < 0)
665                         return r;
666
667                 if ((UNIT(s)->meta.load_state != UNIT_STUB))
668                         break;
669         }
670
671         return 0;
672 }
673
674 static int service_load_sysv(Service *s) {
675         const char *t;
676         Iterator i;
677         int r;
678
679         assert(s);
680
681         /* Load service data from SysV init scripts, preferably with
682          * LSB headers ... */
683
684         if (strv_isempty(UNIT(s)->meta.manager->sysvinit_path))
685                 return 0;
686
687         if ((t = UNIT(s)->meta.id))
688                 if ((r = service_load_sysv_name(s, t)) < 0)
689                         return r;
690
691         if (UNIT(s)->meta.load_state == UNIT_STUB)
692                 SET_FOREACH(t, UNIT(s)->meta.names, i) {
693                         if (t == UNIT(s)->meta.id)
694                                 continue;
695
696                         if ((r == service_load_sysv_name(s, t)) < 0)
697                                 return r;
698
699                         if (UNIT(s)->meta.load_state != UNIT_STUB)
700                                 break;
701                 }
702
703         return 0;
704 }
705
706 static int service_add_bus_name(Service *s) {
707         char *n;
708         int r;
709
710         assert(s);
711         assert(s->bus_name);
712
713         if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
714                 return 0;
715
716         r = unit_merge_by_name(UNIT(s), n);
717         free(n);
718
719         return r;
720 }
721
722 static int service_verify(Service *s) {
723         assert(s);
724
725         if (UNIT(s)->meta.load_state != UNIT_LOADED)
726                 return 0;
727
728         if (!s->exec_command[SERVICE_EXEC_START]) {
729                 log_error("%s lacks ExecStart setting. Refusing.", UNIT(s)->meta.id);
730                 return -EINVAL;
731         }
732
733         if (s->type == SERVICE_DBUS && !s->bus_name) {
734                 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->meta.id);
735                 return -EINVAL;
736         }
737
738         return 0;
739 }
740
741 static int service_load(Unit *u) {
742         int r;
743         Service *s = SERVICE(u);
744
745         assert(s);
746
747         /* Load a .service file */
748         if ((r = unit_load_fragment(u)) < 0)
749                 return r;
750
751         /* Load a classic init script as a fallback, if we couldn't find anything */
752         if (u->meta.load_state == UNIT_STUB)
753                 if ((r = service_load_sysv(s)) < 0)
754                         return r;
755
756         /* Still nothing found? Then let's give up */
757         if (u->meta.load_state == UNIT_STUB)
758                 return -ENOENT;
759
760         /* We were able to load something, then let's add in the
761          * dropin directories. */
762         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
763                 return r;
764
765         /* This is a new unit? Then let's add in some extras */
766         if (u->meta.load_state == UNIT_LOADED) {
767                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
768                         return r;
769
770                 if ((r = unit_add_default_cgroup(u)) < 0)
771                         return r;
772
773                 if ((r = sysv_chkconfig_order(s)) < 0)
774                         return r;
775
776                 if (s->bus_name) {
777                         if ((r = service_add_bus_name(s)) < 0)
778                                 return r;
779
780                         if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
781                             return r;
782                 }
783         }
784
785         return service_verify(s);
786 }
787
788 static void service_dump(Unit *u, FILE *f, const char *prefix) {
789
790         ServiceExecCommand c;
791         Service *s = SERVICE(u);
792         const char *prefix2;
793         char *p2;
794
795         assert(s);
796
797         p2 = strappend(prefix, "\t");
798         prefix2 = p2 ? p2 : prefix;
799
800         fprintf(f,
801                 "%sService State: %s\n"
802                 "%sPermissionsStartOnly: %s\n"
803                 "%sRootDirectoryStartOnly: %s\n"
804                 "%sValidNoProcess: %s\n"
805                 "%sKillMode: %s\n"
806                 "%sType: %s\n",
807                 prefix, service_state_to_string(s->state),
808                 prefix, yes_no(s->permissions_start_only),
809                 prefix, yes_no(s->root_directory_start_only),
810                 prefix, yes_no(s->valid_no_process),
811                 prefix, kill_mode_to_string(s->kill_mode),
812                 prefix, service_type_to_string(s->type));
813
814         if (s->control_pid > 0)
815                 fprintf(f,
816                         "%sControl PID: %llu\n",
817                         prefix, (unsigned long long) s->control_pid);
818
819         if (s->main_pid > 0)
820                 fprintf(f,
821                         "%sMain PID: %llu\n",
822                         prefix, (unsigned long long) s->main_pid);
823
824         if (s->pid_file)
825                 fprintf(f,
826                         "%sPIDFile: %s\n",
827                         prefix, s->pid_file);
828
829         if (s->bus_name)
830                 fprintf(f,
831                         "%sBusName: %s\n"
832                         "%sBus Name Good: %s\n",
833                         prefix, s->bus_name,
834                         prefix, yes_no(s->bus_name_good));
835
836         exec_context_dump(&s->exec_context, f, prefix);
837
838         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
839
840                 if (!s->exec_command[c])
841                         continue;
842
843                 fprintf(f, "%s-> %s:\n",
844                         prefix, service_exec_command_to_string(c));
845
846                 exec_command_dump_list(s->exec_command[c], f, prefix2);
847         }
848
849         if (s->sysv_path)
850                 fprintf(f,
851                         "%sSysV Init Script Path: %s\n"
852                         "%sSysV Init Script has LSB Header: %s\n",
853                         prefix, s->sysv_path,
854                         prefix, yes_no(s->sysv_has_lsb));
855
856         if (s->sysv_start_priority >= 0)
857                 fprintf(f,
858                         "%sSysVStartPriority: %i\n",
859                         prefix, s->sysv_start_priority);
860
861         if (s->sysv_runlevels)
862                 fprintf(f, "%sSysVRunLevels: %s\n",
863                         prefix, s->sysv_runlevels);
864
865         free(p2);
866 }
867
868 static int service_load_pid_file(Service *s) {
869         char *k;
870         unsigned long p;
871         int r;
872
873         assert(s);
874
875         if (s->main_pid_known)
876                 return 0;
877
878         assert(s->main_pid <= 0);
879
880         if (!s->pid_file)
881                 return -ENOENT;
882
883         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
884                 return r;
885
886         if ((r = safe_atolu(k, &p)) < 0) {
887                 free(k);
888                 return r;
889         }
890
891         if ((unsigned long) (pid_t) p != p)
892                 return -ERANGE;
893
894         if (kill((pid_t) p, 0) < 0 && errno != EPERM) {
895                 log_warning("PID %llu read from file %s does not exist. Your service or init script might be broken.",
896                             (unsigned long long) p, s->pid_file);
897                 return -ESRCH;
898         }
899
900         if ((r = unit_watch_pid(UNIT(s), (pid_t) p)) < 0)
901                 /* FIXME: we need to do something here */
902                 return r;
903
904         s->main_pid = (pid_t) p;
905         s->main_pid_known = true;
906
907         return 0;
908 }
909
910 static int service_get_sockets(Service *s, Set **_set) {
911         Set *set;
912         Iterator i;
913         char *t;
914         int r;
915
916         assert(s);
917         assert(_set);
918
919         /* Collects all Socket objects that belong to this
920          * service. Note that a service might have multiple sockets
921          * via multiple names. */
922
923         if (!(set = set_new(NULL, NULL)))
924                 return -ENOMEM;
925
926         SET_FOREACH(t, UNIT(s)->meta.names, i) {
927                 char *k;
928                 Unit *p;
929
930                 /* Look for all socket objects that go by any of our
931                  * units and collect their fds */
932
933                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
934                         r = -ENOMEM;
935                         goto fail;
936                 }
937
938                 p = manager_get_unit(UNIT(s)->meta.manager, k);
939                 free(k);
940
941                 if (!p)
942                         continue;
943
944                 if ((r = set_put(set, p)) < 0)
945                         goto fail;
946         }
947
948         *_set = set;
949         return 0;
950
951 fail:
952         set_free(set);
953         return r;
954 }
955
956 static int service_notify_sockets_dead(Service *s) {
957         Iterator i;
958         Set *set;
959         Socket *sock;
960         int r;
961
962         assert(s);
963
964         /* Notifies all our sockets when we die */
965         if ((r = service_get_sockets(s, &set)) < 0)
966                 return r;
967
968         SET_FOREACH(sock, set, i)
969                 socket_notify_service_dead(sock);
970
971         set_free(set);
972
973         return 0;
974 }
975
976 static void service_set_state(Service *s, ServiceState state) {
977         ServiceState old_state;
978         assert(s);
979
980         old_state = s->state;
981         s->state = state;
982
983         if (state != SERVICE_START_PRE &&
984             state != SERVICE_START &&
985             state != SERVICE_START_POST &&
986             state != SERVICE_RELOAD &&
987             state != SERVICE_STOP &&
988             state != SERVICE_STOP_SIGTERM &&
989             state != SERVICE_STOP_SIGKILL &&
990             state != SERVICE_STOP_POST &&
991             state != SERVICE_FINAL_SIGTERM &&
992             state != SERVICE_FINAL_SIGKILL &&
993             state != SERVICE_AUTO_RESTART)
994                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
995
996         if (state != SERVICE_START &&
997             state != SERVICE_START_POST &&
998             state != SERVICE_RUNNING &&
999             state != SERVICE_RELOAD &&
1000             state != SERVICE_STOP &&
1001             state != SERVICE_STOP_SIGTERM &&
1002             state != SERVICE_STOP_SIGKILL)
1003                 service_unwatch_main_pid(s);
1004
1005         if (state != SERVICE_START_PRE &&
1006             state != SERVICE_START &&
1007             state != SERVICE_START_POST &&
1008             state != SERVICE_RELOAD &&
1009             state != SERVICE_STOP &&
1010             state != SERVICE_STOP_SIGTERM &&
1011             state != SERVICE_STOP_SIGKILL &&
1012             state != SERVICE_STOP_POST &&
1013             state != SERVICE_FINAL_SIGTERM &&
1014             state != SERVICE_FINAL_SIGKILL) {
1015                 service_unwatch_control_pid(s);
1016                 s->control_command = NULL;
1017                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1018         }
1019
1020         if (state == SERVICE_DEAD ||
1021             state == SERVICE_STOP ||
1022             state == SERVICE_STOP_SIGTERM ||
1023             state == SERVICE_STOP_SIGKILL ||
1024             state == SERVICE_STOP_POST ||
1025             state == SERVICE_FINAL_SIGTERM ||
1026             state == SERVICE_FINAL_SIGKILL ||
1027             state == SERVICE_MAINTAINANCE ||
1028             state == SERVICE_AUTO_RESTART)
1029                 service_notify_sockets_dead(s);
1030
1031         if (state != SERVICE_START_PRE &&
1032             state != SERVICE_START &&
1033             !(state == SERVICE_DEAD && UNIT(s)->meta.job))
1034                 service_close_socket_fd(s);
1035
1036         if (old_state != state)
1037                 log_debug("%s changed %s -> %s", UNIT(s)->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1038
1039         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1040 }
1041
1042 static int service_coldplug(Unit *u) {
1043         Service *s = SERVICE(u);
1044         int r;
1045
1046         assert(s);
1047         assert(s->state == SERVICE_DEAD);
1048
1049         if (s->deserialized_state != s->state) {
1050
1051                 if (s->deserialized_state == SERVICE_START_PRE ||
1052                     s->deserialized_state == SERVICE_START ||
1053                     s->deserialized_state == SERVICE_START_POST ||
1054                     s->deserialized_state == SERVICE_RELOAD ||
1055                     s->deserialized_state == SERVICE_STOP ||
1056                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1057                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1058                     s->deserialized_state == SERVICE_STOP_POST ||
1059                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1060                     s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1061                     s->deserialized_state == SERVICE_AUTO_RESTART) {
1062
1063                         if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1064                                 usec_t k;
1065
1066                                 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1067
1068                                 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1069                                         return r;
1070                         }
1071                 }
1072
1073                 if ((s->deserialized_state == SERVICE_START &&
1074                      (s->type == SERVICE_FORKING ||
1075                       s->type == SERVICE_DBUS)) ||
1076                     s->deserialized_state == SERVICE_START_POST ||
1077                     s->deserialized_state == SERVICE_RUNNING ||
1078                     s->deserialized_state == SERVICE_RELOAD ||
1079                     s->deserialized_state == SERVICE_STOP ||
1080                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1081                     s->deserialized_state == SERVICE_STOP_SIGKILL)
1082                         if (s->main_pid > 0)
1083                                 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1084                                         return r;
1085
1086                 if (s->deserialized_state == SERVICE_START_PRE ||
1087                     s->deserialized_state == SERVICE_START ||
1088                     s->deserialized_state == SERVICE_START_POST ||
1089                     s->deserialized_state == SERVICE_RELOAD ||
1090                     s->deserialized_state == SERVICE_STOP ||
1091                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1092                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1093                     s->deserialized_state == SERVICE_STOP_POST ||
1094                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1095                     s->deserialized_state == SERVICE_FINAL_SIGKILL)
1096                         if (s->control_pid > 0)
1097                                 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1098                                         return r;
1099
1100                 service_set_state(s, s->deserialized_state);
1101         }
1102
1103         return 0;
1104 }
1105
1106 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1107         Iterator i;
1108         int r;
1109         int *rfds = NULL;
1110         unsigned rn_fds = 0;
1111         Set *set;
1112         Socket *sock;
1113
1114         assert(s);
1115         assert(fds);
1116         assert(n_fds);
1117
1118         if ((r = service_get_sockets(s, &set)) < 0)
1119                 return r;
1120
1121         SET_FOREACH(sock, set, i) {
1122                 int *cfds;
1123                 unsigned cn_fds;
1124
1125                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1126                         goto fail;
1127
1128                 if (!cfds)
1129                         continue;
1130
1131                 if (!rfds) {
1132                         rfds = cfds;
1133                         rn_fds = cn_fds;
1134                 } else {
1135                         int *t;
1136
1137                         if (!(t = new(int, rn_fds+cn_fds))) {
1138                                 free(cfds);
1139                                 r = -ENOMEM;
1140                                 goto fail;
1141                         }
1142
1143                         memcpy(t, rfds, rn_fds);
1144                         memcpy(t+rn_fds, cfds, cn_fds);
1145                         free(rfds);
1146                         free(cfds);
1147
1148                         rfds = t;
1149                         rn_fds = rn_fds+cn_fds;
1150                 }
1151         }
1152
1153         *fds = rfds;
1154         *n_fds = rn_fds;
1155
1156         set_free(set);
1157
1158         return 0;
1159
1160 fail:
1161         set_free(set);
1162         free(rfds);
1163
1164         return r;
1165 }
1166
1167 static int service_spawn(
1168                 Service *s,
1169                 ExecCommand *c,
1170                 bool timeout,
1171                 bool pass_fds,
1172                 bool apply_permissions,
1173                 bool apply_chroot,
1174                 pid_t *_pid) {
1175
1176         pid_t pid;
1177         int r;
1178         int *fds = NULL;
1179         unsigned n_fds = 0;
1180         char **argv;
1181
1182         assert(s);
1183         assert(c);
1184         assert(_pid);
1185
1186         if (pass_fds) {
1187                 if (s->socket_fd >= 0) {
1188                         fds = &s->socket_fd;
1189                         n_fds = 1;
1190                 } else if ((r = service_collect_fds(s, &fds, &n_fds)) < 0)
1191                         goto fail;
1192         }
1193
1194         if (timeout && s->timeout_usec) {
1195                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1196                         goto fail;
1197         } else
1198                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1199
1200         if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1201                 r = -ENOMEM;
1202                 goto fail;
1203         }
1204
1205         r = exec_spawn(c,
1206                        argv,
1207                        &s->exec_context,
1208                        fds, n_fds,
1209                        s->meta.manager->environment,
1210                        apply_permissions,
1211                        apply_chroot,
1212                        UNIT(s)->meta.manager->confirm_spawn,
1213                        UNIT(s)->meta.cgroup_bondings,
1214                        &pid);
1215
1216         strv_free(argv);
1217         if (r < 0)
1218                 goto fail;
1219
1220         if (fds) {
1221                 if (s->socket_fd >= 0)
1222                         service_close_socket_fd(s);
1223                 else
1224                         free(fds);
1225         }
1226
1227         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1228                 /* FIXME: we need to do something here */
1229                 goto fail;
1230
1231         *_pid = pid;
1232
1233         return 0;
1234
1235 fail:
1236         free(fds);
1237
1238         if (timeout)
1239                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1240
1241         return r;
1242 }
1243
1244 static int main_pid_good(Service *s) {
1245         assert(s);
1246
1247         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1248          * don't know */
1249
1250         /* If we know the pid file, then lets just check if it is
1251          * still valid */
1252         if (s->main_pid_known)
1253                 return s->main_pid > 0;
1254
1255         /* We don't know the pid */
1256         return -EAGAIN;
1257 }
1258
1259 static int control_pid_good(Service *s) {
1260         assert(s);
1261
1262         return s->control_pid > 0;
1263 }
1264
1265 static int cgroup_good(Service *s) {
1266         int r;
1267
1268         assert(s);
1269
1270         if (s->valid_no_process)
1271                 return -EAGAIN;
1272
1273         if ((r = cgroup_bonding_is_empty_list(UNIT(s)->meta.cgroup_bondings)) < 0)
1274                 return r;
1275
1276         return !r;
1277 }
1278
1279 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1280         int r;
1281         assert(s);
1282
1283         if (!success)
1284                 s->failure = true;
1285
1286         if (allow_restart &&
1287             s->allow_restart &&
1288             (s->restart == SERVICE_RESTART_ALWAYS ||
1289              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1290
1291                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1292                         goto fail;
1293
1294                 service_set_state(s, SERVICE_AUTO_RESTART);
1295         } else
1296                 service_set_state(s, s->failure ? SERVICE_MAINTAINANCE : SERVICE_DEAD);
1297
1298         return;
1299
1300 fail:
1301         log_warning("%s failed to run install restart timer: %s", UNIT(s)->meta.id, strerror(-r));
1302         service_enter_dead(s, false, false);
1303 }
1304
1305 static void service_enter_signal(Service *s, ServiceState state, bool success);
1306
1307 static void service_enter_stop_post(Service *s, bool success) {
1308         int r;
1309         assert(s);
1310
1311         if (!success)
1312                 s->failure = true;
1313
1314         service_unwatch_control_pid(s);
1315
1316         s->control_command_id = SERVICE_EXEC_STOP_POST;
1317         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1318                 if ((r = service_spawn(s,
1319                                        s->control_command,
1320                                        true,
1321                                        false,
1322                                        !s->permissions_start_only,
1323                                        !s->root_directory_start_only,
1324                                        &s->control_pid)) < 0)
1325                         goto fail;
1326
1327
1328                 service_set_state(s, SERVICE_STOP_POST);
1329         } else
1330                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1331
1332         return;
1333
1334 fail:
1335         log_warning("%s failed to run stop-post executable: %s", UNIT(s)->meta.id, strerror(-r));
1336         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1337 }
1338
1339 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1340         int r;
1341         bool sent = false;
1342
1343         assert(s);
1344
1345         if (!success)
1346                 s->failure = true;
1347
1348         if (s->kill_mode != KILL_NONE) {
1349                 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1350
1351                 if (s->kill_mode == KILL_CONTROL_GROUP) {
1352
1353                         if ((r = cgroup_bonding_kill_list(UNIT(s)->meta.cgroup_bondings, sig)) < 0) {
1354                                 if (r != -EAGAIN && r != -ESRCH)
1355                                         goto fail;
1356                         } else
1357                                 sent = true;
1358                 }
1359
1360                 if (!sent) {
1361                         r = 0;
1362
1363                         if (s->main_pid > 0) {
1364                                 if (kill(s->kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1365                                         r = -errno;
1366                                 else
1367                                         sent = true;
1368                         }
1369
1370                         if (s->control_pid > 0) {
1371                                 if (kill(s->kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1372                                         r = -errno;
1373                                 else
1374                                         sent = true;
1375                         }
1376
1377                         if (r < 0)
1378                                 goto fail;
1379                 }
1380         }
1381
1382         if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1383                 if (s->timeout_usec > 0)
1384                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1385                                 goto fail;
1386
1387                 service_set_state(s, state);
1388         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1389                 service_enter_stop_post(s, true);
1390         else
1391                 service_enter_dead(s, true, true);
1392
1393         return;
1394
1395 fail:
1396         log_warning("%s failed to kill processes: %s", UNIT(s)->meta.id, strerror(-r));
1397
1398         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1399                 service_enter_stop_post(s, false);
1400         else
1401                 service_enter_dead(s, false, true);
1402 }
1403
1404 static void service_enter_stop(Service *s, bool success) {
1405         int r;
1406         assert(s);
1407
1408         if (!success)
1409                 s->failure = true;
1410
1411         service_unwatch_control_pid(s);
1412
1413         s->control_command_id = SERVICE_EXEC_STOP;
1414         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1415                 if ((r = service_spawn(s,
1416                                        s->control_command,
1417                                        true,
1418                                        false,
1419                                        !s->permissions_start_only,
1420                                        !s->root_directory_start_only,
1421                                        &s->control_pid)) < 0)
1422                         goto fail;
1423
1424                 service_set_state(s, SERVICE_STOP);
1425         } else
1426                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1427
1428         return;
1429
1430 fail:
1431         log_warning("%s failed to run stop executable: %s", UNIT(s)->meta.id, strerror(-r));
1432         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1433 }
1434
1435 static void service_enter_running(Service *s, bool success) {
1436         assert(s);
1437
1438         if (!success)
1439                 s->failure = true;
1440
1441         if (main_pid_good(s) != 0 &&
1442             cgroup_good(s) != 0 &&
1443             (s->bus_name_good || s->type != SERVICE_DBUS))
1444                 service_set_state(s, SERVICE_RUNNING);
1445         else if (s->valid_no_process)
1446                 service_set_state(s, SERVICE_EXITED);
1447         else
1448                 service_enter_stop(s, true);
1449 }
1450
1451 static void service_enter_start_post(Service *s) {
1452         int r;
1453         assert(s);
1454
1455         service_unwatch_control_pid(s);
1456
1457         s->control_command_id = SERVICE_EXEC_START_POST;
1458         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1459                 if ((r = service_spawn(s,
1460                                        s->control_command,
1461                                        true,
1462                                        false,
1463                                        !s->permissions_start_only,
1464                                        !s->root_directory_start_only,
1465                                        &s->control_pid)) < 0)
1466                         goto fail;
1467
1468
1469                 service_set_state(s, SERVICE_START_POST);
1470         } else
1471                 service_enter_running(s, true);
1472
1473         return;
1474
1475 fail:
1476         log_warning("%s failed to run start-post executable: %s", UNIT(s)->meta.id, strerror(-r));
1477         service_enter_stop(s, false);
1478 }
1479
1480 static void service_enter_start(Service *s) {
1481         pid_t pid;
1482         int r;
1483
1484         assert(s);
1485
1486         assert(s->exec_command[SERVICE_EXEC_START]);
1487         assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1488
1489         if (s->type == SERVICE_FORKING)
1490                 service_unwatch_control_pid(s);
1491         else
1492                 service_unwatch_main_pid(s);
1493
1494         if ((r = service_spawn(s,
1495                                s->exec_command[SERVICE_EXEC_START],
1496                                s->type == SERVICE_FORKING || s->type == SERVICE_DBUS,
1497                                true,
1498                                true,
1499                                true,
1500                                &pid)) < 0)
1501                 goto fail;
1502
1503         if (s->type == SERVICE_SIMPLE) {
1504                 /* For simple services we immediately start
1505                  * the START_POST binaries. */
1506
1507                 s->main_pid = pid;
1508                 s->main_pid_known = true;
1509
1510                 service_enter_start_post(s);
1511
1512         } else  if (s->type == SERVICE_FORKING) {
1513
1514                 /* For forking services we wait until the start
1515                  * process exited. */
1516
1517                 s->control_pid = pid;
1518
1519                 s->control_command_id = SERVICE_EXEC_START;
1520                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1521                 service_set_state(s, SERVICE_START);
1522
1523         } else if (s->type == SERVICE_FINISH ||
1524                    s->type == SERVICE_DBUS) {
1525
1526                 /* For finishing services we wait until the start
1527                  * process exited, too, but it is our main process. */
1528
1529                 /* For D-Bus services we know the main pid right away,
1530                  * but wait for the bus name to appear on the bus. */
1531
1532                 s->main_pid = pid;
1533                 s->main_pid_known = true;
1534
1535                 service_set_state(s, SERVICE_START);
1536         } else
1537                 assert_not_reached("Unknown service type");
1538
1539         return;
1540
1541 fail:
1542         log_warning("%s failed to run start exectuable: %s", UNIT(s)->meta.id, strerror(-r));
1543         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1544 }
1545
1546 static void service_enter_start_pre(Service *s) {
1547         int r;
1548
1549         assert(s);
1550
1551         service_unwatch_control_pid(s);
1552
1553         s->control_command_id = SERVICE_EXEC_START_PRE;
1554         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1555                 if ((r = service_spawn(s,
1556                                        s->control_command,
1557                                        true,
1558                                        false,
1559                                        !s->permissions_start_only,
1560                                        !s->root_directory_start_only,
1561                                        &s->control_pid)) < 0)
1562                         goto fail;
1563
1564                 service_set_state(s, SERVICE_START_PRE);
1565         } else
1566                 service_enter_start(s);
1567
1568         return;
1569
1570 fail:
1571         log_warning("%s failed to run start-pre executable: %s", UNIT(s)->meta.id, strerror(-r));
1572         service_enter_dead(s, false, true);
1573 }
1574
1575 static void service_enter_restart(Service *s) {
1576         int r;
1577         assert(s);
1578
1579         service_enter_dead(s, true, false);
1580
1581         if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL)) < 0)
1582                 goto fail;
1583
1584         log_debug("%s scheduled restart job.", UNIT(s)->meta.id);
1585         return;
1586
1587 fail:
1588
1589         log_warning("%s failed to schedule restart job: %s", UNIT(s)->meta.id, strerror(-r));
1590         service_enter_dead(s, false, false);
1591 }
1592
1593 static void service_enter_reload(Service *s) {
1594         int r;
1595
1596         assert(s);
1597
1598         service_unwatch_control_pid(s);
1599
1600         s->control_command_id = SERVICE_EXEC_RELOAD;
1601         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1602                 if ((r = service_spawn(s,
1603                                        s->control_command,
1604                                        true,
1605                                        false,
1606                                        !s->permissions_start_only,
1607                                        !s->root_directory_start_only,
1608                                        &s->control_pid)) < 0)
1609                         goto fail;
1610
1611                 service_set_state(s, SERVICE_RELOAD);
1612         } else
1613                 service_enter_running(s, true);
1614
1615         return;
1616
1617 fail:
1618         log_warning("%s failed to run reload executable: %s", UNIT(s)->meta.id, strerror(-r));
1619         service_enter_stop(s, false);
1620 }
1621
1622 static void service_run_next(Service *s, bool success) {
1623         int r;
1624
1625         assert(s);
1626         assert(s->control_command);
1627         assert(s->control_command->command_next);
1628
1629         if (!success)
1630                 s->failure = true;
1631
1632         s->control_command = s->control_command->command_next;
1633
1634         service_unwatch_control_pid(s);
1635
1636         if ((r = service_spawn(s,
1637                                s->control_command,
1638                                true,
1639                                false,
1640                                !s->permissions_start_only,
1641                                !s->root_directory_start_only,
1642                                &s->control_pid)) < 0)
1643                 goto fail;
1644
1645         return;
1646
1647 fail:
1648         log_warning("%s failed to run spawn next executable: %s", UNIT(s)->meta.id, strerror(-r));
1649
1650         if (s->state == SERVICE_START_PRE)
1651                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1652         else if (s->state == SERVICE_STOP)
1653                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1654         else if (s->state == SERVICE_STOP_POST)
1655                 service_enter_dead(s, false, true);
1656         else
1657                 service_enter_stop(s, false);
1658 }
1659
1660 static int service_start(Unit *u) {
1661         Service *s = SERVICE(u);
1662
1663         assert(s);
1664
1665         /* We cannot fulfill this request right now, try again later
1666          * please! */
1667         if (s->state == SERVICE_STOP ||
1668             s->state == SERVICE_STOP_SIGTERM ||
1669             s->state == SERVICE_STOP_SIGKILL ||
1670             s->state == SERVICE_STOP_POST ||
1671             s->state == SERVICE_FINAL_SIGTERM ||
1672             s->state == SERVICE_FINAL_SIGKILL)
1673                 return -EAGAIN;
1674
1675         /* Already on it! */
1676         if (s->state == SERVICE_START_PRE ||
1677             s->state == SERVICE_START ||
1678             s->state == SERVICE_START_POST)
1679                 return 0;
1680
1681         assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTAINANCE || s->state == SERVICE_AUTO_RESTART);
1682
1683         /* Make sure we don't enter a busy loop of some kind. */
1684         if (!ratelimit_test(&s->ratelimit)) {
1685                 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1686                 return -EAGAIN;
1687         }
1688
1689         s->failure = false;
1690         s->main_pid_known = false;
1691         s->allow_restart = true;
1692
1693         service_enter_start_pre(s);
1694         return 0;
1695 }
1696
1697 static int service_stop(Unit *u) {
1698         Service *s = SERVICE(u);
1699
1700         assert(s);
1701
1702         /* Cannot do this now */
1703         if (s->state == SERVICE_START_PRE ||
1704             s->state == SERVICE_START ||
1705             s->state == SERVICE_START_POST ||
1706             s->state == SERVICE_RELOAD)
1707                 return -EAGAIN;
1708
1709         /* Already on it */
1710         if (s->state == SERVICE_STOP ||
1711             s->state == SERVICE_STOP_SIGTERM ||
1712             s->state == SERVICE_STOP_SIGKILL ||
1713             s->state == SERVICE_STOP_POST ||
1714             s->state == SERVICE_FINAL_SIGTERM ||
1715             s->state == SERVICE_FINAL_SIGKILL)
1716                 return 0;
1717
1718         if (s->state == SERVICE_AUTO_RESTART) {
1719                 service_set_state(s, SERVICE_DEAD);
1720                 return 0;
1721         }
1722
1723         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1724
1725         /* This is a user request, so don't do restarts on this
1726          * shutdown. */
1727         s->allow_restart = false;
1728
1729         service_enter_stop(s, true);
1730         return 0;
1731 }
1732
1733 static int service_reload(Unit *u) {
1734         Service *s = SERVICE(u);
1735
1736         assert(s);
1737
1738         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1739
1740         service_enter_reload(s);
1741         return 0;
1742 }
1743
1744 static bool service_can_reload(Unit *u) {
1745         Service *s = SERVICE(u);
1746
1747         assert(s);
1748
1749         return !!s->exec_command[SERVICE_EXEC_RELOAD];
1750 }
1751
1752 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1753         Service *s = SERVICE(u);
1754
1755         assert(u);
1756         assert(f);
1757         assert(fds);
1758
1759         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1760         unit_serialize_item(u, f, "failure", yes_no(s->failure));
1761
1762         if (s->control_pid > 0)
1763                 unit_serialize_item_format(u, f, "control-pid", "%u", (unsigned) (s->control_pid));
1764
1765         if (s->main_pid > 0)
1766                 unit_serialize_item_format(u, f, "main-pid", "%u", (unsigned) (s->main_pid));
1767
1768         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1769
1770         /* There's a minor uncleanliness here: if there are multiple
1771          * commands attached here, we will start from the first one
1772          * again */
1773         if (s->control_command_id >= 0)
1774                 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
1775
1776         if (s->socket_fd >= 0) {
1777                 int copy;
1778
1779                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1780                         return copy;
1781
1782                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1783         }
1784
1785         return 0;
1786 }
1787
1788 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1789         Service *s = SERVICE(u);
1790         int r;
1791
1792         assert(u);
1793         assert(key);
1794         assert(value);
1795         assert(fds);
1796
1797         if (streq(key, "state")) {
1798                 ServiceState state;
1799
1800                 if ((state = service_state_from_string(value)) < 0)
1801                         log_debug("Failed to parse state value %s", value);
1802                 else
1803                         s->deserialized_state = state;
1804         } else if (streq(key, "failure")) {
1805                 int b;
1806
1807                 if ((b = parse_boolean(value)) < 0)
1808                         log_debug("Failed to parse failure value %s", value);
1809                 else
1810                         s->failure = b || s->failure;
1811         } else if (streq(key, "control-pid")) {
1812                 unsigned pid;
1813
1814                 if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
1815                         log_debug("Failed to parse control-pid value %s", value);
1816                 else
1817                         s->control_pid = (pid_t) pid;
1818         } else if (streq(key, "main-pid")) {
1819                 unsigned pid;
1820
1821                 if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
1822                         log_debug("Failed to parse main-pid value %s", value);
1823                 else
1824                         s->main_pid = (pid_t) pid;
1825         } else if (streq(key, "main-pid-known")) {
1826                 int b;
1827
1828                 if ((b = parse_boolean(value)) < 0)
1829                         log_debug("Failed to parse main-pid-known value %s", value);
1830                 else
1831                         s->main_pid_known = b;
1832         } else if (streq(key, "control-command")) {
1833                 ServiceExecCommand id;
1834
1835                 if ((id = service_exec_command_from_string(value)) < 0)
1836                         log_debug("Failed to parse exec-command value %s", value);
1837                 else {
1838                         s->control_command_id = id;
1839                         s->control_command = s->exec_command[id];
1840                 }
1841         } else if (streq(key, "socket-fd")) {
1842                 int fd;
1843
1844                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1845                         log_debug("Failed to parse socket-fd value %s", value);
1846                 else {
1847
1848                         if (s->socket_fd >= 0)
1849                                 close_nointr_nofail(s->socket_fd);
1850                         s->socket_fd = fdset_remove(fds, fd);
1851                 }
1852         } else
1853                 log_debug("Unknown serialization key '%s'", key);
1854
1855         return 0;
1856 }
1857
1858 static UnitActiveState service_active_state(Unit *u) {
1859         assert(u);
1860
1861         return state_translation_table[SERVICE(u)->state];
1862 }
1863
1864 static const char *service_sub_state_to_string(Unit *u) {
1865         assert(u);
1866
1867         return service_state_to_string(SERVICE(u)->state);
1868 }
1869
1870 static bool service_check_gc(Unit *u) {
1871         Service *s = SERVICE(u);
1872
1873         assert(s);
1874
1875         return !!s->sysv_path;
1876 }
1877
1878 static bool service_check_snapshot(Unit *u) {
1879         Service *s = SERVICE(u);
1880
1881         assert(s);
1882
1883         return !s->got_socket_fd;
1884 }
1885
1886 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1887         Service *s = SERVICE(u);
1888         bool success;
1889
1890         assert(s);
1891         assert(pid >= 0);
1892
1893         success = code == CLD_EXITED && status == 0;
1894         s->failure = s->failure || !success;
1895
1896         if (s->main_pid == pid) {
1897
1898                 exec_status_fill(&s->main_exec_status, pid, code, status);
1899                 s->main_pid = 0;
1900
1901                 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_FINISH) {
1902                         assert(s->exec_command[SERVICE_EXEC_START]);
1903                         s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
1904                 }
1905
1906                 log_debug("%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
1907
1908                 /* The service exited, so the service is officially
1909                  * gone. */
1910
1911                 switch (s->state) {
1912
1913                 case SERVICE_START_POST:
1914                 case SERVICE_RELOAD:
1915                 case SERVICE_STOP:
1916                         /* Need to wait until the operation is
1917                          * done */
1918                         break;
1919
1920                 case SERVICE_START:
1921                         assert(s->type == SERVICE_FINISH);
1922
1923                         /* This was our main goal, so let's go on */
1924                         if (success)
1925                                 service_enter_start_post(s);
1926                         else
1927                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1928                         break;
1929
1930                 case SERVICE_RUNNING:
1931                         service_enter_running(s, success);
1932                         break;
1933
1934                 case SERVICE_STOP_SIGTERM:
1935                 case SERVICE_STOP_SIGKILL:
1936
1937                         if (!control_pid_good(s))
1938                                 service_enter_stop_post(s, success);
1939
1940                         /* If there is still a control process, wait for that first */
1941                         break;
1942
1943                 default:
1944                         assert_not_reached("Uh, main process died at wrong time.");
1945                 }
1946
1947         } else if (s->control_pid == pid) {
1948
1949                 if (s->control_command)
1950                         exec_status_fill(&s->control_command->exec_status, pid, code, status);
1951
1952                 s->control_pid = 0;
1953
1954                 log_debug("%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1955
1956                 /* If we are shutting things down anyway we
1957                  * don't care about failing commands. */
1958
1959                 if (s->control_command && s->control_command->command_next && success) {
1960
1961                         /* There is another command to *
1962                          * execute, so let's do that. */
1963
1964                         log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
1965                         service_run_next(s, success);
1966
1967                 } else {
1968                         /* No further commands for this step, so let's
1969                          * figure out what to do next */
1970
1971                         s->control_command = NULL;
1972                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1973
1974                         log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
1975
1976                         switch (s->state) {
1977
1978                         case SERVICE_START_PRE:
1979                                 if (success)
1980                                         service_enter_start(s);
1981                                 else
1982                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1983                                 break;
1984
1985                         case SERVICE_START:
1986                                 assert(s->type == SERVICE_FORKING);
1987
1988                                 /* Let's try to load the pid
1989                                  * file here if we can. We
1990                                  * ignore the return value,
1991                                  * since the PID file might
1992                                  * actually be created by a
1993                                  * START_POST script */
1994
1995                                 if (success) {
1996                                         if (s->pid_file)
1997                                                 service_load_pid_file(s);
1998
1999                                         service_enter_start_post(s);
2000                                 } else
2001                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2002
2003                                 break;
2004
2005                         case SERVICE_START_POST:
2006                                 if (success && s->pid_file && !s->main_pid_known) {
2007                                         int r;
2008
2009                                         /* Hmm, let's see if we can
2010                                          * load the pid now after the
2011                                          * start-post scripts got
2012                                          * executed. */
2013
2014                                         if ((r = service_load_pid_file(s)) < 0)
2015                                                 log_warning("%s: failed to load PID file %s: %s", UNIT(s)->meta.id, s->pid_file, strerror(-r));
2016                                 }
2017
2018                                 /* Fall through */
2019
2020                         case SERVICE_RELOAD:
2021                                 if (success)
2022                                         service_enter_running(s, true);
2023                                 else
2024                                         service_enter_stop(s, false);
2025
2026                                 break;
2027
2028                         case SERVICE_STOP:
2029                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2030                                 break;
2031
2032                         case SERVICE_STOP_SIGTERM:
2033                         case SERVICE_STOP_SIGKILL:
2034                                 if (main_pid_good(s) <= 0)
2035                                         service_enter_stop_post(s, success);
2036
2037                                 /* If there is still a service
2038                                  * process around, wait until
2039                                  * that one quit, too */
2040                                 break;
2041
2042                         case SERVICE_STOP_POST:
2043                         case SERVICE_FINAL_SIGTERM:
2044                         case SERVICE_FINAL_SIGKILL:
2045                                 service_enter_dead(s, success, true);
2046                                 break;
2047
2048                         default:
2049                                 assert_not_reached("Uh, control process died at wrong time.");
2050                         }
2051                 }
2052         } else
2053                 assert_not_reached("Got SIGCHLD for unkown PID");
2054 }
2055
2056 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2057         Service *s = SERVICE(u);
2058
2059         assert(s);
2060         assert(elapsed == 1);
2061
2062         assert(w == &s->timer_watch);
2063
2064         switch (s->state) {
2065
2066         case SERVICE_START_PRE:
2067         case SERVICE_START:
2068                 log_warning("%s operation timed out. Terminating.", u->meta.id);
2069                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2070                 break;
2071
2072         case SERVICE_START_POST:
2073         case SERVICE_RELOAD:
2074                 log_warning("%s operation timed out. Stopping.", u->meta.id);
2075                 service_enter_stop(s, false);
2076                 break;
2077
2078         case SERVICE_STOP:
2079                 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2080                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2081                 break;
2082
2083         case SERVICE_STOP_SIGTERM:
2084                 log_warning("%s stopping timed out. Killing.", u->meta.id);
2085                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2086                 break;
2087
2088         case SERVICE_STOP_SIGKILL:
2089                 /* Uh, wie sent a SIGKILL and it is still not gone?
2090                  * Must be something we cannot kill, so let's just be
2091                  * weirded out and continue */
2092
2093                 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2094                 service_enter_stop_post(s, false);
2095                 break;
2096
2097         case SERVICE_STOP_POST:
2098                 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2099                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2100                 break;
2101
2102         case SERVICE_FINAL_SIGTERM:
2103                 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2104                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2105                 break;
2106
2107         case SERVICE_FINAL_SIGKILL:
2108                 log_warning("%s still around after SIGKILL (2). Entering maintainance mode.", u->meta.id);
2109                 service_enter_dead(s, false, true);
2110                 break;
2111
2112         case SERVICE_AUTO_RESTART:
2113                 log_debug("%s holdoff time over, scheduling restart.", u->meta.id);
2114                 service_enter_restart(s);
2115                 break;
2116
2117         default:
2118                 assert_not_reached("Timeout at wrong time.");
2119         }
2120 }
2121
2122 static void service_cgroup_notify_event(Unit *u) {
2123         Service *s = SERVICE(u);
2124
2125         assert(u);
2126
2127         log_debug("%s: cgroup is empty", u->meta.id);
2128
2129         switch (s->state) {
2130
2131                 /* Waiting for SIGCHLD is usually more interesting,
2132                  * because it includes return codes/signals. Which is
2133                  * why we ignore the cgroup events for most cases,
2134                  * except when we don't know pid which to expect the
2135                  * SIGCHLD for. */
2136
2137         case SERVICE_RUNNING:
2138                 service_enter_running(s, true);
2139                 break;
2140
2141         default:
2142                 ;
2143         }
2144 }
2145
2146 static int service_enumerate(Manager *m) {
2147         char **p;
2148         unsigned i;
2149         DIR *d = NULL;
2150         char *path = NULL, *fpath = NULL, *name = NULL;
2151         int r;
2152
2153         assert(m);
2154
2155         STRV_FOREACH(p, m->sysvrcnd_path)
2156                 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2157                         struct dirent *de;
2158
2159                         free(path);
2160                         path = NULL;
2161                         if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2162                                 r = -ENOMEM;
2163                                 goto finish;
2164                         }
2165
2166                         if (d)
2167                                 closedir(d);
2168
2169                         if (!(d = opendir(path))) {
2170                                 if (errno != ENOENT)
2171                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
2172
2173                                 continue;
2174                         }
2175
2176                         while ((de = readdir(d))) {
2177                                 Unit *service;
2178                                 int a, b;
2179
2180                                 if (ignore_file(de->d_name))
2181                                         continue;
2182
2183                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2184                                         continue;
2185
2186                                 if (strlen(de->d_name) < 4)
2187                                         continue;
2188
2189                                 a = undecchar(de->d_name[1]);
2190                                 b = undecchar(de->d_name[2]);
2191
2192                                 if (a < 0 || b < 0)
2193                                         continue;
2194
2195                                 free(fpath);
2196                                 fpath = NULL;
2197                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2198                                         r = -ENOMEM;
2199                                         goto finish;
2200                                 }
2201
2202                                 if (access(fpath, X_OK) < 0) {
2203
2204                                         if (errno != ENOENT)
2205                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2206
2207                                         continue;
2208                                 }
2209
2210                                 free(name);
2211                                 if (!(name = new(char, strlen(de->d_name) - 3 + 8 + 1))) {
2212                                         r = -ENOMEM;
2213                                         goto finish;
2214                                 }
2215
2216                                 if (startswith(de->d_name+3, "boot."))
2217                                         /* Drop SuSE-style boot. prefix */
2218                                         strcpy(stpcpy(name, de->d_name + 3 + 5), ".service");
2219                                 else if (endswith(de->d_name+3, ".sh"))
2220                                         /* Drop Debian-style .sh suffix */
2221                                         strcpy(stpcpy(name, de->d_name + 3) - 3, ".service");
2222                                 else
2223                                         /* Normal init scripts */
2224                                         strcpy(stpcpy(name, de->d_name + 3), ".service");
2225
2226                                 if ((r = manager_load_unit_prepare(m, name, NULL, &service)) < 0) {
2227                                         log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2228                                         continue;
2229                                 }
2230
2231                                 if (de->d_name[0] == 'S' &&
2232                                     (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_BASIC))
2233                                         SERVICE(service)->sysv_start_priority =
2234                                                 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2235
2236                                 manager_dispatch_load_queue(m);
2237                                 service = unit_follow_merge(service);
2238
2239                                 if (de->d_name[0] == 'S') {
2240                                         Unit *runlevel_target;
2241
2242                                         if ((r = manager_load_unit(m, rcnd_table[i].target, NULL, &runlevel_target)) < 0)
2243                                                 goto finish;
2244
2245                                         if ((r = unit_add_dependency(runlevel_target, UNIT_WANTS, service, true)) < 0)
2246                                                 goto finish;
2247
2248                                         if ((r = unit_add_dependency(service, UNIT_BEFORE, runlevel_target, true)) < 0)
2249                                                 goto finish;
2250
2251                                 } else if (de->d_name[0] == 'K' && rcnd_table[i].type == RUNLEVEL_DOWN) {
2252                                         Unit *shutdown_target;
2253
2254                                         /* We honour K links only for
2255                                          * halt/reboot. For the normal
2256                                          * runlevels we assume the
2257                                          * stop jobs will be
2258                                          * implicitly added by the
2259                                          * core logic. Also, we don't
2260                                          * really distuingish here
2261                                          * between the runlevels 0 and
2262                                          * 6 and just add them to the
2263                                          * special shutdown target. */
2264
2265                                         if ((r = manager_load_unit(m, SPECIAL_SHUTDOWN_TARGET, NULL, &shutdown_target)) < 0)
2266                                                 goto finish;
2267
2268                                         if ((r = unit_add_dependency(service, UNIT_CONFLICTS, shutdown_target, true)) < 0)
2269                                                 goto finish;
2270
2271                                         if ((r = unit_add_dependency(service, UNIT_BEFORE, shutdown_target, true)) < 0)
2272                                                 goto finish;
2273                                 }
2274                         }
2275                 }
2276
2277         r = 0;
2278
2279 finish:
2280         free(path);
2281         free(fpath);
2282         free(name);
2283
2284         if (d)
2285                 closedir(d);
2286
2287         return r;
2288 }
2289
2290 static void service_bus_name_owner_change(
2291                 Unit *u,
2292                 const char *name,
2293                 const char *old_owner,
2294                 const char *new_owner) {
2295
2296         Service *s = SERVICE(u);
2297
2298         assert(s);
2299         assert(name);
2300
2301         assert(streq(s->bus_name, name));
2302         assert(old_owner || new_owner);
2303
2304         if (old_owner && new_owner)
2305                 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2306         else if (old_owner)
2307                 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2308         else
2309                 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2310
2311         s->bus_name_good = !!new_owner;
2312
2313         if (s->type == SERVICE_DBUS) {
2314
2315                 /* service_enter_running() will figure out what to
2316                  * do */
2317                 if (s->state == SERVICE_RUNNING)
2318                         service_enter_running(s, true);
2319                 else if (s->state == SERVICE_START && new_owner)
2320                         service_enter_start_post(s);
2321
2322         } else if (new_owner &&
2323                    s->main_pid <= 0 &&
2324                    (s->state == SERVICE_START ||
2325                     s->state == SERVICE_START_POST ||
2326                     s->state == SERVICE_RUNNING ||
2327                     s->state == SERVICE_RELOAD)) {
2328
2329                 /* Try to acquire PID from bus service */
2330                 log_debug("Trying to acquire PID from D-Bus name...");
2331
2332                 bus_query_pid(u->meta.manager, name);
2333         }
2334 }
2335
2336 static void service_bus_query_pid_done(
2337                 Unit *u,
2338                 const char *name,
2339                 pid_t pid) {
2340
2341         Service *s = SERVICE(u);
2342
2343         assert(s);
2344         assert(name);
2345
2346         log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2347
2348         if (s->main_pid <= 0 &&
2349             (s->state == SERVICE_START ||
2350              s->state == SERVICE_START_POST ||
2351              s->state == SERVICE_RUNNING ||
2352              s->state == SERVICE_RELOAD))
2353                 s->main_pid = pid;
2354 }
2355
2356 int service_set_socket_fd(Service *s, int fd) {
2357         assert(s);
2358         assert(fd >= 0);
2359
2360         /* This is called by the socket code when instantiating a new
2361          * service for a stream socket and the socket needs to be
2362          * configured. */
2363
2364         if (UNIT(s)->meta.load_state != UNIT_LOADED)
2365                 return -EINVAL;
2366
2367         if (s->socket_fd >= 0)
2368                 return -EBUSY;
2369
2370         if (s->state != SERVICE_DEAD)
2371                 return -EAGAIN;
2372
2373         s->socket_fd = fd;
2374         s->got_socket_fd = true;
2375         return 0;
2376 }
2377
2378 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2379         [SERVICE_DEAD] = "dead",
2380         [SERVICE_START_PRE] = "start-pre",
2381         [SERVICE_START] = "start",
2382         [SERVICE_START_POST] = "start-post",
2383         [SERVICE_RUNNING] = "running",
2384         [SERVICE_EXITED] = "exited",
2385         [SERVICE_RELOAD] = "reload",
2386         [SERVICE_STOP] = "stop",
2387         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2388         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2389         [SERVICE_STOP_POST] = "stop-post",
2390         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2391         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2392         [SERVICE_MAINTAINANCE] = "maintainance",
2393         [SERVICE_AUTO_RESTART] = "auto-restart",
2394 };
2395
2396 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2397
2398 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2399         [SERVICE_ONCE] = "once",
2400         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2401         [SERVICE_RESTART_ALWAYS] = "restart-always",
2402 };
2403
2404 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2405
2406 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2407         [SERVICE_FORKING] = "forking",
2408         [SERVICE_SIMPLE] = "simple",
2409         [SERVICE_FINISH] = "finish",
2410         [SERVICE_DBUS] = "dbus"
2411 };
2412
2413 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2414
2415 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2416         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2417         [SERVICE_EXEC_START] = "ExecStart",
2418         [SERVICE_EXEC_START_POST] = "ExecStartPost",
2419         [SERVICE_EXEC_RELOAD] = "ExecReload",
2420         [SERVICE_EXEC_STOP] = "ExecStop",
2421         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2422 };
2423
2424 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2425
2426 const UnitVTable service_vtable = {
2427         .suffix = ".service",
2428
2429         .init = service_init,
2430         .done = service_done,
2431         .load = service_load,
2432
2433         .coldplug = service_coldplug,
2434
2435         .dump = service_dump,
2436
2437         .start = service_start,
2438         .stop = service_stop,
2439         .reload = service_reload,
2440
2441         .can_reload = service_can_reload,
2442
2443         .serialize = service_serialize,
2444         .deserialize_item = service_deserialize_item,
2445
2446         .active_state = service_active_state,
2447         .sub_state_to_string = service_sub_state_to_string,
2448
2449         .check_gc = service_check_gc,
2450         .check_snapshot = service_check_snapshot,
2451
2452         .sigchld_event = service_sigchld_event,
2453         .timer_event = service_timer_event,
2454
2455         .cgroup_notify_empty = service_cgroup_notify_event,
2456
2457         .bus_name_owner_change = service_bus_name_owner_change,
2458         .bus_query_pid_done = service_bus_query_pid_done,
2459
2460         .bus_message_handler = bus_service_message_handler,
2461
2462         .enumerate = service_enumerate
2463 };