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