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