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