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