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