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