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