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