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