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