chiark / gitweb /
51a7e6b20f54eed85e0604bb9dee2297cc696f3d
[elogind.git] / src / service.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 #include "special.h"
36 #include "bus-errors.h"
37
38 #define COMMENTS "#;\n"
39 #define NEWLINES "\n\r"
40
41 typedef enum RunlevelType {
42         RUNLEVEL_UP,
43         RUNLEVEL_DOWN,
44         RUNLEVEL_SYSINIT
45 } RunlevelType;
46
47 static const struct {
48         const char *path;
49         const char *target;
50         const RunlevelType type;
51 } rcnd_table[] = {
52         /* Standard SysV runlevels for start-up */
53         { "rc1.d",  SPECIAL_RESCUE_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
59 #ifdef TARGET_SUSE
60         /* SUSE style boot.d */
61         { "boot.d", SPECIAL_SYSINIT_TARGET,   RUNLEVEL_SYSINIT },
62 #endif
63
64 #ifdef TARGET_DEBIAN
65         /* Debian style rcS.d */
66         { "rcS.d",  SPECIAL_SYSINIT_TARGET,   RUNLEVEL_SYSINIT },
67 #endif
68
69         /* Standard SysV runlevels for shutdown */
70         { "rc0.d",  SPECIAL_POWEROFF_TARGET,  RUNLEVEL_DOWN },
71         { "rc6.d",  SPECIAL_REBOOT_TARGET,    RUNLEVEL_DOWN }
72
73         /* Note that the order here matters, as we read the
74            directories in this order, and we want to make sure that
75            sysv_start_priority is known when we first load the
76            unit. And that value we only know from S links. Hence
77            UP/SYSINIT must be read before DOWN */
78 };
79
80 #define RUNLEVELS_UP "12345"
81 /* #define RUNLEVELS_DOWN "06" */
82 /* #define RUNLEVELS_BOOT "bBsS" */
83
84 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
85         [SERVICE_DEAD] = UNIT_INACTIVE,
86         [SERVICE_START_PRE] = UNIT_ACTIVATING,
87         [SERVICE_START] = UNIT_ACTIVATING,
88         [SERVICE_START_POST] = UNIT_ACTIVATING,
89         [SERVICE_RUNNING] = UNIT_ACTIVE,
90         [SERVICE_EXITED] = UNIT_ACTIVE,
91         [SERVICE_RELOAD] = UNIT_RELOADING,
92         [SERVICE_STOP] = UNIT_DEACTIVATING,
93         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
94         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
95         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
96         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
97         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
98         [SERVICE_FAILED] = UNIT_FAILED,
99         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
100 };
101
102 static void service_init(Unit *u) {
103         Service *s = SERVICE(u);
104
105         assert(u);
106         assert(u->meta.load_state == UNIT_STUB);
107
108         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
109         s->restart_usec = DEFAULT_RESTART_USEC;
110         s->timer_watch.type = WATCH_INVALID;
111         s->sysv_start_priority = -1;
112         s->socket_fd = -1;
113
114         exec_context_init(&s->exec_context);
115
116         RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
117
118         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
119 }
120
121 static void service_unwatch_control_pid(Service *s) {
122         assert(s);
123
124         if (s->control_pid <= 0)
125                 return;
126
127         unit_unwatch_pid(UNIT(s), s->control_pid);
128         s->control_pid = 0;
129 }
130
131 static void service_unwatch_main_pid(Service *s) {
132         assert(s);
133
134         if (s->main_pid <= 0)
135                 return;
136
137         unit_unwatch_pid(UNIT(s), s->main_pid);
138         s->main_pid = 0;
139 }
140
141 static int service_set_main_pid(Service *s, pid_t pid) {
142         pid_t ppid;
143
144         assert(s);
145
146         if (pid <= 1)
147                 return -EINVAL;
148
149         if (pid == getpid())
150                 return -EINVAL;
151
152         if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid())
153                 log_warning("%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
154                             s->meta.id, (unsigned long) pid);
155
156         s->main_pid = pid;
157         s->main_pid_known = true;
158
159         exec_status_start(&s->main_exec_status, pid);
160
161         return 0;
162 }
163
164 static void service_close_socket_fd(Service *s) {
165         assert(s);
166
167         if (s->socket_fd < 0)
168                 return;
169
170         close_nointr_nofail(s->socket_fd);
171         s->socket_fd = -1;
172 }
173
174 static void service_connection_unref(Service *s) {
175         assert(s);
176
177         if (!s->socket)
178                 return;
179
180         socket_connection_unref(s->socket);
181         s->socket = NULL;
182 }
183
184 static void service_done(Unit *u) {
185         Service *s = SERVICE(u);
186
187         assert(s);
188
189         free(s->pid_file);
190         s->pid_file = NULL;
191
192         free(s->sysv_path);
193         s->sysv_path = NULL;
194
195         free(s->sysv_runlevels);
196         s->sysv_runlevels = NULL;
197
198         free(s->status_text);
199         s->status_text = NULL;
200
201         exec_context_done(&s->exec_context);
202         exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
203         s->control_command = NULL;
204
205         /* This will leak a process, but at least no memory or any of
206          * our resources */
207         service_unwatch_main_pid(s);
208         service_unwatch_control_pid(s);
209
210         if (s->bus_name)  {
211                 unit_unwatch_bus_name(UNIT(u), s->bus_name);
212                 free(s->bus_name);
213                 s->bus_name = NULL;
214         }
215
216         service_close_socket_fd(s);
217         service_connection_unref(s);
218
219         unit_unwatch_timer(u, &s->timer_watch);
220 }
221
222 static char *sysv_translate_name(const char *name) {
223         char *r;
224
225         if (!(r = new(char, strlen(name) + sizeof(".service"))))
226                 return NULL;
227
228         if (startswith(name, "boot."))
229                 /* Drop SuSE-style boot. prefix */
230                 strcpy(stpcpy(r, name + 5), ".service");
231         else if (endswith(name, ".sh"))
232                 /* Drop Debian-style .sh suffix */
233                 strcpy(stpcpy(r, name) - 3, ".service");
234 #ifdef TARGET_ARCH
235         else if (startswith(name, "@"))
236                 /* Drop Arch-style background prefix */
237                 strcpy(stpcpy(r, name + 1), ".service");
238 #endif
239         else
240                 /* Normal init scripts */
241                 strcpy(stpcpy(r, name), ".service");
242
243         return r;
244 }
245
246 static int sysv_translate_facility(const char *name, char **_r) {
247
248         static const char * const table[] = {
249                 /* LSB defined facilities */
250                 "$local_fs",  SPECIAL_LOCAL_FS_TARGET,
251                 "$network",   SPECIAL_NETWORK_TARGET,
252                 "$named",     SPECIAL_NSS_LOOKUP_TARGET,
253                 "$portmap",   SPECIAL_RPCBIND_TARGET,
254                 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
255                 "$syslog",    SPECIAL_SYSLOG_TARGET,
256                 "$time",      SPECIAL_RTC_SET_TARGET,
257
258                 /* Debian extensions */
259 #ifdef TARGET_DEBIAN
260                 "$mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
261 #endif
262                 "$mail-transfer-agent",  SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
263                 "$x-display-manager",    SPECIAL_DISPLAY_MANAGER_SERVICE,
264
265 #ifdef TARGET_FEDORA
266                 /* Fedora extensions, lacking the $ prefix */
267                 "MTA",        SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
268                 "smtpdaemon", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
269                 "httpd",      SPECIAL_HTTP_DAEMON_TARGET,
270 #endif
271         };
272
273         unsigned i;
274         char *r;
275
276         for (i = 0; i < ELEMENTSOF(table); i += 2)
277                 if (streq(table[i], name)) {
278                         if (!(r = strdup(table[i+1])))
279                                 return -ENOMEM;
280
281                         goto finish;
282                 }
283
284         if (*name == '$')
285                 r = unit_name_build(name+1, NULL, ".target");
286         else
287                 r = sysv_translate_name(name);
288
289         if (!r)
290                 return -ENOMEM;
291
292 finish:
293
294         if (_r)
295                 *_r = r;
296
297         return 1;
298 }
299
300 static int sysv_fix_order(Service *s) {
301         Meta *other;
302         int r;
303
304         assert(s);
305
306         if (s->sysv_start_priority < 0)
307                 return 0;
308
309         /* For each pair of services where at least one lacks a LSB
310          * header, we use the start priority value to order things. */
311
312         LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_SERVICE]) {
313                 Service *t;
314                 UnitDependency d;
315                 bool special_s, special_t;
316
317                 t = (Service*) other;
318
319                 if (s == t)
320                         continue;
321
322                 if (t->sysv_start_priority < 0)
323                         continue;
324
325                 /* If both units have modern headers we don't care
326                  * about the priorities */
327                 if ((s->meta.fragment_path || s->sysv_has_lsb) &&
328                     (t->meta.fragment_path || t->sysv_has_lsb))
329                         continue;
330
331                 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
332                 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
333
334                 if (special_t && !special_s)
335                         d = UNIT_AFTER;
336                 else if (special_s && !special_t)
337                         d = UNIT_BEFORE;
338                 else if (t->sysv_start_priority < s->sysv_start_priority)
339                         d = UNIT_AFTER;
340                 else if (t->sysv_start_priority > s->sysv_start_priority)
341                         d = UNIT_BEFORE;
342                 else
343                         continue;
344
345                 /* FIXME: Maybe we should compare the name here lexicographically? */
346
347                 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
348                         return r;
349         }
350
351         return 0;
352 }
353
354 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
355         ExecCommand *c;
356
357         if (!(c = new0(ExecCommand, 1)))
358                 return NULL;
359
360         if (!(c->path = strdup(path))) {
361                 free(c);
362                 return NULL;
363         }
364
365         if (!(c->argv = strv_new(path, arg1, NULL))) {
366                 free(c->path);
367                 free(c);
368                 return NULL;
369         }
370
371         return c;
372 }
373
374 static int sysv_exec_commands(Service *s) {
375         ExecCommand *c;
376
377         assert(s);
378         assert(s->sysv_path);
379
380         if (!(c = exec_command_new(s->sysv_path, "start")))
381                 return -ENOMEM;
382         exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
383
384         if (!(c = exec_command_new(s->sysv_path, "stop")))
385                 return -ENOMEM;
386         exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
387
388         if (!(c = exec_command_new(s->sysv_path, "reload")))
389                 return -ENOMEM;
390         exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
391
392         return 0;
393 }
394
395 static int service_load_sysv_path(Service *s, const char *path) {
396         FILE *f;
397         Unit *u;
398         unsigned line = 0;
399         int r;
400         enum {
401                 NORMAL,
402                 DESCRIPTION,
403                 LSB,
404                 LSB_DESCRIPTION
405         } state = NORMAL;
406
407         assert(s);
408         assert(path);
409
410         u = UNIT(s);
411
412         if (!(f = fopen(path, "re"))) {
413                 r = errno == ENOENT ? 0 : -errno;
414                 goto finish;
415         }
416
417         free(s->sysv_path);
418         if (!(s->sysv_path = strdup(path))) {
419                 r = -ENOMEM;
420                 goto finish;
421         }
422
423         while (!feof(f)) {
424                 char l[LINE_MAX], *t;
425
426                 if (!fgets(l, sizeof(l), f)) {
427                         if (feof(f))
428                                 break;
429
430                         r = -errno;
431                         log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
432                         goto finish;
433                 }
434
435                 line++;
436
437                 t = strstrip(l);
438                 if (*t != '#')
439                         continue;
440
441                 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
442                         state = LSB;
443                         s->sysv_has_lsb = true;
444                         continue;
445                 }
446
447                 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
448                         state = NORMAL;
449                         continue;
450                 }
451
452                 t++;
453                 t += strspn(t, WHITESPACE);
454
455                 if (state == NORMAL) {
456
457                         /* Try to parse Red Hat style chkconfig headers */
458
459                         if (startswith_no_case(t, "chkconfig:")) {
460                                 int start_priority;
461                                 char runlevels[16], *k;
462
463                                 state = NORMAL;
464
465                                 if (sscanf(t+10, "%15s %i %*i",
466                                            runlevels,
467                                            &start_priority) != 2) {
468
469                                         log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
470                                         continue;
471                                 }
472
473                                 /* A start priority gathered from the
474                                  * symlink farms is preferred over the
475                                  * data from the LSB header. */
476                                 if (start_priority < 0 || start_priority > 99)
477                                         log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
478                                 else if (s->sysv_start_priority < 0)
479                                         s->sysv_start_priority = start_priority;
480
481                                 char_array_0(runlevels);
482                                 k = delete_chars(runlevels, WHITESPACE "-");
483
484                                 if (k[0]) {
485                                         char *d;
486
487                                         if (!(d = strdup(k))) {
488                                                 r = -ENOMEM;
489                                                 goto finish;
490                                         }
491
492                                         free(s->sysv_runlevels);
493                                         s->sysv_runlevels = d;
494                                 }
495
496                         } else if (startswith_no_case(t, "description:") &&
497                                    !u->meta.description) {
498
499                                 size_t k = strlen(t);
500                                 char *d;
501
502                                 if (t[k-1] == '\\') {
503                                         state = DESCRIPTION;
504                                         t[k-1] = 0;
505                                 }
506
507                                 if (!(d = strappend("LSB: ", strstrip(t+12)))) {
508                                         r = -ENOMEM;
509                                         goto finish;
510                                 }
511
512                                 free(u->meta.description);
513                                 u->meta.description = d;
514
515                         } else if (startswith_no_case(t, "pidfile:")) {
516
517                                 char *fn;
518
519                                 state = NORMAL;
520
521                                 fn = strstrip(t+8);
522                                 if (!path_is_absolute(fn)) {
523                                         log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
524                                         continue;
525                                 }
526
527                                 if (!(fn = strdup(fn))) {
528                                         r = -ENOMEM;
529                                         goto finish;
530                                 }
531
532                                 free(s->pid_file);
533                                 s->pid_file = fn;
534                         }
535
536                 } else if (state == DESCRIPTION) {
537
538                         /* Try to parse Red Hat style description
539                          * continuation */
540
541                         size_t k = strlen(t);
542                         char *d;
543
544                         if (t[k-1] == '\\')
545                                 t[k-1] = 0;
546                         else
547                                 state = NORMAL;
548
549                         assert(u->meta.description);
550                         if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
551                                 r = -ENOMEM;
552                                 goto finish;
553                         }
554
555                         free(u->meta.description);
556                         u->meta.description = d;
557
558                 } else if (state == LSB || state == LSB_DESCRIPTION) {
559
560                         if (startswith_no_case(t, "Provides:")) {
561                                 char *i, *w;
562                                 size_t z;
563
564                                 state = LSB;
565
566                                 FOREACH_WORD_QUOTED(w, z, t+9, i) {
567                                         char *n, *m;
568
569                                         if (!(n = strndup(w, z))) {
570                                                 r = -ENOMEM;
571                                                 goto finish;
572                                         }
573
574                                         r = sysv_translate_facility(n, &m);
575                                         free(n);
576
577                                         if (r < 0)
578                                                 goto finish;
579
580                                         if (r == 0)
581                                                 continue;
582
583                                         if (unit_name_to_type(m) == UNIT_SERVICE)
584                                                 r = unit_add_name(u, m);
585                                         else {
586                                                 r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
587
588                                                 if (s->sysv_enabled) {
589                                                         int k;
590
591                                                         if ((k = unit_add_dependency_by_name_inverse(u, UNIT_WANTS, m, NULL, true)) < 0)
592                                                                 r = k;
593                                                 }
594                                         }
595
596                                         if (r < 0)
597                                                 log_error("[%s:%u] Failed to add LSB Provides name %s, ignoring: %s", path, line, m, strerror(-r));
598
599                                         free(m);
600                                 }
601
602                         } else if (startswith_no_case(t, "Required-Start:") ||
603                                    startswith_no_case(t, "Should-Start:") ||
604                                    startswith_no_case(t, "X-Start-Before:") ||
605                                    startswith_no_case(t, "X-Start-After:")) {
606                                 char *i, *w;
607                                 size_t z;
608
609                                 state = LSB;
610
611                                 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
612                                         char *n, *m;
613
614                                         if (!(n = strndup(w, z))) {
615                                                 r = -ENOMEM;
616                                                 goto finish;
617                                         }
618
619                                         r = sysv_translate_facility(n, &m);
620                                         free(n);
621
622                                         if (r < 0)
623                                                 goto finish;
624
625                                         if (r == 0)
626                                                 continue;
627
628                                         r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
629
630                                         if (r < 0)
631                                                 log_error("[%s:%u] Failed to add dependency on %s, ignoring: %s", path, line, m, strerror(-r));
632
633                                         free(m);
634                                 }
635                         } else if (startswith_no_case(t, "Default-Start:")) {
636                                 char *k, *d;
637
638                                 state = LSB;
639
640                                 k = delete_chars(t+14, WHITESPACE "-");
641
642                                 if (k[0] != 0) {
643                                         if (!(d = strdup(k))) {
644                                                 r = -ENOMEM;
645                                                 goto finish;
646                                         }
647
648                                         free(s->sysv_runlevels);
649                                         s->sysv_runlevels = d;
650                                 }
651
652                         } else if (startswith_no_case(t, "Description:") &&
653                                    !u->meta.description) {
654                                 char *d;
655
656                                 /* We use the long description only if
657                                  * no short description is set. */
658
659                                 state = LSB_DESCRIPTION;
660
661                                 if (!(d = strappend("LSB: ", strstrip(t+12)))) {
662                                         r = -ENOMEM;
663                                         goto finish;
664                                 }
665
666                                 free(u->meta.description);
667                                 u->meta.description = d;
668
669                         } else if (startswith_no_case(t, "Short-Description:")) {
670                                 char *d;
671
672                                 state = LSB;
673
674                                 if (!(d = strappend("LSB: ", strstrip(t+18)))) {
675                                         r = -ENOMEM;
676                                         goto finish;
677                                 }
678
679                                 free(u->meta.description);
680                                 u->meta.description = d;
681
682                         } else if (startswith_no_case(t, "X-Interactive:")) {
683                                 int b;
684
685                                 if ((b = parse_boolean(strstrip(t+14))) < 0) {
686                                         log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
687                                         continue;
688                                 }
689
690                                 if (b)
691                                         s->exec_context.std_input = EXEC_INPUT_TTY;
692                                 else
693                                         s->exec_context.std_input = EXEC_INPUT_NULL;
694
695                         } else if (state == LSB_DESCRIPTION) {
696
697                                 if (startswith(l, "#\t") || startswith(l, "#  ")) {
698                                         char *d;
699
700                                         assert(u->meta.description);
701                                         if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
702                                                 r = -ENOMEM;
703                                                 goto finish;
704                                         }
705
706                                         free(u->meta.description);
707                                         u->meta.description = d;
708                                 } else
709                                         state = LSB;
710                         }
711                 }
712         }
713
714         if ((r = sysv_exec_commands(s)) < 0)
715                 goto finish;
716
717         if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
718                 /* If there a runlevels configured for this service
719                  * but none of the standard ones, then we assume this
720                  * is some special kind of service (which might be
721                  * needed for early boot) and don't create any links
722                  * to it. */
723
724                 s->meta.default_dependencies = false;
725
726                 /* Don't timeout special services during boot (like fsck) */
727                 s->timeout_usec = 0;
728         }
729
730         /* Special setting for all SysV services */
731         s->type = SERVICE_FORKING;
732         s->remain_after_exit = true;
733         s->restart = SERVICE_ONCE;
734         s->exec_context.std_output =
735                 (s->meta.manager->sysv_console || s->exec_context.std_input == EXEC_INPUT_TTY)
736                 ? EXEC_OUTPUT_TTY : EXEC_OUTPUT_NULL;
737         s->exec_context.kill_mode = KILL_PROCESS_GROUP;
738
739         u->meta.load_state = UNIT_LOADED;
740         r = 0;
741
742 finish:
743
744         if (f)
745                 fclose(f);
746
747         return r;
748 }
749
750 static int service_load_sysv_name(Service *s, const char *name) {
751         char **p;
752
753         assert(s);
754         assert(name);
755
756         /* For SysV services we strip the boot. or .sh
757          * prefixes/suffixes. */
758         if (startswith(name, "boot.") ||
759             endswith(name, ".sh.service"))
760                 return -ENOENT;
761
762         STRV_FOREACH(p, s->meta.manager->lookup_paths.sysvinit_path) {
763                 char *path;
764                 int r;
765
766                 if (asprintf(&path, "%s/%s", *p, name) < 0)
767                         return -ENOMEM;
768
769                 assert(endswith(path, ".service"));
770                 path[strlen(path)-8] = 0;
771
772                 r = service_load_sysv_path(s, path);
773
774                 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
775                         /* Try Debian style xxx.sh source'able init scripts */
776                         strcat(path, ".sh");
777                         r = service_load_sysv_path(s, path);
778                 }
779
780                 free(path);
781
782                 if (r >= 0 && s->meta.load_state == UNIT_STUB) {
783                         /* Try SUSE style boot.xxx init scripts */
784
785                         if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
786                                 return -ENOMEM;
787
788                         path[strlen(path)-8] = 0;
789                         r = service_load_sysv_path(s, path);
790                         free(path);
791                 }
792
793                 if (r < 0)
794                         return r;
795
796                 if ((s->meta.load_state != UNIT_STUB))
797                         break;
798         }
799
800         return 0;
801 }
802
803 static int service_load_sysv(Service *s) {
804         const char *t;
805         Iterator i;
806         int r;
807
808         assert(s);
809
810         /* Load service data from SysV init scripts, preferably with
811          * LSB headers ... */
812
813         if (strv_isempty(s->meta.manager->lookup_paths.sysvinit_path))
814                 return 0;
815
816         if ((t = s->meta.id))
817                 if ((r = service_load_sysv_name(s, t)) < 0)
818                         return r;
819
820         if (s->meta.load_state == UNIT_STUB)
821                 SET_FOREACH(t, s->meta.names, i) {
822                         if (t == s->meta.id)
823                                 continue;
824
825                         if ((r = service_load_sysv_name(s, t)) < 0)
826                                 return r;
827
828                         if (s->meta.load_state != UNIT_STUB)
829                                 break;
830                 }
831
832         return 0;
833 }
834
835 static int service_verify(Service *s) {
836         assert(s);
837
838         if (s->meta.load_state != UNIT_LOADED)
839                 return 0;
840
841         if (!s->exec_command[SERVICE_EXEC_START]) {
842                 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
843                 return -EINVAL;
844         }
845
846         if (s->type != SERVICE_ONESHOT &&
847             s->exec_command[SERVICE_EXEC_START]->command_next) {
848                 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
849                 return -EINVAL;
850         }
851
852         if (s->type == SERVICE_DBUS && !s->bus_name) {
853                 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
854                 return -EINVAL;
855         }
856
857         if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
858                 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
859                 return -EINVAL;
860         }
861
862         return 0;
863 }
864
865 static int service_add_default_dependencies(Service *s) {
866         int r;
867
868         assert(s);
869
870         /* Add a number of automatic dependencies useful for the
871          * majority of services. */
872
873         /* First, pull in base system */
874         if (s->meta.manager->running_as == MANAGER_SYSTEM) {
875
876                 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
877                         return r;
878
879         } else if (s->meta.manager->running_as == MANAGER_SESSION) {
880
881                 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
882                         return r;
883         }
884
885         /* Second, activate normal shutdown */
886         return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTED_BY, SPECIAL_SHUTDOWN_TARGET, NULL, true);
887 }
888
889 static int service_load(Unit *u) {
890         int r;
891         Service *s = SERVICE(u);
892
893         assert(s);
894
895         /* Load a .service file */
896         if ((r = unit_load_fragment(u)) < 0)
897                 return r;
898
899         /* Load a classic init script as a fallback, if we couldn't find anything */
900         if (u->meta.load_state == UNIT_STUB)
901                 if ((r = service_load_sysv(s)) < 0)
902                         return r;
903
904         /* Still nothing found? Then let's give up */
905         if (u->meta.load_state == UNIT_STUB)
906                 return -ENOENT;
907
908         /* We were able to load something, then let's add in the
909          * dropin directories. */
910         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
911                 return r;
912
913         /* This is a new unit? Then let's add in some extras */
914         if (u->meta.load_state == UNIT_LOADED) {
915                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
916                         return r;
917
918                 if ((r = unit_add_default_cgroup(u)) < 0)
919                         return r;
920
921                 if ((r = sysv_fix_order(s)) < 0)
922                         return r;
923
924                 if (s->bus_name)
925                         if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
926                                 return r;
927
928                 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
929                         s->notify_access = NOTIFY_MAIN;
930
931                 if (s->type == SERVICE_DBUS || s->bus_name)
932                         if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
933                                 return r;
934
935                 if (s->meta.default_dependencies)
936                         if ((r = service_add_default_dependencies(s)) < 0)
937                                 return r;
938         }
939
940         return service_verify(s);
941 }
942
943 static void service_dump(Unit *u, FILE *f, const char *prefix) {
944
945         ServiceExecCommand c;
946         Service *s = SERVICE(u);
947         const char *prefix2;
948         char *p2;
949
950         assert(s);
951
952         p2 = strappend(prefix, "\t");
953         prefix2 = p2 ? p2 : prefix;
954
955         fprintf(f,
956                 "%sService State: %s\n"
957                 "%sPermissionsStartOnly: %s\n"
958                 "%sRootDirectoryStartOnly: %s\n"
959                 "%sRemainAfterExit: %s\n"
960                 "%sType: %s\n"
961                 "%sRestart: %s\n"
962                 "%sNotifyAccess: %s\n",
963                 prefix, service_state_to_string(s->state),
964                 prefix, yes_no(s->permissions_start_only),
965                 prefix, yes_no(s->root_directory_start_only),
966                 prefix, yes_no(s->remain_after_exit),
967                 prefix, service_type_to_string(s->type),
968                 prefix, service_restart_to_string(s->restart),
969                 prefix, notify_access_to_string(s->notify_access));
970
971         if (s->control_pid > 0)
972                 fprintf(f,
973                         "%sControl PID: %lu\n",
974                         prefix, (unsigned long) s->control_pid);
975
976         if (s->main_pid > 0)
977                 fprintf(f,
978                         "%sMain PID: %lu\n",
979                         prefix, (unsigned long) s->main_pid);
980
981         if (s->pid_file)
982                 fprintf(f,
983                         "%sPIDFile: %s\n",
984                         prefix, s->pid_file);
985
986         if (s->bus_name)
987                 fprintf(f,
988                         "%sBusName: %s\n"
989                         "%sBus Name Good: %s\n",
990                         prefix, s->bus_name,
991                         prefix, yes_no(s->bus_name_good));
992
993         exec_context_dump(&s->exec_context, f, prefix);
994
995         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
996
997                 if (!s->exec_command[c])
998                         continue;
999
1000                 fprintf(f, "%s-> %s:\n",
1001                         prefix, service_exec_command_to_string(c));
1002
1003                 exec_command_dump_list(s->exec_command[c], f, prefix2);
1004         }
1005
1006         if (s->sysv_path)
1007                 fprintf(f,
1008                         "%sSysV Init Script Path: %s\n"
1009                         "%sSysV Init Script has LSB Header: %s\n",
1010                         prefix, s->sysv_path,
1011                         prefix, yes_no(s->sysv_has_lsb));
1012
1013         if (s->sysv_start_priority >= 0)
1014                 fprintf(f,
1015                         "%sSysVStartPriority: %i\n"
1016                         "%sSysVEnabled: %s\n",
1017                         prefix, s->sysv_start_priority,
1018                         prefix, yes_no(s->sysv_enabled));
1019
1020         if (s->sysv_runlevels)
1021                 fprintf(f, "%sSysVRunLevels: %s\n",
1022                         prefix, s->sysv_runlevels);
1023
1024         if (s->status_text)
1025                 fprintf(f, "%sStatus Text: %s\n",
1026                         prefix, s->status_text);
1027
1028         free(p2);
1029 }
1030
1031 static int service_load_pid_file(Service *s) {
1032         char *k;
1033         int r;
1034         pid_t pid;
1035
1036         assert(s);
1037
1038         if (s->main_pid_known)
1039                 return 0;
1040
1041         assert(s->main_pid <= 0);
1042
1043         if (!s->pid_file)
1044                 return -ENOENT;
1045
1046         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1047                 return r;
1048
1049         r = parse_pid(k, &pid);
1050         free(k);
1051
1052         if (r < 0)
1053                 return r;
1054
1055         if (kill(pid, 0) < 0 && errno != EPERM) {
1056                 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1057                             (unsigned long) pid, s->pid_file);
1058                 return -ESRCH;
1059         }
1060
1061         if ((r = service_set_main_pid(s, pid)) < 0)
1062                 return r;
1063
1064         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1065                 /* FIXME: we need to do something here */
1066                 return r;
1067
1068         return 0;
1069 }
1070
1071 static int service_get_sockets(Service *s, Set **_set) {
1072         Set *set;
1073         Iterator i;
1074         char *t;
1075         int r;
1076
1077         assert(s);
1078         assert(_set);
1079
1080         if (s->socket_fd >= 0)
1081                 return 0;
1082
1083         /* Collects all Socket objects that belong to this
1084          * service. Note that a service might have multiple sockets
1085          * via multiple names. */
1086
1087         if (!(set = set_new(NULL, NULL)))
1088                 return -ENOMEM;
1089
1090         SET_FOREACH(t, s->meta.names, i) {
1091                 char *k;
1092                 Unit *p;
1093
1094                 /* Look for all socket objects that go by any of our
1095                  * units and collect their fds */
1096
1097                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1098                         r = -ENOMEM;
1099                         goto fail;
1100                 }
1101
1102                 p = manager_get_unit(s->meta.manager, k);
1103                 free(k);
1104
1105                 if (!p)
1106                         continue;
1107
1108                 if ((r = set_put(set, p)) < 0)
1109                         goto fail;
1110         }
1111
1112         *_set = set;
1113         return 0;
1114
1115 fail:
1116         set_free(set);
1117         return r;
1118 }
1119
1120 static int service_notify_sockets_dead(Service *s) {
1121         Iterator i;
1122         Set *set;
1123         Socket *sock;
1124         int r;
1125
1126         assert(s);
1127
1128         if (s->socket_fd >= 0)
1129                 return 0;
1130
1131         /* Notifies all our sockets when we die */
1132         if ((r = service_get_sockets(s, &set)) < 0)
1133                 return r;
1134
1135         SET_FOREACH(sock, set, i)
1136                 socket_notify_service_dead(sock);
1137
1138         set_free(set);
1139
1140         return 0;
1141 }
1142
1143 static void service_set_state(Service *s, ServiceState state) {
1144         ServiceState old_state;
1145         assert(s);
1146
1147         old_state = s->state;
1148         s->state = state;
1149
1150         if (state != SERVICE_START_PRE &&
1151             state != SERVICE_START &&
1152             state != SERVICE_START_POST &&
1153             state != SERVICE_RELOAD &&
1154             state != SERVICE_STOP &&
1155             state != SERVICE_STOP_SIGTERM &&
1156             state != SERVICE_STOP_SIGKILL &&
1157             state != SERVICE_STOP_POST &&
1158             state != SERVICE_FINAL_SIGTERM &&
1159             state != SERVICE_FINAL_SIGKILL &&
1160             state != SERVICE_AUTO_RESTART)
1161                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1162
1163         if (state != SERVICE_START &&
1164             state != SERVICE_START_POST &&
1165             state != SERVICE_RUNNING &&
1166             state != SERVICE_RELOAD &&
1167             state != SERVICE_STOP &&
1168             state != SERVICE_STOP_SIGTERM &&
1169             state != SERVICE_STOP_SIGKILL)
1170                 service_unwatch_main_pid(s);
1171
1172         if (state != SERVICE_START_PRE &&
1173             state != SERVICE_START &&
1174             state != SERVICE_START_POST &&
1175             state != SERVICE_RELOAD &&
1176             state != SERVICE_STOP &&
1177             state != SERVICE_STOP_SIGTERM &&
1178             state != SERVICE_STOP_SIGKILL &&
1179             state != SERVICE_STOP_POST &&
1180             state != SERVICE_FINAL_SIGTERM &&
1181             state != SERVICE_FINAL_SIGKILL) {
1182                 service_unwatch_control_pid(s);
1183                 s->control_command = NULL;
1184                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1185         }
1186
1187         if (state == SERVICE_DEAD ||
1188             state == SERVICE_STOP ||
1189             state == SERVICE_STOP_SIGTERM ||
1190             state == SERVICE_STOP_SIGKILL ||
1191             state == SERVICE_STOP_POST ||
1192             state == SERVICE_FINAL_SIGTERM ||
1193             state == SERVICE_FINAL_SIGKILL ||
1194             state == SERVICE_FAILED ||
1195             state == SERVICE_AUTO_RESTART)
1196                 service_notify_sockets_dead(s);
1197
1198         if (state != SERVICE_START_PRE &&
1199             state != SERVICE_START &&
1200             state != SERVICE_START_POST &&
1201             state != SERVICE_RUNNING &&
1202             state != SERVICE_RELOAD &&
1203             state != SERVICE_STOP &&
1204             state != SERVICE_STOP_SIGTERM &&
1205             state != SERVICE_STOP_SIGKILL &&
1206             state != SERVICE_STOP_POST &&
1207             state != SERVICE_FINAL_SIGTERM &&
1208             state != SERVICE_FINAL_SIGKILL &&
1209             !(state == SERVICE_DEAD && s->meta.job)) {
1210                 service_close_socket_fd(s);
1211                 service_connection_unref(s);
1212         }
1213
1214         /* For the inactive states unit_notify() will trim the cgroup,
1215          * but for exit we have to do that ourselves... */
1216         if (state == SERVICE_EXITED)
1217                 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1218
1219         if (old_state != state)
1220                 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1221
1222         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1223 }
1224
1225 static int service_coldplug(Unit *u) {
1226         Service *s = SERVICE(u);
1227         int r;
1228
1229         assert(s);
1230         assert(s->state == SERVICE_DEAD);
1231
1232         if (s->deserialized_state != s->state) {
1233
1234                 if (s->deserialized_state == SERVICE_START_PRE ||
1235                     s->deserialized_state == SERVICE_START ||
1236                     s->deserialized_state == SERVICE_START_POST ||
1237                     s->deserialized_state == SERVICE_RELOAD ||
1238                     s->deserialized_state == SERVICE_STOP ||
1239                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1240                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1241                     s->deserialized_state == SERVICE_STOP_POST ||
1242                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1243                     s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1244                     s->deserialized_state == SERVICE_AUTO_RESTART) {
1245
1246                         if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1247                                 usec_t k;
1248
1249                                 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1250
1251                                 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1252                                         return r;
1253                         }
1254                 }
1255
1256                 if ((s->deserialized_state == SERVICE_START &&
1257                      (s->type == SERVICE_FORKING ||
1258                       s->type == SERVICE_DBUS ||
1259                       s->type == SERVICE_ONESHOT ||
1260                       s->type == SERVICE_NOTIFY)) ||
1261                     s->deserialized_state == SERVICE_START_POST ||
1262                     s->deserialized_state == SERVICE_RUNNING ||
1263                     s->deserialized_state == SERVICE_RELOAD ||
1264                     s->deserialized_state == SERVICE_STOP ||
1265                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1266                     s->deserialized_state == SERVICE_STOP_SIGKILL)
1267                         if (s->main_pid > 0)
1268                                 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1269                                         return r;
1270
1271                 if (s->deserialized_state == SERVICE_START_PRE ||
1272                     s->deserialized_state == SERVICE_START ||
1273                     s->deserialized_state == SERVICE_START_POST ||
1274                     s->deserialized_state == SERVICE_RELOAD ||
1275                     s->deserialized_state == SERVICE_STOP ||
1276                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1277                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1278                     s->deserialized_state == SERVICE_STOP_POST ||
1279                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1280                     s->deserialized_state == SERVICE_FINAL_SIGKILL)
1281                         if (s->control_pid > 0)
1282                                 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1283                                         return r;
1284
1285                 service_set_state(s, s->deserialized_state);
1286         }
1287
1288         return 0;
1289 }
1290
1291 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1292         Iterator i;
1293         int r;
1294         int *rfds = NULL;
1295         unsigned rn_fds = 0;
1296         Set *set;
1297         Socket *sock;
1298
1299         assert(s);
1300         assert(fds);
1301         assert(n_fds);
1302
1303         if (s->socket_fd >= 0)
1304                 return 0;
1305
1306         if ((r = service_get_sockets(s, &set)) < 0)
1307                 return r;
1308
1309         SET_FOREACH(sock, set, i) {
1310                 int *cfds;
1311                 unsigned cn_fds;
1312
1313                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1314                         goto fail;
1315
1316                 if (!cfds)
1317                         continue;
1318
1319                 if (!rfds) {
1320                         rfds = cfds;
1321                         rn_fds = cn_fds;
1322                 } else {
1323                         int *t;
1324
1325                         if (!(t = new(int, rn_fds+cn_fds))) {
1326                                 free(cfds);
1327                                 r = -ENOMEM;
1328                                 goto fail;
1329                         }
1330
1331                         memcpy(t, rfds, rn_fds);
1332                         memcpy(t+rn_fds, cfds, cn_fds);
1333                         free(rfds);
1334                         free(cfds);
1335
1336                         rfds = t;
1337                         rn_fds = rn_fds+cn_fds;
1338                 }
1339         }
1340
1341         *fds = rfds;
1342         *n_fds = rn_fds;
1343
1344         set_free(set);
1345
1346         return 0;
1347
1348 fail:
1349         set_free(set);
1350         free(rfds);
1351
1352         return r;
1353 }
1354
1355 static int service_spawn(
1356                 Service *s,
1357                 ExecCommand *c,
1358                 bool timeout,
1359                 bool pass_fds,
1360                 bool apply_permissions,
1361                 bool apply_chroot,
1362                 bool apply_tty_stdin,
1363                 bool set_notify_socket,
1364                 pid_t *_pid) {
1365
1366         pid_t pid;
1367         int r;
1368         int *fds = NULL, *fdsbuf = NULL;
1369         unsigned n_fds = 0, n_env = 0;
1370         char **argv = NULL, **final_env = NULL, **our_env = NULL;
1371
1372         assert(s);
1373         assert(c);
1374         assert(_pid);
1375
1376         if (pass_fds ||
1377             s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1378             s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1379             s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1380
1381                 if (s->socket_fd >= 0) {
1382                         fds = &s->socket_fd;
1383                         n_fds = 1;
1384                 } else {
1385                         if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1386                                 goto fail;
1387
1388                         fds = fdsbuf;
1389                 }
1390         }
1391
1392         if (timeout && s->timeout_usec) {
1393                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1394                         goto fail;
1395         } else
1396                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1397
1398         if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1399                 r = -ENOMEM;
1400                 goto fail;
1401         }
1402
1403         if (!(our_env = new0(char*, 3))) {
1404                 r = -ENOMEM;
1405                 goto fail;
1406         }
1407
1408         if (set_notify_socket)
1409                 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1410                         r = -ENOMEM;
1411                         goto fail;
1412                 }
1413
1414         if (s->main_pid > 0)
1415                 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1416                         r = -ENOMEM;
1417                         goto fail;
1418                 }
1419
1420         if (!(final_env = strv_env_merge(2,
1421                                          s->meta.manager->environment,
1422                                          our_env,
1423                                          NULL))) {
1424                 r = -ENOMEM;
1425                 goto fail;
1426         }
1427
1428         r = exec_spawn(c,
1429                        argv,
1430                        &s->exec_context,
1431                        fds, n_fds,
1432                        final_env,
1433                        apply_permissions,
1434                        apply_chroot,
1435                        apply_tty_stdin,
1436                        s->meta.manager->confirm_spawn,
1437                        s->meta.cgroup_bondings,
1438                        &pid);
1439
1440         if (r < 0)
1441                 goto fail;
1442
1443
1444         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1445                 /* FIXME: we need to do something here */
1446                 goto fail;
1447
1448         free(fdsbuf);
1449         strv_free(argv);
1450         strv_free(our_env);
1451         strv_free(final_env);
1452
1453         *_pid = pid;
1454
1455         return 0;
1456
1457 fail:
1458         free(fdsbuf);
1459         strv_free(argv);
1460         strv_free(our_env);
1461         strv_free(final_env);
1462
1463         if (timeout)
1464                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1465
1466         return r;
1467 }
1468
1469 static int main_pid_good(Service *s) {
1470         assert(s);
1471
1472         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1473          * don't know */
1474
1475         /* If we know the pid file, then lets just check if it is
1476          * still valid */
1477         if (s->main_pid_known)
1478                 return s->main_pid > 0;
1479
1480         /* We don't know the pid */
1481         return -EAGAIN;
1482 }
1483
1484 static int control_pid_good(Service *s) {
1485         assert(s);
1486
1487         return s->control_pid > 0;
1488 }
1489
1490 static int cgroup_good(Service *s) {
1491         int r;
1492
1493         assert(s);
1494
1495         if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1496                 return r;
1497
1498         return !r;
1499 }
1500
1501 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1502         int r;
1503         assert(s);
1504
1505         if (!success)
1506                 s->failure = true;
1507
1508         if (allow_restart &&
1509             !s->forbid_restart &&
1510             (s->restart == SERVICE_RESTART_ALWAYS ||
1511              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1512
1513                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1514                         goto fail;
1515
1516                 service_set_state(s, SERVICE_AUTO_RESTART);
1517         } else
1518                 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1519
1520         s->forbid_restart = false;
1521
1522         return;
1523
1524 fail:
1525         log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1526         service_enter_dead(s, false, false);
1527 }
1528
1529 static void service_enter_signal(Service *s, ServiceState state, bool success);
1530
1531 static void service_enter_stop_post(Service *s, bool success) {
1532         int r;
1533         assert(s);
1534
1535         if (!success)
1536                 s->failure = true;
1537
1538         service_unwatch_control_pid(s);
1539
1540         s->control_command_id = SERVICE_EXEC_STOP_POST;
1541         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1542                 if ((r = service_spawn(s,
1543                                        s->control_command,
1544                                        true,
1545                                        false,
1546                                        !s->permissions_start_only,
1547                                        !s->root_directory_start_only,
1548                                        true,
1549                                        false,
1550                                        &s->control_pid)) < 0)
1551                         goto fail;
1552
1553
1554                 service_set_state(s, SERVICE_STOP_POST);
1555         } else
1556                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1557
1558         return;
1559
1560 fail:
1561         log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1562         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1563 }
1564
1565 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1566         int r;
1567         Set *pid_set = NULL;
1568         bool wait_for_exit = false;
1569
1570         assert(s);
1571
1572         if (!success)
1573                 s->failure = true;
1574
1575         if (s->exec_context.kill_mode != KILL_NONE) {
1576                 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1577
1578                 if (s->main_pid > 0) {
1579                         if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1580                                  -s->main_pid :
1581                                  s->main_pid, sig) < 0 && errno != ESRCH)
1582
1583                                 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1584                         else
1585                                 wait_for_exit = true;
1586                 }
1587
1588                 if (s->control_pid > 0) {
1589                         if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1590                                  -s->control_pid :
1591                                  s->control_pid, sig) < 0 && errno != ESRCH)
1592
1593                                 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1594                         else
1595                                 wait_for_exit = true;
1596                 }
1597
1598                 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1599
1600                         if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1601                                 r = -ENOMEM;
1602                                 goto fail;
1603                         }
1604
1605                         /* Exclude the main/control pids from being killed via the cgroup */
1606                         if (s->main_pid > 0)
1607                                 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1608                                         goto fail;
1609
1610                         if (s->control_pid > 0)
1611                                 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1612                                         goto fail;
1613
1614                         if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1615                                 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1616                                         log_warning("Failed to kill control group: %s", strerror(-r));
1617                         } else if (r > 0)
1618                                 wait_for_exit = true;
1619
1620                         set_free(pid_set);
1621                 }
1622         }
1623
1624         if (wait_for_exit) {
1625                 if (s->timeout_usec > 0)
1626                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1627                                 goto fail;
1628
1629                 service_set_state(s, state);
1630         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1631                 service_enter_stop_post(s, true);
1632         else
1633                 service_enter_dead(s, true, true);
1634
1635         return;
1636
1637 fail:
1638         log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1639
1640         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1641                 service_enter_stop_post(s, false);
1642         else
1643                 service_enter_dead(s, false, true);
1644
1645         if (pid_set)
1646                 set_free(pid_set);
1647 }
1648
1649 static void service_enter_stop(Service *s, bool success) {
1650         int r;
1651
1652         assert(s);
1653
1654         if (!success)
1655                 s->failure = true;
1656
1657         service_unwatch_control_pid(s);
1658
1659         s->control_command_id = SERVICE_EXEC_STOP;
1660         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1661                 if ((r = service_spawn(s,
1662                                        s->control_command,
1663                                        true,
1664                                        false,
1665                                        !s->permissions_start_only,
1666                                        !s->root_directory_start_only,
1667                                        false,
1668                                        false,
1669                                        &s->control_pid)) < 0)
1670                         goto fail;
1671
1672                 service_set_state(s, SERVICE_STOP);
1673         } else
1674                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1675
1676         return;
1677
1678 fail:
1679         log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1680         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1681 }
1682
1683 static void service_enter_running(Service *s, bool success) {
1684         int main_pid_ok, cgroup_ok;
1685         assert(s);
1686
1687         if (!success)
1688                 s->failure = true;
1689
1690         main_pid_ok = main_pid_good(s);
1691         cgroup_ok = cgroup_good(s);
1692
1693         if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1694             (s->bus_name_good || s->type != SERVICE_DBUS))
1695                 service_set_state(s, SERVICE_RUNNING);
1696         else if (s->remain_after_exit)
1697                 service_set_state(s, SERVICE_EXITED);
1698         else
1699                 service_enter_stop(s, true);
1700 }
1701
1702 static void service_enter_start_post(Service *s) {
1703         int r;
1704         assert(s);
1705
1706         service_unwatch_control_pid(s);
1707
1708         s->control_command_id = SERVICE_EXEC_START_POST;
1709         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1710                 if ((r = service_spawn(s,
1711                                        s->control_command,
1712                                        true,
1713                                        false,
1714                                        !s->permissions_start_only,
1715                                        !s->root_directory_start_only,
1716                                        false,
1717                                        false,
1718                                        &s->control_pid)) < 0)
1719                         goto fail;
1720
1721                 service_set_state(s, SERVICE_START_POST);
1722         } else
1723                 service_enter_running(s, true);
1724
1725         return;
1726
1727 fail:
1728         log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1729         service_enter_stop(s, false);
1730 }
1731
1732 static void service_enter_start(Service *s) {
1733         pid_t pid;
1734         int r;
1735
1736         assert(s);
1737
1738         assert(s->exec_command[SERVICE_EXEC_START]);
1739         assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1740
1741         if (s->type == SERVICE_FORKING)
1742                 service_unwatch_control_pid(s);
1743         else
1744                 service_unwatch_main_pid(s);
1745
1746         s->control_command_id = SERVICE_EXEC_START;
1747         s->control_command = s->exec_command[SERVICE_EXEC_START];
1748
1749         if ((r = service_spawn(s,
1750                                s->control_command,
1751                                s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1752                                true,
1753                                true,
1754                                true,
1755                                true,
1756                                s->notify_access != NOTIFY_NONE,
1757                                &pid)) < 0)
1758                 goto fail;
1759
1760         if (s->type == SERVICE_SIMPLE) {
1761                 /* For simple services we immediately start
1762                  * the START_POST binaries. */
1763
1764                 service_set_main_pid(s, pid);
1765                 service_enter_start_post(s);
1766
1767         } else  if (s->type == SERVICE_FORKING) {
1768
1769                 /* For forking services we wait until the start
1770                  * process exited. */
1771
1772                 s->control_pid = pid;
1773                 service_set_state(s, SERVICE_START);
1774
1775         } else if (s->type == SERVICE_ONESHOT ||
1776                    s->type == SERVICE_DBUS ||
1777                    s->type == SERVICE_NOTIFY) {
1778
1779                 /* For oneshot services we wait until the start
1780                  * process exited, too, but it is our main process. */
1781
1782                 /* For D-Bus services we know the main pid right away,
1783                  * but wait for the bus name to appear on the
1784                  * bus. Notify services are similar. */
1785
1786                 service_set_main_pid(s, pid);
1787                 service_set_state(s, SERVICE_START);
1788         } else
1789                 assert_not_reached("Unknown service type");
1790
1791         return;
1792
1793 fail:
1794         log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1795         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1796 }
1797
1798 static void service_enter_start_pre(Service *s) {
1799         int r;
1800
1801         assert(s);
1802
1803         service_unwatch_control_pid(s);
1804
1805         s->control_command_id = SERVICE_EXEC_START_PRE;
1806         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1807                 if ((r = service_spawn(s,
1808                                        s->control_command,
1809                                        true,
1810                                        false,
1811                                        !s->permissions_start_only,
1812                                        !s->root_directory_start_only,
1813                                        true,
1814                                        false,
1815                                        &s->control_pid)) < 0)
1816                         goto fail;
1817
1818                 service_set_state(s, SERVICE_START_PRE);
1819         } else
1820                 service_enter_start(s);
1821
1822         return;
1823
1824 fail:
1825         log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1826         service_enter_dead(s, false, true);
1827 }
1828
1829 static void service_enter_restart(Service *s) {
1830         int r;
1831         DBusError error;
1832
1833         assert(s);
1834         dbus_error_init(&error);
1835
1836         service_enter_dead(s, true, false);
1837
1838         if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
1839                 goto fail;
1840
1841         log_debug("%s scheduled restart job.", s->meta.id);
1842         return;
1843
1844 fail:
1845         log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1846         service_enter_dead(s, false, false);
1847
1848         dbus_error_free(&error);
1849 }
1850
1851 static void service_enter_reload(Service *s) {
1852         int r;
1853
1854         assert(s);
1855
1856         service_unwatch_control_pid(s);
1857
1858         s->control_command_id = SERVICE_EXEC_RELOAD;
1859         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1860                 if ((r = service_spawn(s,
1861                                        s->control_command,
1862                                        true,
1863                                        false,
1864                                        !s->permissions_start_only,
1865                                        !s->root_directory_start_only,
1866                                        false,
1867                                        false,
1868                                        &s->control_pid)) < 0)
1869                         goto fail;
1870
1871                 service_set_state(s, SERVICE_RELOAD);
1872         } else
1873                 service_enter_running(s, true);
1874
1875         return;
1876
1877 fail:
1878         log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1879         service_enter_stop(s, false);
1880 }
1881
1882 static void service_run_next_control(Service *s, bool success) {
1883         int r;
1884
1885         assert(s);
1886         assert(s->control_command);
1887         assert(s->control_command->command_next);
1888
1889         if (!success)
1890                 s->failure = true;
1891
1892         assert(s->control_command_id != SERVICE_EXEC_START);
1893
1894         s->control_command = s->control_command->command_next;
1895         service_unwatch_control_pid(s);
1896
1897         if ((r = service_spawn(s,
1898                                s->control_command,
1899                                true,
1900                                false,
1901                                !s->permissions_start_only,
1902                                !s->root_directory_start_only,
1903                                s->control_command_id == SERVICE_EXEC_START_PRE ||
1904                                s->control_command_id == SERVICE_EXEC_STOP_POST,
1905                                false,
1906                                &s->control_pid)) < 0)
1907                 goto fail;
1908
1909         return;
1910
1911 fail:
1912         log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
1913
1914         if (s->state == SERVICE_START_PRE)
1915                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1916         else if (s->state == SERVICE_STOP)
1917                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1918         else if (s->state == SERVICE_STOP_POST)
1919                 service_enter_dead(s, false, true);
1920         else
1921                 service_enter_stop(s, false);
1922 }
1923
1924 static void service_run_next_main(Service *s, bool success) {
1925         pid_t pid;
1926         int r;
1927
1928         assert(s);
1929         assert(s->control_command);
1930         assert(s->control_command->command_next);
1931
1932         if (!success)
1933                 s->failure = true;
1934
1935         assert(s->control_command_id == SERVICE_EXEC_START);
1936         assert(s->type == SERVICE_ONESHOT);
1937
1938         s->control_command = s->control_command->command_next;
1939         service_unwatch_main_pid(s);
1940
1941         if ((r = service_spawn(s,
1942                                s->control_command,
1943                                false,
1944                                true,
1945                                true,
1946                                true,
1947                                true,
1948                                s->notify_access != NOTIFY_NONE,
1949                                &pid)) < 0)
1950                 goto fail;
1951
1952         service_set_main_pid(s, pid);
1953
1954         return;
1955
1956 fail:
1957         log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
1958         service_enter_stop(s, false);
1959 }
1960
1961 static int service_start(Unit *u) {
1962         Service *s = SERVICE(u);
1963
1964         assert(s);
1965
1966         /* We cannot fulfill this request right now, try again later
1967          * please! */
1968         if (s->state == SERVICE_STOP ||
1969             s->state == SERVICE_STOP_SIGTERM ||
1970             s->state == SERVICE_STOP_SIGKILL ||
1971             s->state == SERVICE_STOP_POST ||
1972             s->state == SERVICE_FINAL_SIGTERM ||
1973             s->state == SERVICE_FINAL_SIGKILL)
1974                 return -EAGAIN;
1975
1976         /* Already on it! */
1977         if (s->state == SERVICE_START_PRE ||
1978             s->state == SERVICE_START ||
1979             s->state == SERVICE_START_POST)
1980                 return 0;
1981
1982         assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
1983
1984         /* Make sure we don't enter a busy loop of some kind. */
1985         if (!ratelimit_test(&s->ratelimit)) {
1986                 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1987                 return -ECANCELED;
1988         }
1989
1990         if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1991              s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1992              s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1993             s->socket_fd < 0) {
1994                 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1995                 return -EINVAL;
1996         }
1997
1998         s->failure = false;
1999         s->main_pid_known = false;
2000         s->forbid_restart = false;
2001
2002         service_enter_start_pre(s);
2003         return 0;
2004 }
2005
2006 static int service_stop(Unit *u) {
2007         Service *s = SERVICE(u);
2008
2009         assert(s);
2010
2011         /* This is a user request, so don't do restarts on this
2012          * shutdown. */
2013         s->forbid_restart = true;
2014
2015         /* Already on it */
2016         if (s->state == SERVICE_STOP ||
2017             s->state == SERVICE_STOP_SIGTERM ||
2018             s->state == SERVICE_STOP_SIGKILL ||
2019             s->state == SERVICE_STOP_POST ||
2020             s->state == SERVICE_FINAL_SIGTERM ||
2021             s->state == SERVICE_FINAL_SIGKILL)
2022                 return 0;
2023
2024         /* Don't allow a restart */
2025         if (s->state == SERVICE_AUTO_RESTART) {
2026                 service_set_state(s, SERVICE_DEAD);
2027                 return 0;
2028         }
2029
2030         /* If there's already something running we go directly into
2031          * kill mode. */
2032         if (s->state == SERVICE_START_PRE ||
2033             s->state == SERVICE_START ||
2034             s->state == SERVICE_START_POST ||
2035             s->state == SERVICE_RELOAD) {
2036                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2037                 return 0;
2038         }
2039
2040         assert(s->state == SERVICE_RUNNING ||
2041                s->state == SERVICE_EXITED);
2042
2043         service_enter_stop(s, true);
2044         return 0;
2045 }
2046
2047 static int service_reload(Unit *u) {
2048         Service *s = SERVICE(u);
2049
2050         assert(s);
2051
2052         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2053
2054         service_enter_reload(s);
2055         return 0;
2056 }
2057
2058 static bool service_can_reload(Unit *u) {
2059         Service *s = SERVICE(u);
2060
2061         assert(s);
2062
2063         return !!s->exec_command[SERVICE_EXEC_RELOAD];
2064 }
2065
2066 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2067         Service *s = SERVICE(u);
2068
2069         assert(u);
2070         assert(f);
2071         assert(fds);
2072
2073         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2074         unit_serialize_item(u, f, "failure", yes_no(s->failure));
2075
2076         if (s->control_pid > 0)
2077                 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2078
2079         if (s->main_pid_known && s->main_pid > 0)
2080                 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2081
2082         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2083
2084         if (s->status_text)
2085                 unit_serialize_item(u, f, "status-text", s->status_text);
2086
2087         /* There's a minor uncleanliness here: if there are multiple
2088          * commands attached here, we will start from the first one
2089          * again */
2090         if (s->control_command_id >= 0)
2091                 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2092
2093         if (s->socket_fd >= 0) {
2094                 int copy;
2095
2096                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2097                         return copy;
2098
2099                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2100         }
2101
2102         if (s->main_exec_status.pid > 0) {
2103                 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2104
2105                 if (s->main_exec_status.start_timestamp.realtime > 0) {
2106                         unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2107                                                    "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2108
2109                         unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2110                                                    "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2111                 }
2112
2113                 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2114                         unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2115                                                    "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2116                         unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2117                                                    "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2118
2119                         unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2120                         unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2121                 }
2122         }
2123
2124         return 0;
2125 }
2126
2127 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2128         Service *s = SERVICE(u);
2129
2130         assert(u);
2131         assert(key);
2132         assert(value);
2133         assert(fds);
2134
2135         if (streq(key, "state")) {
2136                 ServiceState state;
2137
2138                 if ((state = service_state_from_string(value)) < 0)
2139                         log_debug("Failed to parse state value %s", value);
2140                 else
2141                         s->deserialized_state = state;
2142         } else if (streq(key, "failure")) {
2143                 int b;
2144
2145                 if ((b = parse_boolean(value)) < 0)
2146                         log_debug("Failed to parse failure value %s", value);
2147                 else
2148                         s->failure = b || s->failure;
2149         } else if (streq(key, "control-pid")) {
2150                 pid_t pid;
2151
2152                 if (parse_pid(value, &pid) < 0)
2153                         log_debug("Failed to parse control-pid value %s", value);
2154                 else
2155                         s->control_pid = pid;
2156         } else if (streq(key, "main-pid")) {
2157                 pid_t pid;
2158
2159                 if (parse_pid(value, &pid) < 0)
2160                         log_debug("Failed to parse main-pid value %s", value);
2161                 else
2162                         service_set_main_pid(s, (pid_t) pid);
2163         } else if (streq(key, "main-pid-known")) {
2164                 int b;
2165
2166                 if ((b = parse_boolean(value)) < 0)
2167                         log_debug("Failed to parse main-pid-known value %s", value);
2168                 else
2169                         s->main_pid_known = b;
2170         } else if (streq(key, "status-text")) {
2171                 char *t;
2172
2173                 if ((t = strdup(value))) {
2174                         free(s->status_text);
2175                         s->status_text = t;
2176                 }
2177
2178         } else if (streq(key, "control-command")) {
2179                 ServiceExecCommand id;
2180
2181                 if ((id = service_exec_command_from_string(value)) < 0)
2182                         log_debug("Failed to parse exec-command value %s", value);
2183                 else {
2184                         s->control_command_id = id;
2185                         s->control_command = s->exec_command[id];
2186                 }
2187         } else if (streq(key, "socket-fd")) {
2188                 int fd;
2189
2190                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2191                         log_debug("Failed to parse socket-fd value %s", value);
2192                 else {
2193
2194                         if (s->socket_fd >= 0)
2195                                 close_nointr_nofail(s->socket_fd);
2196                         s->socket_fd = fdset_remove(fds, fd);
2197                 }
2198         } else if (streq(key, "main-exec-status-pid")) {
2199                 pid_t pid;
2200
2201                 if (parse_pid(value, &pid) < 0)
2202                         log_debug("Failed to parse main-exec-status-pid value %s", value);
2203                 else
2204                         s->main_exec_status.pid = pid;
2205         } else if (streq(key, "main-exec-status-code")) {
2206                 int i;
2207
2208                 if (safe_atoi(value, &i) < 0)
2209                         log_debug("Failed to parse main-exec-status-code value %s", value);
2210                 else
2211                         s->main_exec_status.code = i;
2212         } else if (streq(key, "main-exec-status-status")) {
2213                 int i;
2214
2215                 if (safe_atoi(value, &i) < 0)
2216                         log_debug("Failed to parse main-exec-status-status value %s", value);
2217                 else
2218                         s->main_exec_status.status = i;
2219         } else if (streq(key, "main-exec-status-start-realtime")) {
2220                 uint64_t k;
2221
2222                 if (safe_atou64(value, &k) < 0)
2223                         log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2224                 else
2225                         s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2226         } else if (streq(key, "main-exec-status-start-monotonic")) {
2227                 uint64_t k;
2228
2229                 if (safe_atou64(value, &k) < 0)
2230                         log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2231                 else
2232                         s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2233         } else if (streq(key, "main-exec-status-exit-realtime")) {
2234                 uint64_t k;
2235
2236                 if (safe_atou64(value, &k) < 0)
2237                         log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2238                 else
2239                         s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2240         } else if (streq(key, "main-exec-status-exit-monotonic")) {
2241                 uint64_t k;
2242
2243                 if (safe_atou64(value, &k) < 0)
2244                         log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2245                 else
2246                         s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2247         } else
2248                 log_debug("Unknown serialization key '%s'", key);
2249
2250         return 0;
2251 }
2252
2253 static UnitActiveState service_active_state(Unit *u) {
2254         assert(u);
2255
2256         return state_translation_table[SERVICE(u)->state];
2257 }
2258
2259 static const char *service_sub_state_to_string(Unit *u) {
2260         assert(u);
2261
2262         return service_state_to_string(SERVICE(u)->state);
2263 }
2264
2265 static bool service_check_gc(Unit *u) {
2266         Service *s = SERVICE(u);
2267
2268         assert(s);
2269
2270         return !!s->sysv_path;
2271 }
2272
2273 static bool service_check_snapshot(Unit *u) {
2274         Service *s = SERVICE(u);
2275
2276         assert(s);
2277
2278         return !s->got_socket_fd;
2279 }
2280
2281 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2282         Service *s = SERVICE(u);
2283         bool success;
2284
2285         assert(s);
2286         assert(pid >= 0);
2287
2288         if (!s->meta.fragment_path)
2289                 success = is_clean_exit_lsb(code, status);
2290         else
2291                 success = is_clean_exit(code, status);
2292
2293         if (s->main_pid == pid) {
2294
2295                 s->main_pid = 0;
2296                 exec_status_exit(&s->main_exec_status, pid, code, status);
2297
2298                 if (s->type != SERVICE_FORKING && s->control_command) {
2299                         s->control_command->exec_status = s->main_exec_status;
2300
2301                         if (s->control_command->ignore)
2302                                 success = true;
2303                 }
2304
2305                 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2306                          "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2307                 s->failure = s->failure || !success;
2308
2309                 if (s->control_command &&
2310                     s->control_command->command_next &&
2311                     success) {
2312
2313                         /* There is another command to *
2314                          * execute, so let's do that. */
2315
2316                         log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2317                         service_run_next_main(s, success);
2318
2319                 } else {
2320
2321                         /* The service exited, so the service is officially
2322                          * gone. */
2323
2324                         s->control_command = NULL;
2325                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2326
2327                         switch (s->state) {
2328
2329                         case SERVICE_START_POST:
2330                         case SERVICE_RELOAD:
2331                         case SERVICE_STOP:
2332                                 /* Need to wait until the operation is
2333                                  * done */
2334                                 break;
2335
2336                         case SERVICE_START:
2337                                 if (s->type == SERVICE_ONESHOT) {
2338                                         /* This was our main goal, so let's go on */
2339                                         if (success)
2340                                                 service_enter_start_post(s);
2341                                         else
2342                                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2343                                         break;
2344                                 } else {
2345                                         assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2346
2347                                         /* Fall through */
2348                                 }
2349
2350                         case SERVICE_RUNNING:
2351                                 service_enter_running(s, success);
2352                                 break;
2353
2354                         case SERVICE_STOP_SIGTERM:
2355                         case SERVICE_STOP_SIGKILL:
2356
2357                                 if (!control_pid_good(s))
2358                                         service_enter_stop_post(s, success);
2359
2360                                 /* If there is still a control process, wait for that first */
2361                                 break;
2362
2363                         default:
2364                                 assert_not_reached("Uh, main process died at wrong time.");
2365                         }
2366                 }
2367
2368         } else if (s->control_pid == pid) {
2369
2370                 s->control_pid = 0;
2371
2372                 if (s->control_command) {
2373                         exec_status_exit(&s->control_command->exec_status, pid, code, status);
2374
2375                         if (s->control_command->ignore)
2376                                 success = true;
2377                 }
2378
2379                log_full(success ? LOG_DEBUG : LOG_NOTICE,
2380                          "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2381                 s->failure = s->failure || !success;
2382
2383                 if (s->control_command &&
2384                     s->control_command->command_next &&
2385                     success) {
2386
2387                         /* There is another command to *
2388                          * execute, so let's do that. */
2389
2390                         log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2391                         service_run_next_control(s, success);
2392
2393                 } else {
2394                         /* No further commands for this step, so let's
2395                          * figure out what to do next */
2396
2397                         s->control_command = NULL;
2398                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2399
2400                         log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2401
2402                         switch (s->state) {
2403
2404                         case SERVICE_START_PRE:
2405                                 if (success)
2406                                         service_enter_start(s);
2407                                 else
2408                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2409                                 break;
2410
2411                         case SERVICE_START:
2412                                 assert(s->type == SERVICE_FORKING);
2413
2414                                 /* Let's try to load the pid
2415                                  * file here if we can. We
2416                                  * ignore the return value,
2417                                  * since the PID file might
2418                                  * actually be created by a
2419                                  * START_POST script */
2420
2421                                 if (success) {
2422                                         if (s->pid_file)
2423                                                 service_load_pid_file(s);
2424
2425                                         service_enter_start_post(s);
2426                                 } else
2427                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2428
2429                                 break;
2430
2431                         case SERVICE_START_POST:
2432                                 if (success && s->pid_file && !s->main_pid_known) {
2433                                         int r;
2434
2435                                         /* Hmm, let's see if we can
2436                                          * load the pid now after the
2437                                          * start-post scripts got
2438                                          * executed. */
2439
2440                                         if ((r = service_load_pid_file(s)) < 0)
2441                                                 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2442                                 }
2443
2444                                 /* Fall through */
2445
2446                         case SERVICE_RELOAD:
2447                                 if (success)
2448                                         service_enter_running(s, true);
2449                                 else
2450                                         service_enter_stop(s, false);
2451
2452                                 break;
2453
2454                         case SERVICE_STOP:
2455                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2456                                 break;
2457
2458                         case SERVICE_STOP_SIGTERM:
2459                         case SERVICE_STOP_SIGKILL:
2460                                 if (main_pid_good(s) <= 0)
2461                                         service_enter_stop_post(s, success);
2462
2463                                 /* If there is still a service
2464                                  * process around, wait until
2465                                  * that one quit, too */
2466                                 break;
2467
2468                         case SERVICE_STOP_POST:
2469                         case SERVICE_FINAL_SIGTERM:
2470                         case SERVICE_FINAL_SIGKILL:
2471                                 service_enter_dead(s, success, true);
2472                                 break;
2473
2474                         default:
2475                                 assert_not_reached("Uh, control process died at wrong time.");
2476                         }
2477                 }
2478         }
2479
2480         /* Notify clients about changed exit status */
2481         unit_add_to_dbus_queue(u);
2482 }
2483
2484 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2485         Service *s = SERVICE(u);
2486
2487         assert(s);
2488         assert(elapsed == 1);
2489
2490         assert(w == &s->timer_watch);
2491
2492         switch (s->state) {
2493
2494         case SERVICE_START_PRE:
2495         case SERVICE_START:
2496                 log_warning("%s operation timed out. Terminating.", u->meta.id);
2497                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2498                 break;
2499
2500         case SERVICE_START_POST:
2501         case SERVICE_RELOAD:
2502                 log_warning("%s operation timed out. Stopping.", u->meta.id);
2503                 service_enter_stop(s, false);
2504                 break;
2505
2506         case SERVICE_STOP:
2507                 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2508                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2509                 break;
2510
2511         case SERVICE_STOP_SIGTERM:
2512                 log_warning("%s stopping timed out. Killing.", u->meta.id);
2513                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2514                 break;
2515
2516         case SERVICE_STOP_SIGKILL:
2517                 /* Uh, wie sent a SIGKILL and it is still not gone?
2518                  * Must be something we cannot kill, so let's just be
2519                  * weirded out and continue */
2520
2521                 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2522                 service_enter_stop_post(s, false);
2523                 break;
2524
2525         case SERVICE_STOP_POST:
2526                 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2527                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2528                 break;
2529
2530         case SERVICE_FINAL_SIGTERM:
2531                 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2532                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2533                 break;
2534
2535         case SERVICE_FINAL_SIGKILL:
2536                 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2537                 service_enter_dead(s, false, true);
2538                 break;
2539
2540         case SERVICE_AUTO_RESTART:
2541                 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2542                 service_enter_restart(s);
2543                 break;
2544
2545         default:
2546                 assert_not_reached("Timeout at wrong time.");
2547         }
2548 }
2549
2550 static void service_cgroup_notify_event(Unit *u) {
2551         Service *s = SERVICE(u);
2552
2553         assert(u);
2554
2555         log_debug("%s: cgroup is empty", u->meta.id);
2556
2557         switch (s->state) {
2558
2559                 /* Waiting for SIGCHLD is usually more interesting,
2560                  * because it includes return codes/signals. Which is
2561                  * why we ignore the cgroup events for most cases,
2562                  * except when we don't know pid which to expect the
2563                  * SIGCHLD for. */
2564
2565         case SERVICE_RUNNING:
2566                 service_enter_running(s, true);
2567                 break;
2568
2569         case SERVICE_STOP_SIGTERM:
2570         case SERVICE_STOP_SIGKILL:
2571                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2572                         service_enter_stop_post(s, true);
2573
2574                 break;
2575
2576         case SERVICE_FINAL_SIGTERM:
2577         case SERVICE_FINAL_SIGKILL:
2578                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2579                         service_enter_dead(s, true, true);
2580
2581                 break;
2582
2583         default:
2584                 ;
2585         }
2586 }
2587
2588 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2589         Service *s = SERVICE(u);
2590         const char *e;
2591
2592         assert(u);
2593
2594         if (s->notify_access == NOTIFY_NONE) {
2595                 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2596                             u->meta.id, (unsigned long) pid);
2597                 return;
2598         }
2599
2600         if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2601                 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2602                             u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2603                 return;
2604         }
2605
2606         log_debug("%s: Got message", u->meta.id);
2607
2608         /* Interpret MAINPID= */
2609         if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2610             (s->state == SERVICE_START ||
2611              s->state == SERVICE_START_POST ||
2612              s->state == SERVICE_RUNNING ||
2613              s->state == SERVICE_RELOAD)) {
2614
2615                 if (parse_pid(e + 8, &pid) < 0)
2616                         log_warning("Failed to parse notification message %s", e);
2617                 else {
2618                         log_debug("%s: got %s", u->meta.id, e);
2619                         service_set_main_pid(s, pid);
2620                 }
2621         }
2622
2623         /* Interpret READY= */
2624         if (s->type == SERVICE_NOTIFY &&
2625             s->state == SERVICE_START &&
2626             strv_find(tags, "READY=1")) {
2627                 log_debug("%s: got READY=1", u->meta.id);
2628
2629                 service_enter_start_post(s);
2630         }
2631
2632         /* Interpret STATUS= */
2633         if ((e = strv_find_prefix(tags, "STATUS="))) {
2634                 char *t;
2635
2636                 if (e[7]) {
2637                         if (!(t = strdup(e+7))) {
2638                                 log_error("Failed to allocate string.");
2639                                 return;
2640                         }
2641
2642                         log_debug("%s: got %s", u->meta.id, e);
2643
2644                         free(s->status_text);
2645                         s->status_text = t;
2646                 } else {
2647                         free(s->status_text);
2648                         s->status_text = NULL;
2649                 }
2650
2651         }
2652
2653         /* Notify clients about changed status or main pid */
2654         unit_add_to_dbus_queue(u);
2655 }
2656
2657 static int service_enumerate(Manager *m) {
2658         char **p;
2659         unsigned i;
2660         DIR *d = NULL;
2661         char *path = NULL, *fpath = NULL, *name = NULL;
2662         Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2663         Unit *service;
2664         Iterator j;
2665         int r;
2666 #ifdef TARGET_ARCH
2667         Unit *previous = NULL;
2668         char *arch_daemons = NULL;
2669         char *arch_daemons_stripped = NULL;
2670         char **arch_daemons_split = NULL;
2671 #endif
2672
2673         assert(m);
2674
2675 #ifdef TARGET_ARCH
2676         if ((r = parse_env_file("/etc/rc.conf", NEWLINE,
2677                                 "DAEMONS", &arch_daemons,
2678                                 NULL)) < 0) {
2679
2680                 if (r != -ENOENT)
2681                         log_warning("Failed to read /etc/rc.conf: %s", strerror(-r));
2682
2683         } else if (arch_daemons) {
2684                 if (!(arch_daemons_stripped = strchr(arch_daemons, '(')))
2685                         arch_daemons_stripped = arch_daemons;
2686                 else
2687                         arch_daemons_stripped++; /* strip start paren */
2688
2689                 arch_daemons_stripped[strcspn(arch_daemons_stripped, ")")] = 0; /* strip end paren */
2690
2691                 if (!(arch_daemons_split = strv_split_quoted(arch_daemons_stripped))) {
2692                         r = -ENOMEM;
2693                         goto finish;
2694                 }
2695
2696                 STRV_FOREACH(p, arch_daemons_split) {
2697
2698                         free(name);
2699
2700                         if (**p == '!') /* daemons prefixed with ! are disabled, so ignore them */
2701                                 continue;
2702
2703                         if (!(name = sysv_translate_name(*p))) {
2704                                 r = -ENOMEM;
2705                                 goto finish;
2706                         }
2707
2708                         if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2709                                 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2710                                 continue;
2711                         }
2712
2713                         if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, "multi-user.target", NULL, true)) < 0)
2714                                 goto finish;
2715
2716                         if (previous)
2717                                 if ((r = unit_add_dependency(service, UNIT_AFTER, previous, true)) < 0)
2718                                         goto finish;
2719
2720                         if (**p != '@') /* daemons prefixed with @ can be started in the background */
2721                                 previous = service;
2722                 }
2723         }
2724 #endif
2725
2726         zero(runlevel_services);
2727
2728         STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2729                 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2730                         struct dirent *de;
2731
2732                         free(path);
2733                         path = NULL;
2734                         if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2735                                 r = -ENOMEM;
2736                                 goto finish;
2737                         }
2738
2739                         if (d)
2740                                 closedir(d);
2741
2742                         if (!(d = opendir(path))) {
2743                                 if (errno != ENOENT)
2744                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
2745
2746                                 continue;
2747                         }
2748
2749                         while ((de = readdir(d))) {
2750                                 int a, b;
2751
2752                                 if (ignore_file(de->d_name))
2753                                         continue;
2754
2755                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2756                                         continue;
2757
2758                                 if (strlen(de->d_name) < 4)
2759                                         continue;
2760
2761                                 a = undecchar(de->d_name[1]);
2762                                 b = undecchar(de->d_name[2]);
2763
2764                                 if (a < 0 || b < 0)
2765                                         continue;
2766
2767                                 free(fpath);
2768                                 fpath = NULL;
2769                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2770                                         r = -ENOMEM;
2771                                         goto finish;
2772                                 }
2773
2774                                 if (access(fpath, X_OK) < 0) {
2775
2776                                         if (errno != ENOENT)
2777                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2778
2779                                         continue;
2780                                 }
2781
2782                                 free(name);
2783                                 if (!(name = sysv_translate_name(de->d_name + 3))) {
2784                                         r = -ENOMEM;
2785                                         goto finish;
2786                                 }
2787
2788                                 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2789                                         log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2790                                         continue;
2791                                 }
2792
2793                                 if (de->d_name[0] == 'S')  {
2794
2795                                         if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
2796                                                 SERVICE(service)->sysv_start_priority =
2797                                                         MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2798
2799                                                 SERVICE(service)->sysv_enabled = true;
2800                                         }
2801
2802                                         if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
2803                                                 goto finish;
2804
2805                                         if ((r = set_put(runlevel_services[i], service)) < 0)
2806                                                 goto finish;
2807
2808                                 } else if (de->d_name[0] == 'K' &&
2809                                            (rcnd_table[i].type == RUNLEVEL_DOWN ||
2810                                             rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2811
2812                                         if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
2813                                                 goto finish;
2814
2815                                         if ((r = set_put(shutdown_services, service)) < 0)
2816                                                 goto finish;
2817                                 }
2818                         }
2819                 }
2820
2821         /* Now we loaded all stubs and are aware of the lowest
2822         start-up priority for all services, not let's actually load
2823         the services, this will also tell us which services are
2824         actually native now */
2825         manager_dispatch_load_queue(m);
2826
2827         /* If this is a native service, rely on native ways to pull in
2828          * a service, don't pull it in via sysv rcN.d links. */
2829         for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
2830                 SET_FOREACH(service, runlevel_services[i], j) {
2831                         service = unit_follow_merge(service);
2832
2833                         if (service->meta.fragment_path)
2834                                 continue;
2835
2836                         if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2837                                 goto finish;
2838                 }
2839
2840         /* We honour K links only for halt/reboot. For the normal
2841          * runlevels we assume the stop jobs will be implicitly added
2842          * by the core logic. Also, we don't really distuingish here
2843          * between the runlevels 0 and 6 and just add them to the
2844          * special shutdown target. On SUSE the boot.d/ runlevel is
2845          * also used for shutdown, so we add links for that too to the
2846          * shutdown target.*/
2847         SET_FOREACH(service, shutdown_services, j) {
2848                 service = unit_follow_merge(service);
2849
2850                 if (service->meta.fragment_path)
2851                         continue;
2852
2853                 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2854                         goto finish;
2855         }
2856
2857         r = 0;
2858
2859 finish:
2860         free(path);
2861         free(fpath);
2862         free(name);
2863 #ifdef TARGET_ARCH
2864         free(arch_daemons);
2865         free(arch_daemons_split);
2866 #endif
2867
2868         for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
2869                 set_free(runlevel_services[i]);
2870         set_free(shutdown_services);
2871
2872         if (d)
2873                 closedir(d);
2874
2875         return r;
2876 }
2877
2878 static void service_bus_name_owner_change(
2879                 Unit *u,
2880                 const char *name,
2881                 const char *old_owner,
2882                 const char *new_owner) {
2883
2884         Service *s = SERVICE(u);
2885
2886         assert(s);
2887         assert(name);
2888
2889         assert(streq(s->bus_name, name));
2890         assert(old_owner || new_owner);
2891
2892         if (old_owner && new_owner)
2893                 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2894         else if (old_owner)
2895                 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2896         else
2897                 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2898
2899         s->bus_name_good = !!new_owner;
2900
2901         if (s->type == SERVICE_DBUS) {
2902
2903                 /* service_enter_running() will figure out what to
2904                  * do */
2905                 if (s->state == SERVICE_RUNNING)
2906                         service_enter_running(s, true);
2907                 else if (s->state == SERVICE_START && new_owner)
2908                         service_enter_start_post(s);
2909
2910         } else if (new_owner &&
2911                    s->main_pid <= 0 &&
2912                    (s->state == SERVICE_START ||
2913                     s->state == SERVICE_START_POST ||
2914                     s->state == SERVICE_RUNNING ||
2915                     s->state == SERVICE_RELOAD)) {
2916
2917                 /* Try to acquire PID from bus service */
2918                 log_debug("Trying to acquire PID from D-Bus name...");
2919
2920                 bus_query_pid(u->meta.manager, name);
2921         }
2922 }
2923
2924 static void service_bus_query_pid_done(
2925                 Unit *u,
2926                 const char *name,
2927                 pid_t pid) {
2928
2929         Service *s = SERVICE(u);
2930
2931         assert(s);
2932         assert(name);
2933
2934         log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2935
2936         if (s->main_pid <= 0 &&
2937             (s->state == SERVICE_START ||
2938              s->state == SERVICE_START_POST ||
2939              s->state == SERVICE_RUNNING ||
2940              s->state == SERVICE_RELOAD))
2941                 service_set_main_pid(s, pid);
2942 }
2943
2944 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2945         assert(s);
2946         assert(fd >= 0);
2947
2948         /* This is called by the socket code when instantiating a new
2949          * service for a stream socket and the socket needs to be
2950          * configured. */
2951
2952         if (s->meta.load_state != UNIT_LOADED)
2953                 return -EINVAL;
2954
2955         if (s->socket_fd >= 0)
2956                 return -EBUSY;
2957
2958         if (s->state != SERVICE_DEAD)
2959                 return -EAGAIN;
2960
2961         s->socket_fd = fd;
2962         s->got_socket_fd = true;
2963         s->socket = sock;
2964
2965         return 0;
2966 }
2967
2968 static void service_reset_failed(Unit *u) {
2969         Service *s = SERVICE(u);
2970
2971         assert(s);
2972
2973         if (s->state == SERVICE_FAILED)
2974                 service_set_state(s, SERVICE_DEAD);
2975
2976         s->failure = false;
2977 }
2978
2979 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2980         [SERVICE_DEAD] = "dead",
2981         [SERVICE_START_PRE] = "start-pre",
2982         [SERVICE_START] = "start",
2983         [SERVICE_START_POST] = "start-post",
2984         [SERVICE_RUNNING] = "running",
2985         [SERVICE_EXITED] = "exited",
2986         [SERVICE_RELOAD] = "reload",
2987         [SERVICE_STOP] = "stop",
2988         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2989         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2990         [SERVICE_STOP_POST] = "stop-post",
2991         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2992         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2993         [SERVICE_FAILED] = "failed",
2994         [SERVICE_AUTO_RESTART] = "auto-restart",
2995 };
2996
2997 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2998
2999 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3000         [SERVICE_ONCE] = "once",
3001         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
3002         [SERVICE_RESTART_ALWAYS] = "restart-always",
3003 };
3004
3005 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3006
3007 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3008         [SERVICE_SIMPLE] = "simple",
3009         [SERVICE_FORKING] = "forking",
3010         [SERVICE_ONESHOT] = "oneshot",
3011         [SERVICE_DBUS] = "dbus",
3012         [SERVICE_NOTIFY] = "notify"
3013 };
3014
3015 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3016
3017 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3018         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3019         [SERVICE_EXEC_START] = "ExecStart",
3020         [SERVICE_EXEC_START_POST] = "ExecStartPost",
3021         [SERVICE_EXEC_RELOAD] = "ExecReload",
3022         [SERVICE_EXEC_STOP] = "ExecStop",
3023         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3024 };
3025
3026 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3027
3028 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3029         [NOTIFY_NONE] = "none",
3030         [NOTIFY_MAIN] = "main",
3031         [NOTIFY_ALL] = "all"
3032 };
3033
3034 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3035
3036 const UnitVTable service_vtable = {
3037         .suffix = ".service",
3038         .show_status = true,
3039
3040         .init = service_init,
3041         .done = service_done,
3042         .load = service_load,
3043
3044         .coldplug = service_coldplug,
3045
3046         .dump = service_dump,
3047
3048         .start = service_start,
3049         .stop = service_stop,
3050         .reload = service_reload,
3051
3052         .can_reload = service_can_reload,
3053
3054         .serialize = service_serialize,
3055         .deserialize_item = service_deserialize_item,
3056
3057         .active_state = service_active_state,
3058         .sub_state_to_string = service_sub_state_to_string,
3059
3060         .check_gc = service_check_gc,
3061         .check_snapshot = service_check_snapshot,
3062
3063         .sigchld_event = service_sigchld_event,
3064         .timer_event = service_timer_event,
3065
3066         .reset_failed = service_reset_failed,
3067
3068         .cgroup_notify_empty = service_cgroup_notify_event,
3069         .notify_message = service_notify_message,
3070
3071         .bus_name_owner_change = service_bus_name_owner_change,
3072         .bus_query_pid_done = service_bus_query_pid_done,
3073
3074         .bus_interface = "org.freedesktop.systemd1.Service",
3075         .bus_message_handler = bus_service_message_handler,
3076         .bus_invalidating_properties =  bus_service_invalidating_properties,
3077
3078         .enumerate = service_enumerate
3079 };