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