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