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