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