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