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