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