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