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