chiark / gitweb /
sysv: require sysinit.service from all sysv services
[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         if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_SYSINIT_SERVICE)) < 0 ||
485             (r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_SYSINIT_SERVICE)) < 0)
486                 goto finish;
487
488         r = 1;
489
490 finish:
491
492         if (f)
493                 fclose(f);
494
495         return r;
496 }
497
498 static int service_load_sysv_name(Service *s, const char *name) {
499         char **p;
500
501         assert(s);
502         assert(name);
503
504         STRV_FOREACH(p, UNIT(s)->meta.manager->sysvinit_path) {
505                 char *path;
506                 int r;
507
508                 if (asprintf(&path, "%s/%s", *p, name) < 0)
509                         return -ENOMEM;
510
511                 assert(endswith(path, ".service"));
512                 path[strlen(path)-8] = 0;
513
514                 r = service_load_sysv_path(s, path);
515                 free(path);
516
517                 if (r != 0)
518                         return r;
519         }
520
521         return 0;
522 }
523
524 static int service_load_sysv(Service *s) {
525         const char *t;
526         Iterator i;
527         int r;
528
529         assert(s);
530
531         /* Load service data from SysV init scripts, preferably with
532          * LSB headers ... */
533
534         if (strv_isempty(UNIT(s)->meta.manager->sysvinit_path))
535                 return 0;
536
537         if ((t = unit_id(UNIT(s))))
538                 if ((r = service_load_sysv_name(s, t)) != 0)
539                         return r;
540
541         SET_FOREACH(t, UNIT(s)->meta.names, i)
542                 if ((r == service_load_sysv_name(s, t)) != 0)
543                         return r;
544
545         return 0;
546 }
547
548 static int service_init(Unit *u) {
549         int r;
550         Service *s = SERVICE(u);
551
552         assert(s);
553
554         /* First, reset everything to the defaults, in case this is a
555          * reload */
556
557         s->type = 0;
558         s->restart = 0;
559
560         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
561         s->restart_usec = DEFAULT_RESTART_USEC;
562
563         exec_context_init(&s->exec_context);
564
565         s->timer_watch.type = WATCH_INVALID;
566
567         s->state = SERVICE_DEAD;
568
569         s->sysv_start_priority = -1;
570         s->permissions_start_only = false;
571         s->root_directory_start_only = false;
572
573         RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
574
575         /* Load a .service file */
576         if ((r = unit_load_fragment(u)) < 0) {
577                 service_done(u);
578                 return r;
579         }
580
581         /* Load a classic init script as a fallback, if we couldn't find anything */
582         if (r == 0)
583                 if ((r = service_load_sysv(s)) <= 0) {
584                         service_done(u);
585                         return r < 0 ? r : -ENOENT;
586                 }
587
588         /* Load dropin directory data */
589         if ((r = unit_load_dropin(u)) < 0) {
590                 service_done(u);
591                 return r;
592         }
593
594         /* Add default cgroup */
595         if ((r = unit_add_default_cgroup(u)) < 0) {
596                 service_done(u);
597                 return r;
598         }
599
600         return 0;
601 }
602
603 static void service_dump(Unit *u, FILE *f, const char *prefix) {
604
605         ServiceExecCommand c;
606         Service *s = SERVICE(u);
607         const char *prefix2;
608         char *p2;
609
610         assert(s);
611
612         p2 = strappend(prefix, "\t");
613         prefix2 = p2 ? p2 : prefix;
614
615         fprintf(f,
616                 "%sService State: %s\n"
617                 "%sPermissionsStartOnly: %s\n"
618                 "%sRootDirectoryStartOnly: %s\n"
619                 "%sValidNoProcess: %s\n"
620                 "%sType: %s\n",
621                 prefix, service_state_to_string(s->state),
622                 prefix, yes_no(s->permissions_start_only),
623                 prefix, yes_no(s->root_directory_start_only),
624                 prefix, yes_no(s->valid_no_process),
625                 prefix, service_type_to_string(s->type));
626
627         if (s->pid_file)
628                 fprintf(f,
629                         "%sPIDFile: %s\n",
630                         prefix, s->pid_file);
631
632
633         exec_context_dump(&s->exec_context, f, prefix);
634
635         for (c = 0; c < _SERVICE_EXEC_MAX; c++) {
636
637                 if (!s->exec_command[c])
638                         continue;
639
640                 fprintf(f, "%sā†’ %s:\n",
641                         prefix, service_exec_command_to_string(c));
642
643                 exec_command_dump_list(s->exec_command[c], f, prefix2);
644         }
645
646         if (s->sysv_path)
647                 fprintf(f,
648                         "%sSysV Init Script Path: %s\n",
649                         prefix, s->sysv_path);
650
651         if (s->sysv_start_priority >= 0)
652                 fprintf(f,
653                         "%sSysV Start Priority: %i\n",
654                         prefix, s->sysv_start_priority);
655
656         free(p2);
657 }
658
659 static int service_load_pid_file(Service *s) {
660         char *k;
661         unsigned long p;
662         int r;
663
664         assert(s);
665
666         if (s->main_pid_known)
667                 return 0;
668
669         if (!s->pid_file)
670                 return -ENOENT;
671
672         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
673                 return r;
674
675         if ((r = safe_atolu(k, &p)) < 0) {
676                 free(k);
677                 return r;
678         }
679
680         if ((unsigned long) (pid_t) p != p)
681                 return -ERANGE;
682
683         s->main_pid = p;
684         s->main_pid_known = true;
685
686         return 0;
687 }
688
689 static int service_get_sockets(Service *s, Set **_set) {
690         Set *set;
691         Iterator i;
692         char *t;
693         int r;
694
695         assert(s);
696         assert(_set);
697
698         /* Collects all Socket objects that belong to this
699          * service. Note that a service might have multiple sockets
700          * via multiple names. */
701
702         if (!(set = set_new(NULL, NULL)))
703                 return -ENOMEM;
704
705         SET_FOREACH(t, UNIT(s)->meta.names, i) {
706                 char *k;
707                 Unit *p;
708
709                 /* Look for all socket objects that go by any of our
710                  * units and collect their fds */
711
712                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
713                         r = -ENOMEM;
714                         goto fail;
715                 }
716
717                 p = manager_get_unit(UNIT(s)->meta.manager, k);
718                 free(k);
719
720                 if (!p) continue;
721
722                 if ((r = set_put(set, p)) < 0)
723                         goto fail;
724         }
725
726         *_set = set;
727         return 0;
728
729 fail:
730         set_free(set);
731         return r;
732 }
733
734
735 static int service_notify_sockets(Service *s) {
736         Iterator i;
737         Set *set;
738         Socket *sock;
739         int r;
740
741         assert(s);
742
743         /* Notifies all our sockets when we die */
744
745         if ((r = service_get_sockets(s, &set)) < 0)
746                 return r;
747
748         SET_FOREACH(sock, set, i)
749                 socket_notify_service_dead(sock);
750
751         set_free(set);
752
753         return 0;
754 }
755
756 static void service_set_state(Service *s, ServiceState state) {
757         ServiceState old_state;
758         assert(s);
759
760         old_state = s->state;
761         s->state = state;
762
763         if (state != SERVICE_START_PRE &&
764             state != SERVICE_START &&
765             state != SERVICE_START_POST &&
766             state != SERVICE_RELOAD &&
767             state != SERVICE_STOP &&
768             state != SERVICE_STOP_SIGTERM &&
769             state != SERVICE_STOP_SIGKILL &&
770             state != SERVICE_STOP_POST &&
771             state != SERVICE_FINAL_SIGTERM &&
772             state != SERVICE_FINAL_SIGKILL &&
773             state != SERVICE_AUTO_RESTART)
774                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
775
776         if (state != SERVICE_START &&
777             state != SERVICE_START_POST &&
778             state != SERVICE_RUNNING &&
779             state != SERVICE_RELOAD &&
780             state != SERVICE_STOP &&
781             state != SERVICE_STOP_SIGTERM &&
782             state != SERVICE_STOP_SIGKILL)
783                 if (s->main_pid > 0) {
784                         unit_unwatch_pid(UNIT(s), s->main_pid);
785                         s->main_pid = 0;
786                 }
787
788         if (state != SERVICE_START_PRE &&
789             state != SERVICE_START &&
790             state != SERVICE_START_POST &&
791             state != SERVICE_RELOAD &&
792             state != SERVICE_STOP &&
793             state != SERVICE_STOP_SIGTERM &&
794             state != SERVICE_STOP_SIGKILL &&
795             state != SERVICE_STOP_POST &&
796             state != SERVICE_FINAL_SIGTERM &&
797             state != SERVICE_FINAL_SIGKILL)
798                 if (s->control_pid > 0) {
799                         unit_unwatch_pid(UNIT(s), s->control_pid);
800                         s->control_pid = 0;
801                 }
802
803         if (state != SERVICE_START_PRE &&
804             state != SERVICE_START &&
805             state != SERVICE_START_POST &&
806             state != SERVICE_RELOAD &&
807             state != SERVICE_STOP &&
808             state != SERVICE_STOP_POST)
809                 s->control_command = NULL;
810
811         if (state == SERVICE_DEAD ||
812             state == SERVICE_STOP ||
813             state == SERVICE_STOP_SIGTERM ||
814             state == SERVICE_STOP_SIGKILL ||
815             state == SERVICE_STOP_POST ||
816             state == SERVICE_FINAL_SIGTERM ||
817             state == SERVICE_FINAL_SIGKILL ||
818             state == SERVICE_MAINTAINANCE ||
819             state == SERVICE_AUTO_RESTART)
820                 service_notify_sockets(s);
821
822         log_debug("%s changed %s ā†’ %s", unit_id(UNIT(s)), service_state_to_string(old_state), service_state_to_string(state));
823
824         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
825 }
826
827 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
828         Iterator i;
829         int r;
830         int *rfds = NULL;
831         unsigned rn_fds = 0;
832         Set *set;
833         Socket *sock;
834
835         assert(s);
836         assert(fds);
837         assert(n_fds);
838
839         if ((r = service_get_sockets(s, &set)) < 0)
840                 return r;
841
842         SET_FOREACH(sock, set, i) {
843                 int *cfds;
844                 unsigned cn_fds;
845
846                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
847                         goto fail;
848
849                 if (!cfds)
850                         continue;
851
852                 if (!rfds) {
853                         rfds = cfds;
854                         rn_fds = cn_fds;
855                 } else {
856                         int *t;
857
858                         if (!(t = new(int, rn_fds+cn_fds))) {
859                                 free(cfds);
860                                 r = -ENOMEM;
861                                 goto fail;
862                         }
863
864                         memcpy(t, rfds, rn_fds);
865                         memcpy(t+rn_fds, cfds, cn_fds);
866                         free(rfds);
867                         free(cfds);
868
869                         rfds = t;
870                         rn_fds = rn_fds+cn_fds;
871                 }
872         }
873
874         *fds = rfds;
875         *n_fds = rn_fds;
876
877         set_free(set);
878
879         return 0;
880
881 fail:
882         set_free(set);
883         free(rfds);
884
885         return r;
886 }
887
888 static int service_spawn(
889                 Service *s,
890                 ExecCommand *c,
891                 bool timeout,
892                 bool pass_fds,
893                 bool apply_permissions,
894                 bool apply_chroot,
895                 pid_t *_pid) {
896
897         pid_t pid;
898         int r;
899         int *fds = NULL;
900         unsigned n_fds = 0;
901
902         assert(s);
903         assert(c);
904         assert(_pid);
905
906         if (pass_fds)
907                 if ((r = service_collect_fds(s, &fds, &n_fds)) < 0)
908                         goto fail;
909
910         if (timeout) {
911                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
912                         goto fail;
913         } else
914                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
915
916         if ((r = exec_spawn(c,
917                             &s->exec_context,
918                             fds, n_fds,
919                             apply_permissions,
920                             apply_chroot,
921                             UNIT(s)->meta.cgroup_bondings,
922                             &pid)) < 0)
923                 goto fail;
924
925         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
926                 /* FIXME: we need to do something here */
927                 goto fail;
928
929         free(fds);
930         *_pid = pid;
931
932         return 0;
933
934 fail:
935         free(fds);
936
937         if (timeout)
938                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
939
940         return r;
941 }
942
943 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
944         int r;
945         assert(s);
946
947         if (!success)
948                 s->failure = true;
949
950         if (allow_restart &&
951             (s->restart == SERVICE_RESTART_ALWAYS ||
952              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
953
954                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
955                         goto fail;
956
957                 service_set_state(s, SERVICE_AUTO_RESTART);
958         } else
959                 service_set_state(s, s->failure ? SERVICE_MAINTAINANCE : SERVICE_DEAD);
960
961         return;
962
963 fail:
964         log_warning("%s failed to run install restart timer: %s", unit_id(UNIT(s)), strerror(-r));
965         service_enter_dead(s, false, false);
966 }
967
968 static void service_enter_signal(Service *s, ServiceState state, bool success);
969
970 static void service_enter_stop_post(Service *s, bool success) {
971         int r;
972         assert(s);
973
974         if (!success)
975                 s->failure = true;
976
977         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST]))
978                 if ((r = service_spawn(s,
979                                        s->control_command,
980                                        true,
981                                        false,
982                                        !s->permissions_start_only,
983                                        !s->root_directory_start_only,
984                                        &s->control_pid)) < 0)
985                         goto fail;
986
987
988         service_set_state(s, SERVICE_STOP_POST);
989
990         if (!s->control_command)
991                 service_enter_dead(s, true, true);
992
993         return;
994
995 fail:
996         log_warning("%s failed to run stop executable: %s", unit_id(UNIT(s)), strerror(-r));
997         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
998 }
999
1000 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1001         int r;
1002         bool sent = false;
1003
1004         assert(s);
1005
1006         if (!success)
1007                 s->failure = true;
1008
1009         if (s->main_pid > 0 || s->control_pid > 0) {
1010                 int sig;
1011
1012                 sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1013
1014                 r = 0;
1015                 if (s->main_pid > 0) {
1016                         if (kill(s->main_pid, sig) < 0 && errno != ESRCH)
1017                                 r = -errno;
1018                         else
1019                                 sent = true;
1020                 }
1021
1022                 if (s->control_pid > 0) {
1023                         if (kill(s->control_pid, sig) < 0 && errno != ESRCH)
1024                                 r = -errno;
1025                         else
1026                                 sent = true;
1027                 }
1028
1029                 if (r < 0)
1030                         goto fail;
1031         }
1032
1033         service_set_state(s, state);
1034
1035         if (s->main_pid <= 0 && s->control_pid <= 0)
1036                 service_enter_dead(s, true, true);
1037
1038         return;
1039
1040 fail:
1041         log_warning("%s failed to kill processes: %s", unit_id(UNIT(s)), strerror(-r));
1042
1043         if (sent)  {
1044                 s->failure = true;
1045                 service_set_state(s, state);
1046         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1047                 service_enter_stop_post(s, false);
1048         else
1049                 service_enter_dead(s, false, true);
1050 }
1051
1052 static void service_enter_stop(Service *s, bool success) {
1053         int r;
1054         assert(s);
1055
1056         if (!success)
1057                 s->failure = true;
1058
1059         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP]))
1060                 if ((r = service_spawn(s,
1061                                        s->control_command,
1062                                        true,
1063                                        false,
1064                                        !s->permissions_start_only,
1065                                        !s->root_directory_start_only,
1066                                        &s->control_pid)) < 0)
1067                         goto fail;
1068
1069         service_set_state(s, SERVICE_STOP);
1070
1071         if (!s->control_command)
1072                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1073
1074         return;
1075
1076 fail:
1077         log_warning("%s failed to run stop executable: %s", unit_id(UNIT(s)), strerror(-r));
1078         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1079 }
1080
1081 static void service_enter_start_post(Service *s) {
1082         int r;
1083         assert(s);
1084
1085         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST]))
1086                 if ((r = service_spawn(s,
1087                                        s->control_command,
1088                                        true,
1089                                        false,
1090                                        !s->permissions_start_only,
1091                                        !s->root_directory_start_only,
1092                                        &s->control_pid)) < 0)
1093                         goto fail;
1094
1095
1096         service_set_state(s, SERVICE_START_POST);
1097
1098         if (!s->control_command)
1099                 service_set_state(s, SERVICE_RUNNING);
1100
1101         return;
1102
1103 fail:
1104         log_warning("%s failed to run start-post executable: %s", unit_id(UNIT(s)), strerror(-r));
1105         service_enter_stop(s, false);
1106 }
1107
1108 static void service_enter_start(Service *s) {
1109         pid_t pid;
1110         int r;
1111
1112         assert(s);
1113
1114         assert(s->exec_command[SERVICE_EXEC_START]);
1115         assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1116
1117         if ((r = service_spawn(s,
1118                                s->exec_command[SERVICE_EXEC_START],
1119                                s->type == SERVICE_FORKING,
1120                                true,
1121                                true,
1122                                true,
1123                                &pid)) < 0)
1124                 goto fail;
1125
1126         service_set_state(s, SERVICE_START);
1127
1128         if (s->type == SERVICE_SIMPLE) {
1129                 /* For simple services we immediately start
1130                  * the START_POST binaries. */
1131
1132                 s->main_pid = pid;
1133                 s->main_pid_known = true;
1134                 service_enter_start_post(s);
1135
1136         } else  if (s->type == SERVICE_FORKING) {
1137
1138                 /* For forking services we wait until the start
1139                  * process exited. */
1140
1141                 s->control_pid = pid;
1142                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1143         } else if (s->type == SERVICE_FINISH) {
1144
1145                 /* For finishing services we wait until the start
1146                  * process exited, too, but it is our main process. */
1147
1148                 s->main_pid = pid;
1149                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1150         } else
1151                 assert_not_reached("Unknown service type");
1152
1153         return;
1154
1155 fail:
1156         log_warning("%s failed to run start exectuable: %s", unit_id(UNIT(s)), strerror(-r));
1157         service_enter_stop(s, false);
1158 }
1159
1160 static void service_enter_start_pre(Service *s) {
1161         int r;
1162
1163         assert(s);
1164
1165         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE]))
1166                 if ((r = service_spawn(s,
1167                                        s->control_command,
1168                                        true,
1169                                        false,
1170                                        !s->permissions_start_only,
1171                                        !s->root_directory_start_only,
1172                                        &s->control_pid)) < 0)
1173                         goto fail;
1174
1175         service_set_state(s, SERVICE_START_PRE);
1176
1177         if (!s->control_command)
1178                 service_enter_start(s);
1179
1180         return;
1181
1182 fail:
1183         log_warning("%s failed to run start-pre executable: %s", unit_id(UNIT(s)), strerror(-r));
1184         service_enter_dead(s, false, true);
1185 }
1186
1187 static void service_enter_restart(Service *s) {
1188         int r;
1189         assert(s);
1190
1191         if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL)) < 0)
1192                 goto fail;
1193
1194         log_debug("%s scheduled restart job.", unit_id(UNIT(s)));
1195         service_enter_dead(s, true, false);
1196         return;
1197
1198 fail:
1199
1200         log_warning("%s failed to schedule restart job: %s", unit_id(UNIT(s)), strerror(-r));
1201         service_enter_dead(s, false, false);
1202 }
1203
1204 static void service_enter_reload(Service *s) {
1205         int r;
1206
1207         assert(s);
1208
1209         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD]))
1210                 if ((r = service_spawn(s,
1211                                        s->control_command,
1212                                        true,
1213                                        false,
1214                                        !s->permissions_start_only,
1215                                        !s->root_directory_start_only,
1216                                        &s->control_pid)) < 0)
1217                         goto fail;
1218
1219         service_set_state(s, SERVICE_RELOAD);
1220
1221         if (!s->control_command)
1222                 service_set_state(s, SERVICE_RUNNING);
1223
1224         return;
1225
1226 fail:
1227         log_warning("%s failed to run reload executable: %s", unit_id(UNIT(s)), strerror(-r));
1228         service_enter_stop(s, false);
1229 }
1230
1231 static void service_run_next(Service *s, bool success) {
1232         int r;
1233
1234         assert(s);
1235         assert(s->control_command);
1236         assert(s->control_command->command_next);
1237
1238         if (!success)
1239                 s->failure = true;
1240
1241         s->control_command = s->control_command->command_next;
1242
1243         if ((r = service_spawn(s,
1244                                s->control_command,
1245                                true,
1246                                false,
1247                                !s->permissions_start_only,
1248                                !s->root_directory_start_only,
1249                                &s->control_pid)) < 0)
1250                 goto fail;
1251
1252         return;
1253
1254 fail:
1255         log_warning("%s failed to run spawn next executable: %s", unit_id(UNIT(s)), strerror(-r));
1256
1257         if (s->state == SERVICE_STOP)
1258                 service_enter_stop_post(s, false);
1259         else if (s->state == SERVICE_STOP_POST)
1260                 service_enter_dead(s, false, true);
1261         else
1262                 service_enter_stop(s, false);
1263 }
1264
1265 static int service_start(Unit *u) {
1266         Service *s = SERVICE(u);
1267
1268         assert(s);
1269
1270         /* We cannot fulfill this request right now, try again later
1271          * please! */
1272         if (s->state == SERVICE_STOP ||
1273             s->state == SERVICE_STOP_SIGTERM ||
1274             s->state == SERVICE_STOP_SIGKILL ||
1275             s->state == SERVICE_STOP_POST ||
1276             s->state == SERVICE_FINAL_SIGTERM ||
1277             s->state == SERVICE_FINAL_SIGKILL)
1278                 return -EAGAIN;
1279
1280         /* Already on it! */
1281         if (s->state == SERVICE_START_PRE ||
1282             s->state == SERVICE_START ||
1283             s->state == SERVICE_START_POST)
1284                 return 0;
1285
1286         assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTAINANCE || s->state == SERVICE_AUTO_RESTART);
1287
1288         /* Make sure we don't enter a busy loop of some kind. */
1289         if (!ratelimit_test(&s->ratelimit)) {
1290                 log_warning("%s start request repeated too quickly, refusing to start.", unit_id(u));
1291                 return -EAGAIN;
1292         }
1293
1294         s->failure = false;
1295         s->main_pid_known = false;
1296
1297         service_enter_start_pre(s);
1298         return 0;
1299 }
1300
1301 static int service_stop(Unit *u) {
1302         Service *s = SERVICE(u);
1303
1304         assert(s);
1305
1306         if (s->state == SERVICE_START_PRE ||
1307             s->state == SERVICE_START ||
1308             s->state == SERVICE_START_POST ||
1309             s->state == SERVICE_RELOAD)
1310                 return -EAGAIN;
1311
1312         if (s->state == SERVICE_AUTO_RESTART) {
1313                 service_set_state(s, SERVICE_DEAD);
1314                 return 0;
1315         }
1316
1317         assert(s->state == SERVICE_RUNNING);
1318
1319         service_enter_stop(s, true);
1320         return 0;
1321 }
1322
1323 static int service_reload(Unit *u) {
1324         Service *s = SERVICE(u);
1325
1326         assert(s);
1327
1328         assert(s->state == SERVICE_RUNNING);
1329
1330         service_enter_reload(s);
1331         return 0;
1332 }
1333
1334 static bool service_can_reload(Unit *u) {
1335         Service *s = SERVICE(u);
1336
1337         assert(s);
1338
1339         return !!s->exec_command[SERVICE_EXEC_RELOAD];
1340 }
1341
1342 static UnitActiveState service_active_state(Unit *u) {
1343         assert(u);
1344
1345         return state_translation_table[SERVICE(u)->state];
1346 }
1347
1348 static int main_pid_good(Service *s) {
1349         assert(s);
1350
1351         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1352          * don't know */
1353
1354         /* If we know the pid file, then lets just check if it is
1355          * still valid */
1356         if (s->main_pid_known)
1357                 return s->main_pid > 0;
1358
1359         /* We don't know the pid */
1360         return -EAGAIN;
1361 }
1362
1363 static bool control_pid_good(Service *s) {
1364         assert(s);
1365
1366         return s->control_pid > 0;
1367 }
1368
1369 static int cgroup_good(Service *s) {
1370         assert(s);
1371
1372         if (s->valid_no_process)
1373                 return -EAGAIN;
1374
1375         return cgroup_bonding_is_empty_list(UNIT(s)->meta.cgroup_bondings);
1376 }
1377
1378 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1379         Service *s = SERVICE(u);
1380         bool success;
1381
1382         assert(s);
1383         assert(pid >= 0);
1384
1385         success = code == CLD_EXITED && status == 0;
1386         s->failure = s->failure || !success;
1387
1388         if (s->main_pid == pid) {
1389
1390                 exec_status_fill(&s->main_exec_status, pid, code, status);
1391                 s->main_pid = 0;
1392
1393                 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_FINISH) {
1394                         assert(s->exec_command[SERVICE_EXEC_START]);
1395                         s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
1396                 }
1397
1398                 log_debug("%s: main process exited, code=%s status=%i", unit_id(u), sigchld_code_to_string(code), status);
1399
1400                 /* The service exited, so the service is officially
1401                  * gone. */
1402
1403                 switch (s->state) {
1404
1405                 case SERVICE_START_POST:
1406                 case SERVICE_RELOAD:
1407                 case SERVICE_STOP:
1408                         /* Need to wait until the operation is
1409                          * done */
1410                         break;
1411
1412                 case SERVICE_START:
1413                         assert(s->type == SERVICE_FINISH);
1414
1415                         /* This was our main goal, so let's go on */
1416                         if (success)
1417                                 service_enter_start_post(s);
1418                         else
1419                                 service_enter_stop(s, false);
1420                         break;
1421
1422                 case SERVICE_RUNNING:
1423                         service_enter_stop(s, success);
1424                         break;
1425
1426                 case SERVICE_STOP_SIGTERM:
1427                 case SERVICE_STOP_SIGKILL:
1428
1429                         if (!control_pid_good(s))
1430                                 service_enter_stop_post(s, success);
1431
1432                         /* If there is still a control process, wait for that first */
1433                         break;
1434
1435                 default:
1436                         assert_not_reached("Uh, main process died at wrong time.");
1437                 }
1438
1439         } else if (s->control_pid == pid) {
1440                 assert(s->control_command);
1441
1442                 exec_status_fill(&s->control_command->exec_status, pid, code, status);
1443                 s->control_pid = 0;
1444
1445                 log_debug("%s: control process exited, code=%s status=%i", unit_id(u), sigchld_code_to_string(code), status);
1446
1447                 /* If we are shutting things down anyway we
1448                  * don't care about failing commands. */
1449
1450                 if (s->control_command->command_next &&
1451                     (success || (s->state == SERVICE_STOP || s->state == SERVICE_STOP_POST)))
1452
1453                         /* There is another command to *
1454                          * execute, so let's do that. */
1455
1456                         service_run_next(s, success);
1457
1458                 else {
1459                         /* No further commands for this step, so let's
1460                          * figure out what to do next */
1461
1462                         log_debug("%s got final SIGCHLD for state %s", unit_id(u), service_state_to_string(s->state));
1463
1464                         switch (s->state) {
1465
1466                         case SERVICE_START_PRE:
1467                                 if (success)
1468                                         service_enter_start(s);
1469                                 else
1470                                         service_enter_stop(s, false);
1471                                 break;
1472
1473                         case SERVICE_START:
1474                                 assert(s->type == SERVICE_FORKING);
1475
1476                                 /* Let's try to load the pid
1477                                  * file here if we can. We
1478                                  * ignore the return value,
1479                                  * since the PID file might
1480                                  * actually be created by a
1481                                  * START_POST script */
1482
1483                                 if (success) {
1484                                         if (s->pid_file)
1485                                                 service_load_pid_file(s);
1486
1487                                         service_enter_start_post(s);
1488                                 } else
1489                                         service_enter_stop(s, false);
1490
1491                                 break;
1492
1493                         case SERVICE_START_POST:
1494                                 if (success && s->pid_file && !s->main_pid_known) {
1495                                         int r;
1496
1497                                         /* Hmm, let's see if we can
1498                                          * load the pid now after the
1499                                          * start-post scripts got
1500                                          * executed. */
1501
1502                                         if ((r = service_load_pid_file(s)) < 0)
1503                                                 log_warning("%s: failed to load PID file %s: %s", unit_id(UNIT(s)), s->pid_file, strerror(-r));
1504                                 }
1505
1506                                 /* Fall through */
1507
1508                         case SERVICE_RELOAD:
1509                                 if (success) {
1510                                         if (main_pid_good(s) != 0 && cgroup_good(s) != 0)
1511                                                 service_set_state(s, SERVICE_RUNNING);
1512                                         else
1513                                                 service_enter_stop(s, true);
1514                                 } else
1515                                         service_enter_stop(s, false);
1516
1517                                 break;
1518
1519                         case SERVICE_STOP:
1520                                 if (main_pid_good(s) > 0)
1521                                         /* Still not dead and we know the PID? Let's go hunting. */
1522                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
1523                                 else
1524                                         service_enter_stop_post(s, success);
1525                                 break;
1526
1527                         case SERVICE_STOP_SIGTERM:
1528                         case SERVICE_STOP_SIGKILL:
1529                                 if (main_pid_good(s) <= 0)
1530                                         service_enter_stop_post(s, success);
1531
1532                                 /* If there is still a service
1533                                  * process around, wait until
1534                                  * that one quit, too */
1535                                 break;
1536
1537                         case SERVICE_STOP_POST:
1538                         case SERVICE_FINAL_SIGTERM:
1539                         case SERVICE_FINAL_SIGKILL:
1540                                 service_enter_dead(s, success, true);
1541                                 break;
1542
1543                         default:
1544                                 assert_not_reached("Uh, control process died at wrong time.");
1545                         }
1546                 }
1547         } else
1548                 assert_not_reached("Got SIGCHLD for unkown PID");
1549 }
1550
1551 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
1552         Service *s = SERVICE(u);
1553
1554         assert(s);
1555         assert(elapsed == 1);
1556
1557         assert(w == &s->timer_watch);
1558
1559         switch (s->state) {
1560
1561         case SERVICE_START_PRE:
1562         case SERVICE_START:
1563         case SERVICE_START_POST:
1564         case SERVICE_RELOAD:
1565                 log_warning("%s operation timed out. Stopping.", unit_id(u));
1566                 service_enter_stop(s, false);
1567                 break;
1568
1569         case SERVICE_STOP:
1570                 log_warning("%s stopping timed out. Terminating.", unit_id(u));
1571                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1572                 break;
1573
1574         case SERVICE_STOP_SIGTERM:
1575                 log_warning("%s stopping timed out. Killing.", unit_id(u));
1576                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
1577                 break;
1578
1579         case SERVICE_STOP_SIGKILL:
1580                 /* Uh, wie sent a SIGKILL and it is still not gone?
1581                  * Must be something we cannot kill, so let's just be
1582                  * weirded out and continue */
1583
1584                 log_warning("%s still around after SIGKILL. Ignoring.", unit_id(u));
1585                 service_enter_stop_post(s, false);
1586                 break;
1587
1588         case SERVICE_STOP_POST:
1589                 log_warning("%s stopping timed out (2). Terminating.", unit_id(u));
1590                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1591                 break;
1592
1593         case SERVICE_FINAL_SIGTERM:
1594                 log_warning("%s stopping timed out (2). Killing.", unit_id(u));
1595                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
1596                 break;
1597
1598         case SERVICE_FINAL_SIGKILL:
1599                 log_warning("%s still around after SIGKILL (2). Entering maintainance mode.", unit_id(u));
1600                 service_enter_dead(s, false, true);
1601                 break;
1602
1603         case SERVICE_AUTO_RESTART:
1604                 log_debug("%s holdoff time over, scheduling restart.", unit_id(u));
1605                 service_enter_restart(s);
1606                 break;
1607
1608         default:
1609                 assert_not_reached("Timeout at wrong time.");
1610         }
1611 }
1612
1613 static void service_cgroup_notify_event(Unit *u) {
1614         Service *s = SERVICE(u);
1615
1616         assert(u);
1617
1618         log_debug("%s: cgroup is empty", unit_id(u));
1619
1620         switch (s->state) {
1621
1622                 /* Waiting for SIGCHLD is usually more interesting,
1623                  * because it includes return codes/signals. Which is
1624                  * why we ignore the cgroup events for most cases,
1625                  * except when we don't know pid which to expect the
1626                  * SIGCHLD for. */
1627
1628         case SERVICE_RUNNING:
1629
1630                 if (!s->valid_no_process && main_pid_good(s) <= 0)
1631                         service_enter_stop(s, true);
1632
1633                 break;
1634
1635         default:
1636                 ;
1637         }
1638 }
1639
1640 static int service_enumerate(Manager *m) {
1641
1642         static const char * const rcnd[] = {
1643                 "../rc0.d", SPECIAL_RUNLEVEL0_TARGET,
1644                 "../rc1.d", SPECIAL_RUNLEVEL1_TARGET,
1645                 "../rc2.d", SPECIAL_RUNLEVEL2_TARGET,
1646                 "../rc3.d", SPECIAL_RUNLEVEL3_TARGET,
1647                 "../rc4.d", SPECIAL_RUNLEVEL4_TARGET,
1648                 "../rc5.d", SPECIAL_RUNLEVEL5_TARGET,
1649                 "../rc6.d", SPECIAL_RUNLEVEL6_TARGET
1650         };
1651
1652         char **p;
1653         unsigned i;
1654         DIR *d = NULL;
1655         char *path = NULL, *fpath = NULL, *name = NULL;
1656         int r;
1657
1658         assert(m);
1659
1660         STRV_FOREACH(p, m->sysvinit_path)
1661                 for (i = 0; i < ELEMENTSOF(rcnd); i += 2) {
1662                         struct dirent *de;
1663
1664                         free(path);
1665                         path = NULL;
1666                         if (asprintf(&path, "%s/%s", *p, rcnd[i]) < 0) {
1667                                 r = -ENOMEM;
1668                                 goto finish;
1669                         }
1670
1671                         if (d)
1672                                 closedir(d);
1673
1674                         if (!(d = opendir(path))) {
1675                                 if (errno != ENOENT)
1676                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
1677
1678                                 continue;
1679                         }
1680
1681                         while ((de = readdir(d))) {
1682                                 Unit *runlevel, *service;
1683
1684                                 if (ignore_file(de->d_name))
1685                                         continue;
1686
1687                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
1688                                         continue;
1689
1690                                 if (strlen(de->d_name) < 4)
1691                                         continue;
1692
1693                                 free(fpath);
1694                                 fpath = NULL;
1695                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd[i], de->d_name) < 0) {
1696                                         r = -ENOMEM;
1697                                         goto finish;
1698                                 }
1699
1700                                 if (access(fpath, X_OK) < 0) {
1701
1702                                         if (errno != ENOENT)
1703                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
1704
1705                                         continue;
1706                                 }
1707
1708                                 free(name);
1709                                 name = NULL;
1710                                 if (asprintf(&name, "%s.service", de->d_name+3) < 0) {
1711                                         r = -ENOMEM;
1712                                         goto finish;
1713                                 }
1714
1715                                 if ((r = manager_load_unit(m, name, &service)) < 0)
1716                                         goto finish;
1717
1718                                 if ((r = manager_load_unit(m, rcnd[i+1], &runlevel)) < 0)
1719                                         goto finish;
1720
1721                                 if (de->d_name[0] == 'S') {
1722                                         if ((r = unit_add_dependency(runlevel, UNIT_WANTS, service)) < 0)
1723                                                 goto finish;
1724
1725                                         if ((r = unit_add_dependency(runlevel, UNIT_AFTER, service)) < 0)
1726                                                 goto finish;
1727                                 } else {
1728                                         if ((r = unit_add_dependency(runlevel, UNIT_CONFLICTS, service)) < 0)
1729                                                 goto finish;
1730
1731                                         if ((r = unit_add_dependency(runlevel, UNIT_BEFORE, service)) < 0)
1732                                                 goto finish;
1733                                 }
1734                         }
1735                 }
1736
1737         r = 0;
1738
1739 finish:
1740         free(path);
1741         free(fpath);
1742         free(name);
1743         closedir(d);
1744
1745         return r;
1746 }
1747
1748 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
1749         [SERVICE_DEAD] = "dead",
1750         [SERVICE_START_PRE] = "start-pre",
1751         [SERVICE_START] = "start",
1752         [SERVICE_START_POST] = "start-post",
1753         [SERVICE_RUNNING] = "running",
1754         [SERVICE_RELOAD] = "reload",
1755         [SERVICE_STOP] = "stop",
1756         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
1757         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
1758         [SERVICE_STOP_POST] = "stop-post",
1759         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
1760         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
1761         [SERVICE_MAINTAINANCE] = "maintainance",
1762         [SERVICE_AUTO_RESTART] = "auto-restart",
1763 };
1764
1765 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
1766
1767 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
1768         [SERVICE_ONCE] = "once",
1769         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
1770         [SERVICE_RESTART_ALWAYS] = "restart-on-failure",
1771 };
1772
1773 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
1774
1775 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
1776         [SERVICE_FORKING] = "forking",
1777         [SERVICE_SIMPLE] = "simple",
1778         [SERVICE_FINISH] = "finish"
1779 };
1780
1781 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
1782
1783 static const char* const service_exec_command_table[_SERVICE_EXEC_MAX] = {
1784         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
1785         [SERVICE_EXEC_START] = "ExecStart",
1786         [SERVICE_EXEC_START_POST] = "ExecStartPost",
1787         [SERVICE_EXEC_RELOAD] = "ExecReload",
1788         [SERVICE_EXEC_STOP] = "ExecStop",
1789         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
1790 };
1791
1792 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
1793
1794 const UnitVTable service_vtable = {
1795         .suffix = ".service",
1796
1797         .init = service_init,
1798         .done = service_done,
1799
1800         .dump = service_dump,
1801
1802         .start = service_start,
1803         .stop = service_stop,
1804         .reload = service_reload,
1805
1806         .can_reload = service_can_reload,
1807
1808         .active_state = service_active_state,
1809
1810         .sigchld_event = service_sigchld_event,
1811         .timer_event = service_timer_event,
1812
1813         .cgroup_notify_empty = service_cgroup_notify_event,
1814
1815         .enumerate = service_enumerate
1816 };