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