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