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