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