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