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