chiark / gitweb /
macro: hookup assert logic with log logic
[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_load(Unit *u) {
730         int r;
731         Service *s = SERVICE(u);
732
733         assert(s);
734
735         /* Load a .service file */
736         if ((r = unit_load_fragment(u)) < 0)
737                 return r;
738
739         /* Load a classic init script as a fallback, if we couldn't find anything */
740         if (u->meta.load_state == UNIT_STUB)
741                 if ((r = service_load_sysv(s)) < 0)
742                         return r;
743
744         /* Still nothing found? Then let's give up */
745         if (u->meta.load_state == UNIT_STUB)
746                 return -ENOENT;
747
748         /* We were able to load something, then let's add in the
749          * dropin directories. */
750         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
751                 return r;
752
753         /* This is a new unit? Then let's add in some extras */
754         if (u->meta.load_state == UNIT_LOADED) {
755                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
756                         return r;
757
758                 if ((r = unit_add_default_cgroup(u)) < 0)
759                         return r;
760
761                 if ((r = sysv_chkconfig_order(s)) < 0)
762                         return r;
763         }
764
765         return 0;
766 }
767
768 static void service_dump(Unit *u, FILE *f, const char *prefix) {
769
770         ServiceExecCommand c;
771         Service *s = SERVICE(u);
772         const char *prefix2;
773         char *p2;
774
775         assert(s);
776
777         p2 = strappend(prefix, "\t");
778         prefix2 = p2 ? p2 : prefix;
779
780         fprintf(f,
781                 "%sService State: %s\n"
782                 "%sPermissionsStartOnly: %s\n"
783                 "%sRootDirectoryStartOnly: %s\n"
784                 "%sValidNoProcess: %s\n"
785                 "%sKillMode: %s\n"
786                 "%sType: %s\n",
787                 prefix, service_state_to_string(s->state),
788                 prefix, yes_no(s->permissions_start_only),
789                 prefix, yes_no(s->root_directory_start_only),
790                 prefix, yes_no(s->valid_no_process),
791                 prefix, kill_mode_to_string(s->kill_mode),
792                 prefix, service_type_to_string(s->type));
793
794         if (s->control_pid > 0)
795                 fprintf(f,
796                         "%sControl PID: %llu\n",
797                         prefix, (unsigned long long) s->control_pid);
798
799         if (s->main_pid > 0)
800                 fprintf(f,
801                         "%sMain PID: %llu\n",
802                         prefix, (unsigned long long) s->main_pid);
803
804         if (s->pid_file)
805                 fprintf(f,
806                         "%sPIDFile: %s\n",
807                         prefix, s->pid_file);
808
809         exec_context_dump(&s->exec_context, f, prefix);
810
811         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
812
813                 if (!s->exec_command[c])
814                         continue;
815
816                 fprintf(f, "%s→ %s:\n",
817                         prefix, service_exec_command_to_string(c));
818
819                 exec_command_dump_list(s->exec_command[c], f, prefix2);
820         }
821
822         if (s->sysv_path)
823                 fprintf(f,
824                         "%sSysV Init Script Path: %s\n"
825                         "%sSysV Init Script has LSB Header: %s\n",
826                         prefix, s->sysv_path,
827                         prefix, yes_no(s->sysv_has_lsb));
828
829         if (s->sysv_start_priority >= 0)
830                 fprintf(f,
831                         "%sSysVStartPriority: %i\n",
832                         prefix, s->sysv_start_priority);
833
834         if (s->sysv_runlevels)
835                 fprintf(f, "%sSysVRunLevels: %s\n",
836                         prefix, s->sysv_runlevels);
837
838         free(p2);
839 }
840
841 static int service_load_pid_file(Service *s) {
842         char *k;
843         unsigned long p;
844         int r;
845
846         assert(s);
847
848         if (s->main_pid_known)
849                 return 0;
850
851         assert(s->main_pid <= 0);
852
853         if (!s->pid_file)
854                 return -ENOENT;
855
856         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
857                 return r;
858
859         if ((r = safe_atolu(k, &p)) < 0) {
860                 free(k);
861                 return r;
862         }
863
864         if ((unsigned long) (pid_t) p != p)
865                 return -ERANGE;
866
867         if (kill((pid_t) p, 0) < 0 && errno != EPERM) {
868                 log_warning("PID %llu read from file %s does not exist. Your service or init script might be broken.",
869                             (unsigned long long) p, s->pid_file);
870                 return -ESRCH;
871         }
872
873         if ((r = unit_watch_pid(UNIT(s), (pid_t) p)) < 0)
874                 /* FIXME: we need to do something here */
875                 return r;
876
877         s->main_pid = (pid_t) p;
878         s->main_pid_known = true;
879
880         return 0;
881 }
882
883 static int service_get_sockets(Service *s, Set **_set) {
884         Set *set;
885         Iterator i;
886         char *t;
887         int r;
888
889         assert(s);
890         assert(_set);
891
892         /* Collects all Socket objects that belong to this
893          * service. Note that a service might have multiple sockets
894          * via multiple names. */
895
896         if (!(set = set_new(NULL, NULL)))
897                 return -ENOMEM;
898
899         SET_FOREACH(t, UNIT(s)->meta.names, i) {
900                 char *k;
901                 Unit *p;
902
903                 /* Look for all socket objects that go by any of our
904                  * units and collect their fds */
905
906                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
907                         r = -ENOMEM;
908                         goto fail;
909                 }
910
911                 p = manager_get_unit(UNIT(s)->meta.manager, k);
912                 free(k);
913
914                 if (!p) continue;
915
916                 if ((r = set_put(set, p)) < 0)
917                         goto fail;
918         }
919
920         *_set = set;
921         return 0;
922
923 fail:
924         set_free(set);
925         return r;
926 }
927
928
929 static int service_notify_sockets_dead(Service *s) {
930         Iterator i;
931         Set *set;
932         Socket *sock;
933         int r;
934
935         assert(s);
936
937         /* Notifies all our sockets when we die */
938
939         if ((r = service_get_sockets(s, &set)) < 0)
940                 return r;
941
942         SET_FOREACH(sock, set, i)
943                 socket_notify_service_dead(sock);
944
945         set_free(set);
946
947         return 0;
948 }
949
950 static void service_set_state(Service *s, ServiceState state) {
951         ServiceState old_state;
952         assert(s);
953
954         old_state = s->state;
955         s->state = state;
956
957         if (state != SERVICE_START_PRE &&
958             state != SERVICE_START &&
959             state != SERVICE_START_POST &&
960             state != SERVICE_RELOAD &&
961             state != SERVICE_STOP &&
962             state != SERVICE_STOP_SIGTERM &&
963             state != SERVICE_STOP_SIGKILL &&
964             state != SERVICE_STOP_POST &&
965             state != SERVICE_FINAL_SIGTERM &&
966             state != SERVICE_FINAL_SIGKILL &&
967             state != SERVICE_AUTO_RESTART)
968                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
969
970         if (state != SERVICE_START &&
971             state != SERVICE_START_POST &&
972             state != SERVICE_RUNNING &&
973             state != SERVICE_RELOAD &&
974             state != SERVICE_STOP &&
975             state != SERVICE_STOP_SIGTERM &&
976             state != SERVICE_STOP_SIGKILL)
977                 service_unwatch_main_pid(s);
978
979         if (state != SERVICE_START_PRE &&
980             state != SERVICE_START &&
981             state != SERVICE_START_POST &&
982             state != SERVICE_RELOAD &&
983             state != SERVICE_STOP &&
984             state != SERVICE_STOP_SIGTERM &&
985             state != SERVICE_STOP_SIGKILL &&
986             state != SERVICE_STOP_POST &&
987             state != SERVICE_FINAL_SIGTERM &&
988             state != SERVICE_FINAL_SIGKILL) {
989                 service_unwatch_control_pid(s);
990                 s->control_command = NULL;
991         }
992
993         if (state == SERVICE_DEAD ||
994             state == SERVICE_STOP ||
995             state == SERVICE_STOP_SIGTERM ||
996             state == SERVICE_STOP_SIGKILL ||
997             state == SERVICE_STOP_POST ||
998             state == SERVICE_FINAL_SIGTERM ||
999             state == SERVICE_FINAL_SIGKILL ||
1000             state == SERVICE_MAINTAINANCE ||
1001             state == SERVICE_AUTO_RESTART)
1002                 service_notify_sockets_dead(s);
1003
1004         if (old_state != state)
1005                 log_debug("%s changed %s â†’ %s", unit_id(UNIT(s)), service_state_to_string(old_state), service_state_to_string(state));
1006
1007         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1008 }
1009
1010 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1011         Iterator i;
1012         int r;
1013         int *rfds = NULL;
1014         unsigned rn_fds = 0;
1015         Set *set;
1016         Socket *sock;
1017
1018         assert(s);
1019         assert(fds);
1020         assert(n_fds);
1021
1022         if ((r = service_get_sockets(s, &set)) < 0)
1023                 return r;
1024
1025         SET_FOREACH(sock, set, i) {
1026                 int *cfds;
1027                 unsigned cn_fds;
1028
1029                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1030                         goto fail;
1031
1032                 if (!cfds)
1033                         continue;
1034
1035                 if (!rfds) {
1036                         rfds = cfds;
1037                         rn_fds = cn_fds;
1038                 } else {
1039                         int *t;
1040
1041                         if (!(t = new(int, rn_fds+cn_fds))) {
1042                                 free(cfds);
1043                                 r = -ENOMEM;
1044                                 goto fail;
1045                         }
1046
1047                         memcpy(t, rfds, rn_fds);
1048                         memcpy(t+rn_fds, cfds, cn_fds);
1049                         free(rfds);
1050                         free(cfds);
1051
1052                         rfds = t;
1053                         rn_fds = rn_fds+cn_fds;
1054                 }
1055         }
1056
1057         *fds = rfds;
1058         *n_fds = rn_fds;
1059
1060         set_free(set);
1061
1062         return 0;
1063
1064 fail:
1065         set_free(set);
1066         free(rfds);
1067
1068         return r;
1069 }
1070
1071 static int service_spawn(
1072                 Service *s,
1073                 ExecCommand *c,
1074                 bool timeout,
1075                 bool pass_fds,
1076                 bool apply_permissions,
1077                 bool apply_chroot,
1078                 pid_t *_pid) {
1079
1080         pid_t pid;
1081         int r;
1082         int *fds = NULL;
1083         unsigned n_fds = 0;
1084
1085         assert(s);
1086         assert(c);
1087         assert(_pid);
1088
1089         if (pass_fds)
1090                 if ((r = service_collect_fds(s, &fds, &n_fds)) < 0)
1091                         goto fail;
1092
1093         if (timeout) {
1094                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1095                         goto fail;
1096         } else
1097                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1098
1099         if ((r = exec_spawn(c,
1100                             &s->exec_context,
1101                             fds, n_fds,
1102                             apply_permissions,
1103                             apply_chroot,
1104                             UNIT(s)->meta.manager->confirm_spawn,
1105                             UNIT(s)->meta.cgroup_bondings,
1106                             &pid)) < 0)
1107                 goto fail;
1108
1109         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1110                 /* FIXME: we need to do something here */
1111                 goto fail;
1112
1113         free(fds);
1114         *_pid = pid;
1115
1116         return 0;
1117
1118 fail:
1119         free(fds);
1120
1121         if (timeout)
1122                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1123
1124         return r;
1125 }
1126
1127 static int main_pid_good(Service *s) {
1128         assert(s);
1129
1130         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1131          * don't know */
1132
1133         /* If we know the pid file, then lets just check if it is
1134          * still valid */
1135         if (s->main_pid_known)
1136                 return s->main_pid > 0;
1137
1138         /* We don't know the pid */
1139         return -EAGAIN;
1140 }
1141
1142 static int control_pid_good(Service *s) {
1143         assert(s);
1144
1145         return s->control_pid > 0;
1146 }
1147
1148 static int cgroup_good(Service *s) {
1149         int r;
1150
1151         assert(s);
1152
1153         if (s->valid_no_process)
1154                 return -EAGAIN;
1155
1156         if ((r = cgroup_bonding_is_empty_list(UNIT(s)->meta.cgroup_bondings)) < 0)
1157                 return r;
1158
1159         return !r;
1160 }
1161
1162 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1163         int r;
1164         assert(s);
1165
1166         if (!success)
1167                 s->failure = true;
1168
1169         if (allow_restart &&
1170             (s->restart == SERVICE_RESTART_ALWAYS ||
1171              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1172
1173                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1174                         goto fail;
1175
1176                 service_set_state(s, SERVICE_AUTO_RESTART);
1177         } else
1178                 service_set_state(s, s->failure ? SERVICE_MAINTAINANCE : SERVICE_DEAD);
1179
1180         return;
1181
1182 fail:
1183         log_warning("%s failed to run install restart timer: %s", unit_id(UNIT(s)), strerror(-r));
1184         service_enter_dead(s, false, false);
1185 }
1186
1187 static void service_enter_signal(Service *s, ServiceState state, bool success);
1188
1189 static void service_enter_stop_post(Service *s, bool success) {
1190         int r;
1191         assert(s);
1192
1193         if (!success)
1194                 s->failure = true;
1195
1196         service_unwatch_control_pid(s);
1197
1198         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1199                 if ((r = service_spawn(s,
1200                                        s->control_command,
1201                                        true,
1202                                        false,
1203                                        !s->permissions_start_only,
1204                                        !s->root_directory_start_only,
1205                                        &s->control_pid)) < 0)
1206                         goto fail;
1207
1208
1209                 service_set_state(s, SERVICE_STOP_POST);
1210         } else
1211                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1212
1213         return;
1214
1215 fail:
1216         log_warning("%s failed to run stop-post executable: %s", unit_id(UNIT(s)), strerror(-r));
1217         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1218 }
1219
1220 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1221         int r;
1222         bool sent = false;
1223
1224         assert(s);
1225
1226         if (!success)
1227                 s->failure = true;
1228
1229         if (s->kill_mode != KILL_NONE) {
1230                 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1231
1232                 if (s->kill_mode == KILL_CONTROL_GROUP) {
1233
1234                         if ((r = cgroup_bonding_kill_list(UNIT(s)->meta.cgroup_bondings, sig)) < 0) {
1235                                 if (r != -EAGAIN && r != -ESRCH)
1236                                         goto fail;
1237                         } else
1238                                 sent = true;
1239                 }
1240
1241                 if (!sent) {
1242                         r = 0;
1243
1244                         if (s->main_pid > 0) {
1245                                 if (kill(s->kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1246                                         r = -errno;
1247                                 else
1248                                         sent = true;
1249                         }
1250
1251                         if (s->control_pid > 0) {
1252                                 if (kill(s->kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1253                                         r = -errno;
1254                                 else
1255                                         sent = true;
1256                         }
1257
1258                         if (r < 0)
1259                                 goto fail;
1260                 }
1261         }
1262
1263         if (sent) {
1264                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1265                         goto fail;
1266
1267                 service_set_state(s, state);
1268         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1269                 service_enter_stop_post(s, true);
1270         else
1271                 service_enter_dead(s, true, true);
1272
1273         return;
1274
1275 fail:
1276         log_warning("%s failed to kill processes: %s", unit_id(UNIT(s)), strerror(-r));
1277
1278         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1279                 service_enter_stop_post(s, false);
1280         else
1281                 service_enter_dead(s, false, true);
1282 }
1283
1284 static void service_enter_stop(Service *s, bool success) {
1285         int r;
1286         assert(s);
1287
1288         if (!success)
1289                 s->failure = true;
1290
1291         service_unwatch_control_pid(s);
1292
1293         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1294                 if ((r = service_spawn(s,
1295                                        s->control_command,
1296                                        true,
1297                                        false,
1298                                        !s->permissions_start_only,
1299                                        !s->root_directory_start_only,
1300                                        &s->control_pid)) < 0)
1301                         goto fail;
1302
1303                 service_set_state(s, SERVICE_STOP);
1304         } else
1305                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1306
1307         return;
1308
1309 fail:
1310         log_warning("%s failed to run stop executable: %s", unit_id(UNIT(s)), strerror(-r));
1311         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1312 }
1313
1314 static void service_enter_running(Service *s, bool success) {
1315         assert(s);
1316
1317         if (!success)
1318                 s->failure = true;
1319
1320         if (main_pid_good(s) != 0 && cgroup_good(s) != 0)
1321                 service_set_state(s, SERVICE_RUNNING);
1322         else if (s->valid_no_process)
1323                 service_set_state(s, SERVICE_EXITED);
1324         else
1325                 service_enter_stop(s, true);
1326 }
1327
1328 static void service_enter_start_post(Service *s) {
1329         int r;
1330         assert(s);
1331
1332         service_unwatch_control_pid(s);
1333
1334         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1335                 if ((r = service_spawn(s,
1336                                        s->control_command,
1337                                        true,
1338                                        false,
1339                                        !s->permissions_start_only,
1340                                        !s->root_directory_start_only,
1341                                        &s->control_pid)) < 0)
1342                         goto fail;
1343
1344
1345                 service_set_state(s, SERVICE_START_POST);
1346         } else
1347                 service_enter_running(s, true);
1348
1349         return;
1350
1351 fail:
1352         log_warning("%s failed to run start-post executable: %s", unit_id(UNIT(s)), strerror(-r));
1353         service_enter_stop(s, false);
1354 }
1355
1356 static void service_enter_start(Service *s) {
1357         pid_t pid;
1358         int r;
1359
1360         assert(s);
1361
1362         assert(s->exec_command[SERVICE_EXEC_START]);
1363         assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1364
1365         if (s->type == SERVICE_FORKING)
1366                 service_unwatch_control_pid(s);
1367         else
1368                 service_unwatch_main_pid(s);
1369
1370         if ((r = service_spawn(s,
1371                                s->exec_command[SERVICE_EXEC_START],
1372                                s->type == SERVICE_FORKING,
1373                                true,
1374                                true,
1375                                true,
1376                                &pid)) < 0)
1377                 goto fail;
1378
1379         if (s->type == SERVICE_SIMPLE) {
1380                 /* For simple services we immediately start
1381                  * the START_POST binaries. */
1382
1383                 s->main_pid = pid;
1384                 s->main_pid_known = true;
1385
1386                 service_enter_start_post(s);
1387
1388         } else  if (s->type == SERVICE_FORKING) {
1389
1390                 /* For forking services we wait until the start
1391                  * process exited. */
1392
1393                 s->control_pid = pid;
1394
1395                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1396                 service_set_state(s, SERVICE_START);
1397
1398         } else if (s->type == SERVICE_FINISH) {
1399
1400                 /* For finishing services we wait until the start
1401                  * process exited, too, but it is our main process. */
1402
1403                 s->main_pid = pid;
1404                 s->main_pid_known = true;
1405
1406                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1407                 service_set_state(s, SERVICE_START);
1408         } else
1409                 assert_not_reached("Unknown service type");
1410
1411         return;
1412
1413 fail:
1414         log_warning("%s failed to run start exectuable: %s", unit_id(UNIT(s)), strerror(-r));
1415         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1416 }
1417
1418 static void service_enter_start_pre(Service *s) {
1419         int r;
1420
1421         assert(s);
1422
1423         service_unwatch_control_pid(s);
1424
1425         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1426                 if ((r = service_spawn(s,
1427                                        s->control_command,
1428                                        true,
1429                                        false,
1430                                        !s->permissions_start_only,
1431                                        !s->root_directory_start_only,
1432                                        &s->control_pid)) < 0)
1433                         goto fail;
1434
1435                 service_set_state(s, SERVICE_START_PRE);
1436         } else
1437                 service_enter_start(s);
1438
1439         return;
1440
1441 fail:
1442         log_warning("%s failed to run start-pre executable: %s", unit_id(UNIT(s)), strerror(-r));
1443         service_enter_dead(s, false, true);
1444 }
1445
1446 static void service_enter_restart(Service *s) {
1447         int r;
1448         assert(s);
1449
1450         if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL)) < 0)
1451                 goto fail;
1452
1453         log_debug("%s scheduled restart job.", unit_id(UNIT(s)));
1454         service_enter_dead(s, true, false);
1455         return;
1456
1457 fail:
1458
1459         log_warning("%s failed to schedule restart job: %s", unit_id(UNIT(s)), strerror(-r));
1460         service_enter_dead(s, false, false);
1461 }
1462
1463 static void service_enter_reload(Service *s) {
1464         int r;
1465
1466         assert(s);
1467
1468         service_unwatch_control_pid(s);
1469
1470         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1471                 if ((r = service_spawn(s,
1472                                        s->control_command,
1473                                        true,
1474                                        false,
1475                                        !s->permissions_start_only,
1476                                        !s->root_directory_start_only,
1477                                        &s->control_pid)) < 0)
1478                         goto fail;
1479
1480                 service_set_state(s, SERVICE_RELOAD);
1481         } else
1482                 service_enter_running(s, true);
1483
1484         return;
1485
1486 fail:
1487         log_warning("%s failed to run reload executable: %s", unit_id(UNIT(s)), strerror(-r));
1488         service_enter_stop(s, false);
1489 }
1490
1491 static void service_run_next(Service *s, bool success) {
1492         int r;
1493
1494         assert(s);
1495         assert(s->control_command);
1496         assert(s->control_command->command_next);
1497
1498         if (!success)
1499                 s->failure = true;
1500
1501         s->control_command = s->control_command->command_next;
1502
1503         service_unwatch_control_pid(s);
1504
1505         if ((r = service_spawn(s,
1506                                s->control_command,
1507                                true,
1508                                false,
1509                                !s->permissions_start_only,
1510                                !s->root_directory_start_only,
1511                                &s->control_pid)) < 0)
1512                 goto fail;
1513
1514         return;
1515
1516 fail:
1517         log_warning("%s failed to run spawn next executable: %s", unit_id(UNIT(s)), strerror(-r));
1518
1519         if (s->state == SERVICE_START_PRE)
1520                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1521         else if (s->state == SERVICE_STOP)
1522                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1523         else if (s->state == SERVICE_STOP_POST)
1524                 service_enter_dead(s, false, true);
1525         else
1526                 service_enter_stop(s, false);
1527 }
1528
1529 static int service_start(Unit *u) {
1530         Service *s = SERVICE(u);
1531
1532         assert(s);
1533
1534         /* We cannot fulfill this request right now, try again later
1535          * please! */
1536         if (s->state == SERVICE_STOP ||
1537             s->state == SERVICE_STOP_SIGTERM ||
1538             s->state == SERVICE_STOP_SIGKILL ||
1539             s->state == SERVICE_STOP_POST ||
1540             s->state == SERVICE_FINAL_SIGTERM ||
1541             s->state == SERVICE_FINAL_SIGKILL)
1542                 return -EAGAIN;
1543
1544         /* Already on it! */
1545         if (s->state == SERVICE_START_PRE ||
1546             s->state == SERVICE_START ||
1547             s->state == SERVICE_START_POST)
1548                 return 0;
1549
1550         assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTAINANCE || s->state == SERVICE_AUTO_RESTART);
1551
1552         /* Make sure we don't enter a busy loop of some kind. */
1553         if (!ratelimit_test(&s->ratelimit)) {
1554                 log_warning("%s start request repeated too quickly, refusing to start.", unit_id(u));
1555                 return -EAGAIN;
1556         }
1557
1558         s->failure = false;
1559         s->main_pid_known = false;
1560
1561         service_enter_start_pre(s);
1562         return 0;
1563 }
1564
1565 static int service_stop(Unit *u) {
1566         Service *s = SERVICE(u);
1567
1568         assert(s);
1569
1570         /* Cannot do this now */
1571         if (s->state == SERVICE_START_PRE ||
1572             s->state == SERVICE_START ||
1573             s->state == SERVICE_START_POST ||
1574             s->state == SERVICE_RELOAD)
1575                 return -EAGAIN;
1576
1577         /* Already on it */
1578         if (s->state == SERVICE_STOP ||
1579             s->state == SERVICE_STOP_SIGTERM ||
1580             s->state == SERVICE_STOP_SIGKILL ||
1581             s->state == SERVICE_STOP_POST ||
1582             s->state == SERVICE_FINAL_SIGTERM ||
1583             s->state == SERVICE_FINAL_SIGKILL)
1584                 return 0;
1585
1586         if (s->state == SERVICE_AUTO_RESTART) {
1587                 service_set_state(s, SERVICE_DEAD);
1588                 return 0;
1589         }
1590
1591         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1592
1593         service_enter_stop(s, true);
1594         return 0;
1595 }
1596
1597 static int service_reload(Unit *u) {
1598         Service *s = SERVICE(u);
1599
1600         assert(s);
1601
1602         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1603
1604         service_enter_reload(s);
1605         return 0;
1606 }
1607
1608 static bool service_can_reload(Unit *u) {
1609         Service *s = SERVICE(u);
1610
1611         assert(s);
1612
1613         return !!s->exec_command[SERVICE_EXEC_RELOAD];
1614 }
1615
1616 static UnitActiveState service_active_state(Unit *u) {
1617         assert(u);
1618
1619         return state_translation_table[SERVICE(u)->state];
1620 }
1621
1622 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1623         Service *s = SERVICE(u);
1624         bool success;
1625
1626         assert(s);
1627         assert(pid >= 0);
1628
1629         success = code == CLD_EXITED && status == 0;
1630         s->failure = s->failure || !success;
1631
1632         if (s->main_pid == pid) {
1633
1634                 exec_status_fill(&s->main_exec_status, pid, code, status);
1635                 s->main_pid = 0;
1636
1637                 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_FINISH) {
1638                         assert(s->exec_command[SERVICE_EXEC_START]);
1639                         s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
1640                 }
1641
1642                 log_debug("%s: main process exited, code=%s, status=%i", unit_id(u), sigchld_code_to_string(code), status);
1643
1644                 /* The service exited, so the service is officially
1645                  * gone. */
1646
1647                 switch (s->state) {
1648
1649                 case SERVICE_START_POST:
1650                 case SERVICE_RELOAD:
1651                 case SERVICE_STOP:
1652                         /* Need to wait until the operation is
1653                          * done */
1654                         break;
1655
1656                 case SERVICE_START:
1657                         assert(s->type == SERVICE_FINISH);
1658
1659                         /* This was our main goal, so let's go on */
1660                         if (success)
1661                                 service_enter_start_post(s);
1662                         else
1663                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1664                         break;
1665
1666                 case SERVICE_RUNNING:
1667                         service_enter_running(s, success);
1668                         break;
1669
1670                 case SERVICE_STOP_SIGTERM:
1671                 case SERVICE_STOP_SIGKILL:
1672
1673                         if (!control_pid_good(s))
1674                                 service_enter_stop_post(s, success);
1675
1676                         /* If there is still a control process, wait for that first */
1677                         break;
1678
1679                 default:
1680                         assert_not_reached("Uh, main process died at wrong time.");
1681                 }
1682
1683         } else if (s->control_pid == pid) {
1684                 assert(s->control_command);
1685
1686                 exec_status_fill(&s->control_command->exec_status, pid, code, status);
1687                 s->control_pid = 0;
1688
1689                 log_debug("%s: control process exited, code=%s status=%i", unit_id(u), sigchld_code_to_string(code), status);
1690
1691                 /* If we are shutting things down anyway we
1692                  * don't care about failing commands. */
1693
1694                 if (s->control_command->command_next && success) {
1695
1696                         /* There is another command to *
1697                          * execute, so let's do that. */
1698
1699                         log_debug("%s running next command for state %s", unit_id(u), service_state_to_string(s->state));
1700                         service_run_next(s, success);
1701
1702                 } else {
1703                         /* No further commands for this step, so let's
1704                          * figure out what to do next */
1705
1706                         log_debug("%s got final SIGCHLD for state %s", unit_id(u), service_state_to_string(s->state));
1707
1708                         switch (s->state) {
1709
1710                         case SERVICE_START_PRE:
1711                                 if (success)
1712                                         service_enter_start(s);
1713                                 else
1714                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1715                                 break;
1716
1717                         case SERVICE_START:
1718                                 assert(s->type == SERVICE_FORKING);
1719
1720                                 /* Let's try to load the pid
1721                                  * file here if we can. We
1722                                  * ignore the return value,
1723                                  * since the PID file might
1724                                  * actually be created by a
1725                                  * START_POST script */
1726
1727                                 if (success) {
1728                                         if (s->pid_file)
1729                                                 service_load_pid_file(s);
1730
1731                                         service_enter_start_post(s);
1732                                 } else
1733                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1734
1735                                 break;
1736
1737                         case SERVICE_START_POST:
1738                                 if (success && s->pid_file && !s->main_pid_known) {
1739                                         int r;
1740
1741                                         /* Hmm, let's see if we can
1742                                          * load the pid now after the
1743                                          * start-post scripts got
1744                                          * executed. */
1745
1746                                         if ((r = service_load_pid_file(s)) < 0)
1747                                                 log_warning("%s: failed to load PID file %s: %s", unit_id(UNIT(s)), s->pid_file, strerror(-r));
1748                                 }
1749
1750                                 /* Fall through */
1751
1752                         case SERVICE_RELOAD:
1753                                 if (success)
1754                                         service_enter_running(s, true);
1755                                 else
1756                                         service_enter_stop(s, false);
1757
1758                                 break;
1759
1760                         case SERVICE_STOP:
1761                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
1762                                 break;
1763
1764                         case SERVICE_STOP_SIGTERM:
1765                         case SERVICE_STOP_SIGKILL:
1766                                 if (main_pid_good(s) <= 0)
1767                                         service_enter_stop_post(s, success);
1768
1769                                 /* If there is still a service
1770                                  * process around, wait until
1771                                  * that one quit, too */
1772                                 break;
1773
1774                         case SERVICE_STOP_POST:
1775                         case SERVICE_FINAL_SIGTERM:
1776                         case SERVICE_FINAL_SIGKILL:
1777                                 service_enter_dead(s, success, true);
1778                                 break;
1779
1780                         default:
1781                                 assert_not_reached("Uh, control process died at wrong time.");
1782                         }
1783                 }
1784         } else
1785                 assert_not_reached("Got SIGCHLD for unkown PID");
1786 }
1787
1788 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
1789         Service *s = SERVICE(u);
1790
1791         assert(s);
1792         assert(elapsed == 1);
1793
1794         assert(w == &s->timer_watch);
1795
1796         switch (s->state) {
1797
1798         case SERVICE_START_PRE:
1799         case SERVICE_START:
1800                 log_warning("%s operation timed out. Terminating.", unit_id(u));
1801                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1802                 break;
1803
1804         case SERVICE_START_POST:
1805         case SERVICE_RELOAD:
1806                 log_warning("%s operation timed out. Stopping.", unit_id(u));
1807                 service_enter_stop(s, false);
1808                 break;
1809
1810         case SERVICE_STOP:
1811                 log_warning("%s stopping timed out. Terminating.", unit_id(u));
1812                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1813                 break;
1814
1815         case SERVICE_STOP_SIGTERM:
1816                 log_warning("%s stopping timed out. Killing.", unit_id(u));
1817                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
1818                 break;
1819
1820         case SERVICE_STOP_SIGKILL:
1821                 /* Uh, wie sent a SIGKILL and it is still not gone?
1822                  * Must be something we cannot kill, so let's just be
1823                  * weirded out and continue */
1824
1825                 log_warning("%s still around after SIGKILL. Ignoring.", unit_id(u));
1826                 service_enter_stop_post(s, false);
1827                 break;
1828
1829         case SERVICE_STOP_POST:
1830                 log_warning("%s stopping timed out (2). Terminating.", unit_id(u));
1831                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1832                 break;
1833
1834         case SERVICE_FINAL_SIGTERM:
1835                 log_warning("%s stopping timed out (2). Killing.", unit_id(u));
1836                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
1837                 break;
1838
1839         case SERVICE_FINAL_SIGKILL:
1840                 log_warning("%s still around after SIGKILL (2). Entering maintainance mode.", unit_id(u));
1841                 service_enter_dead(s, false, true);
1842                 break;
1843
1844         case SERVICE_AUTO_RESTART:
1845                 log_debug("%s holdoff time over, scheduling restart.", unit_id(u));
1846                 service_enter_restart(s);
1847                 break;
1848
1849         default:
1850                 assert_not_reached("Timeout at wrong time.");
1851         }
1852 }
1853
1854 static void service_cgroup_notify_event(Unit *u) {
1855         Service *s = SERVICE(u);
1856
1857         assert(u);
1858
1859         log_debug("%s: cgroup is empty", unit_id(u));
1860
1861         switch (s->state) {
1862
1863                 /* Waiting for SIGCHLD is usually more interesting,
1864                  * because it includes return codes/signals. Which is
1865                  * why we ignore the cgroup events for most cases,
1866                  * except when we don't know pid which to expect the
1867                  * SIGCHLD for. */
1868
1869         case SERVICE_RUNNING:
1870                 service_enter_running(s, true);
1871                 break;
1872
1873         default:
1874                 ;
1875         }
1876 }
1877
1878 static int service_enumerate(Manager *m) {
1879         char **p;
1880         unsigned i;
1881         DIR *d = NULL;
1882         char *path = NULL, *fpath = NULL, *name = NULL;
1883         int r;
1884
1885         assert(m);
1886
1887         STRV_FOREACH(p, m->sysvrcnd_path)
1888                 for (i = 0; i < ELEMENTSOF(rcnd_table); i += 2) {
1889                         struct dirent *de;
1890
1891                         free(path);
1892                         path = NULL;
1893                         if (asprintf(&path, "%s/%s", *p, rcnd_table[i]) < 0) {
1894                                 r = -ENOMEM;
1895                                 goto finish;
1896                         }
1897
1898                         if (d)
1899                                 closedir(d);
1900
1901                         if (!(d = opendir(path))) {
1902                                 if (errno != ENOENT)
1903                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
1904
1905                                 continue;
1906                         }
1907
1908                         while ((de = readdir(d))) {
1909                                 Unit *runlevel, *service;
1910
1911                                 if (ignore_file(de->d_name))
1912                                         continue;
1913
1914                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
1915                                         continue;
1916
1917                                 if (strlen(de->d_name) < 4)
1918                                         continue;
1919
1920                                 free(fpath);
1921                                 fpath = NULL;
1922                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i], de->d_name) < 0) {
1923                                         r = -ENOMEM;
1924                                         goto finish;
1925                                 }
1926
1927                                 if (access(fpath, X_OK) < 0) {
1928
1929                                         if (errno != ENOENT)
1930                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
1931
1932                                         continue;
1933                                 }
1934
1935                                 free(name);
1936                                 name = NULL;
1937                                 if (asprintf(&name, "%s.service", de->d_name+3) < 0) {
1938                                         r = -ENOMEM;
1939                                         goto finish;
1940                                 }
1941
1942                                 if ((r = manager_load_unit(m, name, &service)) < 0)
1943                                         goto finish;
1944
1945                                 if ((r = manager_load_unit(m, rcnd_table[i+1], &runlevel)) < 0)
1946                                         goto finish;
1947
1948                                 if (de->d_name[0] == 'S') {
1949                                         if ((r = unit_add_dependency(runlevel, UNIT_WANTS, service)) < 0)
1950                                                 goto finish;
1951
1952                                         if ((r = unit_add_dependency(runlevel, UNIT_AFTER, service)) < 0)
1953                                                 goto finish;
1954
1955                                 } else if (de->d_name[0] == 'K' &&
1956                                            (streq(rcnd_table[i+1], SPECIAL_RUNLEVEL0_TARGET) ||
1957                                             streq(rcnd_table[i+1], SPECIAL_RUNLEVEL6_TARGET))) {
1958
1959                                         /* We honour K links only for
1960                                          * halt/reboot. For the normal
1961                                          * runlevels we assume the
1962                                          * stop jobs will be
1963                                          * implicitly added by the
1964                                          * core logic. */
1965
1966                                         if ((r = unit_add_dependency(runlevel, UNIT_CONFLICTS, service)) < 0)
1967                                                 goto finish;
1968
1969                                         if ((r = unit_add_dependency(runlevel, UNIT_BEFORE, service)) < 0)
1970                                                 goto finish;
1971                                 }
1972                         }
1973                 }
1974
1975         r = 0;
1976
1977 finish:
1978         free(path);
1979         free(fpath);
1980         free(name);
1981         closedir(d);
1982
1983         return r;
1984 }
1985
1986 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
1987         [SERVICE_DEAD] = "dead",
1988         [SERVICE_START_PRE] = "start-pre",
1989         [SERVICE_START] = "start",
1990         [SERVICE_START_POST] = "start-post",
1991         [SERVICE_RUNNING] = "running",
1992         [SERVICE_EXITED] = "exited",
1993         [SERVICE_RELOAD] = "reload",
1994         [SERVICE_STOP] = "stop",
1995         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
1996         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
1997         [SERVICE_STOP_POST] = "stop-post",
1998         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
1999         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2000         [SERVICE_MAINTAINANCE] = "maintainance",
2001         [SERVICE_AUTO_RESTART] = "auto-restart",
2002 };
2003
2004 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2005
2006 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2007         [SERVICE_ONCE] = "once",
2008         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2009         [SERVICE_RESTART_ALWAYS] = "restart-always",
2010 };
2011
2012 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2013
2014 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2015         [SERVICE_FORKING] = "forking",
2016         [SERVICE_SIMPLE] = "simple",
2017         [SERVICE_FINISH] = "finish"
2018 };
2019
2020 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2021
2022 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2023         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2024         [SERVICE_EXEC_START] = "ExecStart",
2025         [SERVICE_EXEC_START_POST] = "ExecStartPost",
2026         [SERVICE_EXEC_RELOAD] = "ExecReload",
2027         [SERVICE_EXEC_STOP] = "ExecStop",
2028         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2029 };
2030
2031 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2032
2033 const UnitVTable service_vtable = {
2034         .suffix = ".service",
2035
2036         .init = service_init,
2037         .load = service_load,
2038         .done = service_done,
2039
2040         .dump = service_dump,
2041
2042         .start = service_start,
2043         .stop = service_stop,
2044         .reload = service_reload,
2045
2046         .can_reload = service_can_reload,
2047
2048         .active_state = service_active_state,
2049
2050         .sigchld_event = service_sigchld_event,
2051         .timer_event = service_timer_event,
2052
2053         .cgroup_notify_empty = service_cgroup_notify_event,
2054
2055         .enumerate = service_enumerate
2056 };