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