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