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