chiark / gitweb /
core: sysvcompat - $network should be equivalent to network-online, rather than netwo...
[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 #include <linux/reboot.h>
28 #include <sys/syscall.h>
29
30 #include "manager.h"
31 #include "unit.h"
32 #include "service.h"
33 #include "load-fragment.h"
34 #include "load-dropin.h"
35 #include "log.h"
36 #include "strv.h"
37 #include "unit-name.h"
38 #include "unit-printf.h"
39 #include "dbus-service.h"
40 #include "special.h"
41 #include "exit-status.h"
42 #include "def.h"
43 #include "path-util.h"
44 #include "util.h"
45 #include "utf8.h"
46 #include "env-util.h"
47 #include "fileio.h"
48 #include "bus-error.h"
49 #include "bus-util.h"
50
51 #ifdef HAVE_SYSV_COMPAT
52
53 #define DEFAULT_SYSV_TIMEOUT_USEC (5*USEC_PER_MINUTE)
54
55 typedef enum RunlevelType {
56         RUNLEVEL_UP,
57         RUNLEVEL_DOWN
58 } RunlevelType;
59
60 static const struct {
61         const char *path;
62         const char *target;
63         const RunlevelType type;
64 } rcnd_table[] = {
65         /* Standard SysV runlevels for start-up */
66         { "rc1.d",  SPECIAL_RESCUE_TARGET,    RUNLEVEL_UP },
67         { "rc2.d",  SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
68         { "rc3.d",  SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
69         { "rc4.d",  SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
70         { "rc5.d",  SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
71
72         /* Standard SysV runlevels for shutdown */
73         { "rc0.d",  SPECIAL_POWEROFF_TARGET,  RUNLEVEL_DOWN },
74         { "rc6.d",  SPECIAL_REBOOT_TARGET,    RUNLEVEL_DOWN }
75
76         /* Note that the order here matters, as we read the
77            directories in this order, and we want to make sure that
78            sysv_start_priority is known when we first load the
79            unit. And that value we only know from S links. Hence
80            UP must be read before DOWN */
81 };
82
83 #define RUNLEVELS_UP "12345"
84 #endif
85
86 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
87         [SERVICE_DEAD] = UNIT_INACTIVE,
88         [SERVICE_START_PRE] = UNIT_ACTIVATING,
89         [SERVICE_START] = UNIT_ACTIVATING,
90         [SERVICE_START_POST] = UNIT_ACTIVATING,
91         [SERVICE_RUNNING] = UNIT_ACTIVE,
92         [SERVICE_EXITED] = UNIT_ACTIVE,
93         [SERVICE_RELOAD] = UNIT_RELOADING,
94         [SERVICE_STOP] = UNIT_DEACTIVATING,
95         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
96         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
97         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
98         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
99         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
100         [SERVICE_FAILED] = UNIT_FAILED,
101         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
102 };
103
104 /* For Type=idle we never want to delay any other jobs, hence we
105  * consider idle jobs active as soon as we start working on them */
106 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
107         [SERVICE_DEAD] = UNIT_INACTIVE,
108         [SERVICE_START_PRE] = UNIT_ACTIVE,
109         [SERVICE_START] = UNIT_ACTIVE,
110         [SERVICE_START_POST] = UNIT_ACTIVE,
111         [SERVICE_RUNNING] = UNIT_ACTIVE,
112         [SERVICE_EXITED] = UNIT_ACTIVE,
113         [SERVICE_RELOAD] = UNIT_RELOADING,
114         [SERVICE_STOP] = UNIT_DEACTIVATING,
115         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
116         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
117         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
118         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
119         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
120         [SERVICE_FAILED] = UNIT_FAILED,
121         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
122 };
123
124 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
125 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
126 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
127
128 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
129
130 static void service_init(Unit *u) {
131         Service *s = SERVICE(u);
132
133         assert(u);
134         assert(u->load_state == UNIT_STUB);
135
136         s->timeout_start_usec = u->manager->default_timeout_start_usec;
137         s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
138         s->restart_usec = u->manager->default_restart_usec;
139         s->type = _SERVICE_TYPE_INVALID;
140
141 #ifdef HAVE_SYSV_COMPAT
142         s->sysv_start_priority = -1;
143         s->sysv_start_priority_from_rcnd = -1;
144 #endif
145         s->socket_fd = -1;
146         s->guess_main_pid = true;
147
148         RATELIMIT_INIT(s->start_limit, u->manager->default_start_limit_interval, u->manager->default_start_limit_burst);
149
150         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
151 }
152
153 static void service_unwatch_control_pid(Service *s) {
154         assert(s);
155
156         if (s->control_pid <= 0)
157                 return;
158
159         unit_unwatch_pid(UNIT(s), s->control_pid);
160         s->control_pid = 0;
161 }
162
163 static void service_unwatch_main_pid(Service *s) {
164         assert(s);
165
166         if (s->main_pid <= 0)
167                 return;
168
169         unit_unwatch_pid(UNIT(s), s->main_pid);
170         s->main_pid = 0;
171 }
172
173 static void service_unwatch_pid_file(Service *s) {
174         if (!s->pid_file_pathspec)
175                 return;
176
177         log_debug_unit(UNIT(s)->id, "Stopping watch for %s's PID file %s",
178                        UNIT(s)->id, s->pid_file_pathspec->path);
179         path_spec_unwatch(s->pid_file_pathspec);
180         path_spec_done(s->pid_file_pathspec);
181         free(s->pid_file_pathspec);
182         s->pid_file_pathspec = NULL;
183 }
184
185 static int service_set_main_pid(Service *s, pid_t pid) {
186         pid_t ppid;
187
188         assert(s);
189
190         if (pid <= 1)
191                 return -EINVAL;
192
193         if (pid == getpid())
194                 return -EINVAL;
195
196         if (s->main_pid == pid && s->main_pid_known)
197                 return 0;
198
199         if (s->main_pid != pid) {
200                 service_unwatch_main_pid(s);
201                 exec_status_start(&s->main_exec_status, pid);
202         }
203
204         s->main_pid = pid;
205         s->main_pid_known = true;
206
207         if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
208                 log_warning_unit(UNIT(s)->id,
209                                  "%s: Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.",
210                                  UNIT(s)->id, pid);
211
212                 s->main_pid_alien = true;
213         } else
214                 s->main_pid_alien = false;
215
216         return 0;
217 }
218
219 static void service_close_socket_fd(Service *s) {
220         assert(s);
221
222         if (s->socket_fd < 0)
223                 return;
224
225         s->socket_fd = safe_close(s->socket_fd);
226 }
227
228 static void service_connection_unref(Service *s) {
229         assert(s);
230
231         if (!UNIT_ISSET(s->accept_socket))
232                 return;
233
234         socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
235         unit_ref_unset(&s->accept_socket);
236 }
237
238 static void service_stop_watchdog(Service *s) {
239         assert(s);
240
241         s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
242         s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
243 }
244
245 static void service_start_watchdog(Service *s) {
246         int r;
247
248         assert(s);
249
250         if (s->watchdog_usec <= 0)
251                 return;
252
253         if (s->watchdog_event_source) {
254                 r = sd_event_source_set_time(s->watchdog_event_source, s->watchdog_timestamp.monotonic + s->watchdog_usec);
255                 if (r < 0) {
256                         log_warning_unit(UNIT(s)->id, "%s failed to reset watchdog timer: %s", UNIT(s)->id, strerror(-r));
257                         return;
258                 }
259
260                 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
261         } else {
262                 r = sd_event_add_time(
263                                 UNIT(s)->manager->event,
264                                 &s->watchdog_event_source,
265                                 CLOCK_MONOTONIC,
266                                 s->watchdog_timestamp.monotonic + s->watchdog_usec, 0,
267                                 service_dispatch_watchdog, s);
268                 if (r < 0) {
269                         log_warning_unit(UNIT(s)->id, "%s failed to add watchdog timer: %s", UNIT(s)->id, strerror(-r));
270                         return;
271                 }
272
273                 /* Let's process everything else which might be a sign
274                  * of living before we consider a service died. */
275                 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
276         }
277
278         if (r < 0)
279                 log_warning_unit(UNIT(s)->id, "%s failed to install watchdog timer: %s", UNIT(s)->id, strerror(-r));
280 }
281
282 static void service_reset_watchdog(Service *s) {
283         assert(s);
284
285         dual_timestamp_get(&s->watchdog_timestamp);
286         service_start_watchdog(s);
287 }
288
289 static void service_done(Unit *u) {
290         Service *s = SERVICE(u);
291
292         assert(s);
293
294         free(s->pid_file);
295         s->pid_file = NULL;
296
297 #ifdef HAVE_SYSV_COMPAT
298         free(s->sysv_runlevels);
299         s->sysv_runlevels = NULL;
300 #endif
301
302         free(s->status_text);
303         s->status_text = NULL;
304
305         free(s->reboot_arg);
306         s->reboot_arg = NULL;
307
308         s->exec_runtime = exec_runtime_unref(s->exec_runtime);
309         exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
310         s->control_command = NULL;
311         s->main_command = NULL;
312
313         set_free(s->restart_ignore_status.code);
314         s->restart_ignore_status.code = NULL;
315         set_free(s->restart_ignore_status.signal);
316         s->restart_ignore_status.signal = NULL;
317
318         set_free(s->success_status.code);
319         s->success_status.code = NULL;
320         set_free(s->success_status.signal);
321         s->success_status.signal = NULL;
322
323         /* This will leak a process, but at least no memory or any of
324          * our resources */
325         service_unwatch_main_pid(s);
326         service_unwatch_control_pid(s);
327         service_unwatch_pid_file(s);
328
329         if (s->bus_name)  {
330                 unit_unwatch_bus_name(u, s->bus_name);
331                 free(s->bus_name);
332                 s->bus_name = NULL;
333         }
334
335         service_close_socket_fd(s);
336         service_connection_unref(s);
337
338         unit_ref_unset(&s->accept_socket);
339
340         service_stop_watchdog(s);
341
342         s->timer_event_source = sd_event_source_unref(s->timer_event_source);
343 }
344
345 static int service_arm_timer(Service *s, usec_t usec) {
346         int r;
347
348         assert(s);
349
350         if (s->timer_event_source) {
351                 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
352                 if (r < 0)
353                         return r;
354
355                 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
356         }
357
358         return sd_event_add_time(
359                         UNIT(s)->manager->event,
360                         &s->timer_event_source,
361                         CLOCK_MONOTONIC,
362                         now(CLOCK_MONOTONIC) + usec, 0,
363                         service_dispatch_timer, s);
364 }
365
366 #ifdef HAVE_SYSV_COMPAT
367 static char *sysv_translate_name(const char *name) {
368         char *r;
369
370         r = new(char, strlen(name) + strlen(".service") + 1);
371         if (!r)
372                 return NULL;
373
374         if (endswith(name, ".sh"))
375                 /* Drop .sh suffix */
376                 strcpy(stpcpy(r, name) - 3, ".service");
377         else
378                 /* Normal init script name */
379                 strcpy(stpcpy(r, name), ".service");
380
381         return r;
382 }
383
384 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
385
386         /* We silently ignore the $ prefix here. According to the LSB
387          * spec it simply indicates whether something is a
388          * standardized name or a distribution-specific one. Since we
389          * just follow what already exists and do not introduce new
390          * uses or names we don't care who introduced a new name. */
391
392         static const char * const table[] = {
393                 /* LSB defined facilities */
394                 "local_fs",             NULL,
395                 "network",              SPECIAL_NETWORK_ONLINE_TARGET,
396                 "named",                SPECIAL_NSS_LOOKUP_TARGET,
397                 "portmap",              SPECIAL_RPCBIND_TARGET,
398                 "remote_fs",            SPECIAL_REMOTE_FS_TARGET,
399                 "syslog",               NULL,
400                 "time",                 SPECIAL_TIME_SYNC_TARGET,
401         };
402
403         unsigned i;
404         char *r;
405         const char *n;
406
407         assert(name);
408         assert(_r);
409
410         n = *name == '$' ? name + 1 : name;
411
412         for (i = 0; i < ELEMENTSOF(table); i += 2) {
413
414                 if (!streq(table[i], n))
415                         continue;
416
417                 if (!table[i+1])
418                         return 0;
419
420                 r = strdup(table[i+1]);
421                 if (!r)
422                         return log_oom();
423
424                 goto finish;
425         }
426
427         /* If we don't know this name, fallback heuristics to figure
428          * out whether something is a target or a service alias. */
429
430         if (*name == '$') {
431                 if (!unit_prefix_is_valid(n))
432                         return -EINVAL;
433
434                 /* Facilities starting with $ are most likely targets */
435                 r = unit_name_build(n, NULL, ".target");
436         } else if (filename && streq(name, filename))
437                 /* Names equaling the file name of the services are redundant */
438                 return 0;
439         else
440                 /* Everything else we assume to be normal service names */
441                 r = sysv_translate_name(n);
442
443         if (!r)
444                 return -ENOMEM;
445
446 finish:
447         *_r = r;
448
449         return 1;
450 }
451
452 static int sysv_fix_order(Service *s) {
453         Unit *other;
454         int r;
455
456         assert(s);
457
458         if (s->sysv_start_priority < 0)
459                 return 0;
460
461         /* For each pair of services where at least one lacks a LSB
462          * header, we use the start priority value to order things. */
463
464         LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
465                 Service *t;
466                 UnitDependency d;
467                 bool special_s, special_t;
468
469                 t = SERVICE(other);
470
471                 if (s == t)
472                         continue;
473
474                 if (UNIT(t)->load_state != UNIT_LOADED)
475                         continue;
476
477                 if (t->sysv_start_priority < 0)
478                         continue;
479
480                 /* If both units have modern headers we don't care
481                  * about the priorities */
482                 if ((UNIT(s)->fragment_path || s->sysv_has_lsb) &&
483                     (UNIT(t)->fragment_path || t->sysv_has_lsb))
484                         continue;
485
486                 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
487                 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
488
489                 if (special_t && !special_s)
490                         d = UNIT_AFTER;
491                 else if (special_s && !special_t)
492                         d = UNIT_BEFORE;
493                 else if (t->sysv_start_priority < s->sysv_start_priority)
494                         d = UNIT_AFTER;
495                 else if (t->sysv_start_priority > s->sysv_start_priority)
496                         d = UNIT_BEFORE;
497                 else
498                         continue;
499
500                 /* FIXME: Maybe we should compare the name here lexicographically? */
501
502                 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
503                         return r;
504         }
505
506         return 0;
507 }
508
509 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
510         ExecCommand *c;
511
512         if (!(c = new0(ExecCommand, 1)))
513                 return NULL;
514
515         if (!(c->path = strdup(path))) {
516                 free(c);
517                 return NULL;
518         }
519
520         if (!(c->argv = strv_new(path, arg1, NULL))) {
521                 free(c->path);
522                 free(c);
523                 return NULL;
524         }
525
526         return c;
527 }
528
529 static int sysv_exec_commands(Service *s, const bool supports_reload) {
530         ExecCommand *c;
531
532         assert(s);
533         assert(s->is_sysv);
534         assert(UNIT(s)->source_path);
535
536         c = exec_command_new(UNIT(s)->source_path, "start");
537         if (!c)
538                 return -ENOMEM;
539         exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
540
541         c = exec_command_new(UNIT(s)->source_path, "stop");
542         if (!c)
543                 return -ENOMEM;
544         exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
545
546         if (supports_reload) {
547                 c = exec_command_new(UNIT(s)->source_path, "reload");
548                 if (!c)
549                         return -ENOMEM;
550                 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
551         }
552
553         return 0;
554 }
555
556 static bool usage_contains_reload(const char *line) {
557         return (strcasestr(line, "{reload|") ||
558                 strcasestr(line, "{reload}") ||
559                 strcasestr(line, "{reload\"") ||
560                 strcasestr(line, "|reload|") ||
561                 strcasestr(line, "|reload}") ||
562                 strcasestr(line, "|reload\""));
563 }
564
565 static int service_load_sysv_path(Service *s, const char *path) {
566         FILE *f;
567         Unit *u;
568         unsigned line = 0;
569         int r;
570         enum {
571                 NORMAL,
572                 DESCRIPTION,
573                 LSB,
574                 LSB_DESCRIPTION,
575                 USAGE_CONTINUATION
576         } state = NORMAL;
577         char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
578         struct stat st;
579         bool supports_reload = false;
580
581         assert(s);
582         assert(path);
583
584         u = UNIT(s);
585
586         f = fopen(path, "re");
587         if (!f) {
588                 r = errno == ENOENT ? 0 : -errno;
589                 goto finish;
590         }
591
592         if (fstat(fileno(f), &st) < 0) {
593                 r = -errno;
594                 goto finish;
595         }
596
597         free(u->source_path);
598         u->source_path = strdup(path);
599         if (!u->source_path) {
600                 r = -ENOMEM;
601                 goto finish;
602         }
603         u->source_mtime = timespec_load(&st.st_mtim);
604
605         if (null_or_empty(&st)) {
606                 u->load_state = UNIT_MASKED;
607                 r = 0;
608                 goto finish;
609         }
610
611         s->is_sysv = true;
612
613         while (!feof(f)) {
614                 char l[LINE_MAX], *t;
615
616                 if (!fgets(l, sizeof(l), f)) {
617                         if (feof(f))
618                                 break;
619
620                         r = -errno;
621                         log_error_unit(u->id,
622                                        "Failed to read configuration file '%s': %s",
623                                        path, strerror(-r));
624                         goto finish;
625                 }
626
627                 line++;
628
629                 t = strstrip(l);
630                 if (*t != '#') {
631                         /* Try to figure out whether this init script supports
632                          * the reload operation. This heuristic looks for
633                          * "Usage" lines which include the reload option. */
634                         if ( state == USAGE_CONTINUATION ||
635                             (state == NORMAL && strcasestr(t, "usage"))) {
636                                 if (usage_contains_reload(t)) {
637                                         supports_reload = true;
638                                         state = NORMAL;
639                                 } else if (t[strlen(t)-1] == '\\')
640                                         state = USAGE_CONTINUATION;
641                                 else
642                                         state = NORMAL;
643                         }
644
645                         continue;
646                 }
647
648                 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
649                         state = LSB;
650                         s->sysv_has_lsb = true;
651                         continue;
652                 }
653
654                 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
655                         state = NORMAL;
656                         continue;
657                 }
658
659                 t++;
660                 t += strspn(t, WHITESPACE);
661
662                 if (state == NORMAL) {
663
664                         /* Try to parse Red Hat style chkconfig headers */
665
666                         if (startswith_no_case(t, "chkconfig:")) {
667                                 int start_priority;
668                                 char runlevels[16], *k;
669
670                                 state = NORMAL;
671
672                                 if (sscanf(t+10, "%15s %i %*i", runlevels, &start_priority) != 2) {
673                                         log_warning_unit(u->id, "[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
674                                         continue;
675                                 }
676
677                                 /* A start priority gathered from the
678                                  * symlink farms is preferred over the
679                                  * data from the LSB header. */
680                                 if (start_priority < 0 || start_priority > 99)
681                                         log_warning_unit(u->id, "[%s:%u] Start priority out of range. Ignoring.", path, line);
682                                 else
683                                         log_debug_unit(u->id, "[%s:%u] Ignoring start priority set in the chkconfig file.", path, line);
684
685                                 char_array_0(runlevels);
686                                 k = delete_chars(runlevels, WHITESPACE "-");
687                                 if (k[0]) {
688                                         char *d;
689
690                                         d = strdup(k);
691                                         if (!d) {
692                                                 r = -ENOMEM;
693                                                 goto finish;
694                                         }
695
696                                         free(s->sysv_runlevels);
697                                         s->sysv_runlevels = d;
698                                 }
699
700                         } else if (startswith_no_case(t, "description:")) {
701
702                                 size_t k = strlen(t);
703                                 char *d;
704                                 const char *j;
705
706                                 if (t[k-1] == '\\') {
707                                         state = DESCRIPTION;
708                                         t[k-1] = 0;
709                                 }
710
711                                 if ((j = strstrip(t+12)) && *j) {
712                                         if (!(d = strdup(j))) {
713                                                 r = -ENOMEM;
714                                                 goto finish;
715                                         }
716                                 } else
717                                         d = NULL;
718
719                                 free(chkconfig_description);
720                                 chkconfig_description = d;
721
722                         } else if (startswith_no_case(t, "pidfile:")) {
723
724                                 char *fn;
725
726                                 state = NORMAL;
727
728                                 fn = strstrip(t+8);
729                                 if (!path_is_absolute(fn)) {
730                                         log_warning_unit(u->id,
731                                                          "[%s:%u] PID file not absolute. Ignoring.",
732                                                          path, line);
733                                         continue;
734                                 }
735
736                                 if (!(fn = strdup(fn))) {
737                                         r = -ENOMEM;
738                                         goto finish;
739                                 }
740
741                                 free(s->pid_file);
742                                 s->pid_file = fn;
743                         }
744
745                 } else if (state == DESCRIPTION) {
746
747                         /* Try to parse Red Hat style description
748                          * continuation */
749
750                         size_t k = strlen(t);
751                         char *j;
752
753                         if (t[k-1] == '\\')
754                                 t[k-1] = 0;
755                         else
756                                 state = NORMAL;
757
758                         if ((j = strstrip(t)) && *j) {
759                                 char *d = NULL;
760
761                                 if (chkconfig_description)
762                                         d = strjoin(chkconfig_description, " ", j, NULL);
763                                 else
764                                         d = strdup(j);
765
766                                 if (!d) {
767                                         r = -ENOMEM;
768                                         goto finish;
769                                 }
770
771                                 free(chkconfig_description);
772                                 chkconfig_description = d;
773                         }
774
775                 } else if (state == LSB || state == LSB_DESCRIPTION) {
776
777                         if (startswith_no_case(t, "Provides:")) {
778                                 char *i, *w;
779                                 size_t z;
780
781                                 state = LSB;
782
783                                 FOREACH_WORD_QUOTED(w, z, t+9, i) {
784                                         char *n, *m;
785
786                                         if (!(n = strndup(w, z))) {
787                                                 r = -ENOMEM;
788                                                 goto finish;
789                                         }
790
791                                         r = sysv_translate_facility(n, basename(path), &m);
792                                         free(n);
793
794                                         if (r < 0)
795                                                 goto finish;
796
797                                         if (r == 0)
798                                                 continue;
799
800                                         if (unit_name_to_type(m) == UNIT_SERVICE)
801                                                 r = unit_merge_by_name(u, m);
802                                         else
803                                                 /* NB: SysV targets
804                                                  * which are provided
805                                                  * by a service are
806                                                  * pulled in by the
807                                                  * services, as an
808                                                  * indication that the
809                                                  * generic service is
810                                                  * now available. This
811                                                  * is strictly
812                                                  * one-way. The
813                                                  * targets do NOT pull
814                                                  * in the SysV
815                                                  * services! */
816                                                 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
817
818                                         if (r < 0)
819                                                 log_error_unit(u->id,
820                                                                "[%s:%u] Failed to add LSB Provides name %s, ignoring: %s",
821                                                                path, line, m, strerror(-r));
822
823                                         free(m);
824                                 }
825
826                         } else if (startswith_no_case(t, "Required-Start:") ||
827                                    startswith_no_case(t, "Should-Start:") ||
828                                    startswith_no_case(t, "X-Start-Before:") ||
829                                    startswith_no_case(t, "X-Start-After:")) {
830                                 char *i, *w;
831                                 size_t z;
832
833                                 state = LSB;
834
835                                 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
836                                         char *n, *m;
837
838                                         if (!(n = strndup(w, z))) {
839                                                 r = -ENOMEM;
840                                                 goto finish;
841                                         }
842
843                                         r = sysv_translate_facility(n, basename(path), &m);
844                                         if (r < 0) {
845                                                 log_error_unit(u->id,
846                                                                "[%s:%u] Failed to translate LSB dependency %s, ignoring: %s",
847                                                                path, line, n, strerror(-r));
848                                                 free(n);
849                                                 continue;
850                                         }
851
852                                         free(n);
853
854                                         if (r == 0)
855                                                 continue;
856
857                                         if (streq(m, SPECIAL_NETWORK_ONLINE_TARGET) && !startswith_no_case(t, "X-Start-Before:"))
858                                                 /* the network-online target is special, as it needs to be actively pulled in */
859                                                 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, m, NULL, true);
860                                         else
861                                                 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
862
863                                         if (r < 0)
864                                                 log_error_unit(u->id, "[%s:%u] Failed to add dependency on %s, ignoring: %s",
865                                                                path, line, m, strerror(-r));
866
867                                         free(m);
868                                 }
869                         } else if (startswith_no_case(t, "Default-Start:")) {
870                                 char *k, *d;
871
872                                 state = LSB;
873
874                                 k = delete_chars(t+14, WHITESPACE "-");
875
876                                 if (k[0] != 0) {
877                                         if (!(d = strdup(k))) {
878                                                 r = -ENOMEM;
879                                                 goto finish;
880                                         }
881
882                                         free(s->sysv_runlevels);
883                                         s->sysv_runlevels = d;
884                                 }
885
886                         } else if (startswith_no_case(t, "Description:")) {
887                                 char *d, *j;
888
889                                 state = LSB_DESCRIPTION;
890
891                                 if ((j = strstrip(t+12)) && *j) {
892                                         if (!(d = strdup(j))) {
893                                                 r = -ENOMEM;
894                                                 goto finish;
895                                         }
896                                 } else
897                                         d = NULL;
898
899                                 free(long_description);
900                                 long_description = d;
901
902                         } else if (startswith_no_case(t, "Short-Description:")) {
903                                 char *d, *j;
904
905                                 state = LSB;
906
907                                 if ((j = strstrip(t+18)) && *j) {
908                                         if (!(d = strdup(j))) {
909                                                 r = -ENOMEM;
910                                                 goto finish;
911                                         }
912                                 } else
913                                         d = NULL;
914
915                                 free(short_description);
916                                 short_description = d;
917
918                         } else if (state == LSB_DESCRIPTION) {
919
920                                 if (startswith(l, "#\t") || startswith(l, "#  ")) {
921                                         char *j;
922
923                                         if ((j = strstrip(t)) && *j) {
924                                                 char *d = NULL;
925
926                                                 if (long_description)
927                                                         d = strjoin(long_description, " ", t, NULL);
928                                                 else
929                                                         d = strdup(j);
930
931                                                 if (!d) {
932                                                         r = -ENOMEM;
933                                                         goto finish;
934                                                 }
935
936                                                 free(long_description);
937                                                 long_description = d;
938                                         }
939
940                                 } else
941                                         state = LSB;
942                         }
943                 }
944         }
945
946         if ((r = sysv_exec_commands(s, supports_reload)) < 0)
947                 goto finish;
948
949         if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
950                 /* If there a runlevels configured for this service
951                  * but none of the standard ones, then we assume this
952                  * is some special kind of service (which might be
953                  * needed for early boot) and don't create any links
954                  * to it. */
955
956                 UNIT(s)->default_dependencies = false;
957
958                 /* Don't timeout special services during boot (like fsck) */
959                 s->timeout_start_usec = 0;
960                 s->timeout_stop_usec = 0;
961         } else {
962                 s->timeout_start_usec = DEFAULT_SYSV_TIMEOUT_USEC;
963                 s->timeout_stop_usec = DEFAULT_SYSV_TIMEOUT_USEC;
964         }
965
966         /* Special setting for all SysV services */
967         s->type = SERVICE_FORKING;
968         s->remain_after_exit = !s->pid_file;
969         s->guess_main_pid = false;
970         s->restart = SERVICE_RESTART_NO;
971         s->exec_context.ignore_sigpipe = false;
972         s->kill_context.kill_mode = KILL_PROCESS;
973
974         /* We use the long description only if
975          * no short description is set. */
976
977         if (short_description)
978                 description = short_description;
979         else if (chkconfig_description)
980                 description = chkconfig_description;
981         else if (long_description)
982                 description = long_description;
983         else
984                 description = NULL;
985
986         if (description) {
987                 char *d;
988
989                 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
990                         r = -ENOMEM;
991                         goto finish;
992                 }
993
994                 u->description = d;
995         }
996
997         /* Initialize the start priority from what has been set in the
998          * /etc/rcN.d/ hierarchies if we load the unit file as SysV
999          * init script. */
1000         if (s->sysv_start_priority_from_rcnd >= 0)
1001                 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
1002
1003         u->load_state = UNIT_LOADED;
1004         r = 0;
1005
1006 finish:
1007
1008         if (f)
1009                 fclose(f);
1010
1011         free(short_description);
1012         free(long_description);
1013         free(chkconfig_description);
1014
1015         return r;
1016 }
1017
1018 static int service_load_sysv_name(Service *s, const char *name) {
1019         char **p;
1020
1021         assert(s);
1022         assert(name);
1023
1024         /* For SysV services we strip the *.sh suffixes. */
1025         if (endswith(name, ".sh.service"))
1026                 return -ENOENT;
1027
1028         STRV_FOREACH(p, UNIT(s)->manager->lookup_paths.sysvinit_path) {
1029                 char *path;
1030                 int r;
1031
1032                 path = strjoin(*p, "/", name, NULL);
1033                 if (!path)
1034                         return -ENOMEM;
1035
1036                 assert(endswith(path, ".service"));
1037                 path[strlen(path)-8] = 0;
1038
1039                 r = service_load_sysv_path(s, path);
1040
1041                 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
1042                         /* Try *.sh source'able init scripts */
1043                         strcat(path, ".sh");
1044                         r = service_load_sysv_path(s, path);
1045                 }
1046                 free(path);
1047
1048                 if (r < 0)
1049                         return r;
1050
1051                 if (UNIT(s)->load_state != UNIT_STUB)
1052                         break;
1053         }
1054
1055         return 0;
1056 }
1057
1058 static int service_load_sysv(Service *s) {
1059         const char *t;
1060         Iterator i;
1061         int r;
1062
1063         assert(s);
1064
1065         /* Load service data from SysV init scripts, preferably with
1066          * LSB headers ... */
1067
1068         if (strv_isempty(UNIT(s)->manager->lookup_paths.sysvinit_path))
1069                 return 0;
1070
1071         if ((t = UNIT(s)->id))
1072                 if ((r = service_load_sysv_name(s, t)) < 0)
1073                         return r;
1074
1075         if (UNIT(s)->load_state == UNIT_STUB)
1076                 SET_FOREACH(t, UNIT(s)->names, i) {
1077                         if (t == UNIT(s)->id)
1078                                 continue;
1079
1080                         if ((r = service_load_sysv_name(s, t)) < 0)
1081                                 return r;
1082
1083                         if (UNIT(s)->load_state != UNIT_STUB)
1084                                 break;
1085                 }
1086
1087         return 0;
1088 }
1089 #endif
1090
1091 static int service_verify(Service *s) {
1092         assert(s);
1093
1094         if (UNIT(s)->load_state != UNIT_LOADED)
1095                 return 0;
1096
1097         if (!s->exec_command[SERVICE_EXEC_START]) {
1098                 log_error_unit(UNIT(s)->id, "%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
1099                 return -EINVAL;
1100         }
1101
1102         if (s->type != SERVICE_ONESHOT &&
1103             s->exec_command[SERVICE_EXEC_START]->command_next) {
1104                 log_error_unit(UNIT(s)->id, "%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1105                 return -EINVAL;
1106         }
1107
1108         if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
1109                 log_error_unit(UNIT(s)->id, "%s has Restart setting other than no, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1110                 return -EINVAL;
1111         }
1112
1113         if (s->type == SERVICE_DBUS && !s->bus_name) {
1114                 log_error_unit(UNIT(s)->id, "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
1115                 return -EINVAL;
1116         }
1117
1118         if (s->bus_name && s->type != SERVICE_DBUS)
1119                 log_warning_unit(UNIT(s)->id, "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
1120
1121         if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
1122                 log_error_unit(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.", UNIT(s)->id);
1123                 return -EINVAL;
1124         }
1125
1126         return 0;
1127 }
1128
1129 static int service_add_default_dependencies(Service *s) {
1130         int r;
1131
1132         assert(s);
1133
1134         /* Add a number of automatic dependencies useful for the
1135          * majority of services. */
1136
1137         /* First, pull in base system */
1138         r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
1139                                               SPECIAL_BASIC_TARGET, NULL, true);
1140         if (r < 0)
1141                 return r;
1142
1143         /* Second, activate normal shutdown */
1144         r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS,
1145                                               SPECIAL_SHUTDOWN_TARGET, NULL, true);
1146         return r;
1147 }
1148
1149 static void service_fix_output(Service *s) {
1150         assert(s);
1151
1152         /* If nothing has been explicitly configured, patch default
1153          * output in. If input is socket/tty we avoid this however,
1154          * since in that case we want output to default to the same
1155          * place as we read input from. */
1156
1157         if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1158             s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1159             s->exec_context.std_input == EXEC_INPUT_NULL)
1160                 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
1161
1162         if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1163             s->exec_context.std_input == EXEC_INPUT_NULL)
1164                 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
1165 }
1166
1167 static int service_load(Unit *u) {
1168         int r;
1169         Service *s = SERVICE(u);
1170
1171         assert(s);
1172
1173         /* Load a .service file */
1174         r = unit_load_fragment(u);
1175         if (r < 0)
1176                 return r;
1177
1178 #ifdef HAVE_SYSV_COMPAT
1179         /* Load a classic init script as a fallback, if we couldn't find anything */
1180         if (u->load_state == UNIT_STUB) {
1181                 r = service_load_sysv(s);
1182                 if (r < 0)
1183                         return r;
1184         }
1185 #endif
1186
1187         /* Still nothing found? Then let's give up */
1188         if (u->load_state == UNIT_STUB)
1189                 return -ENOENT;
1190
1191         /* This is a new unit? Then let's add in some extras */
1192         if (u->load_state == UNIT_LOADED) {
1193
1194                 /* We were able to load something, then let's add in
1195                  * the dropin directories. */
1196                 r = unit_load_dropin(u);
1197                 if (r < 0)
1198                         return r;
1199
1200                 if (s->type == _SERVICE_TYPE_INVALID)
1201                         s->type = s->bus_name ? SERVICE_DBUS : SERVICE_SIMPLE;
1202
1203                 /* Oneshot services have disabled start timeout by default */
1204                 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
1205                         s->timeout_start_usec = 0;
1206
1207                 service_fix_output(s);
1208
1209                 r = unit_patch_contexts(u);
1210                 if (r < 0)
1211                         return r;
1212
1213                 r = unit_add_exec_dependencies(u, &s->exec_context);
1214                 if (r < 0)
1215                         return r;
1216
1217                 r = unit_add_default_slice(u, &s->cgroup_context);
1218                 if (r < 0)
1219                         return r;
1220
1221 #ifdef HAVE_SYSV_COMPAT
1222                 r = sysv_fix_order(s);
1223                 if (r < 0)
1224                         return r;
1225 #endif
1226
1227                 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1228                         s->notify_access = NOTIFY_MAIN;
1229
1230                 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
1231                         s->notify_access = NOTIFY_MAIN;
1232
1233                 if (s->bus_name) {
1234                         r = unit_watch_bus_name(u, s->bus_name);
1235                         if (r < 0)
1236                                 return r;
1237                 }
1238
1239                 if (u->default_dependencies) {
1240                         r = service_add_default_dependencies(s);
1241                         if (r < 0)
1242                                 return r;
1243                 }
1244         }
1245
1246         return service_verify(s);
1247 }
1248
1249 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1250
1251         ServiceExecCommand c;
1252         Service *s = SERVICE(u);
1253         const char *prefix2;
1254         _cleanup_free_ char *p2 = NULL;
1255
1256         assert(s);
1257
1258         p2 = strappend(prefix, "\t");
1259         prefix2 = p2 ? p2 : prefix;
1260
1261         fprintf(f,
1262                 "%sService State: %s\n"
1263                 "%sResult: %s\n"
1264                 "%sReload Result: %s\n"
1265                 "%sPermissionsStartOnly: %s\n"
1266                 "%sRootDirectoryStartOnly: %s\n"
1267                 "%sRemainAfterExit: %s\n"
1268                 "%sGuessMainPID: %s\n"
1269                 "%sType: %s\n"
1270                 "%sRestart: %s\n"
1271                 "%sNotifyAccess: %s\n",
1272                 prefix, service_state_to_string(s->state),
1273                 prefix, service_result_to_string(s->result),
1274                 prefix, service_result_to_string(s->reload_result),
1275                 prefix, yes_no(s->permissions_start_only),
1276                 prefix, yes_no(s->root_directory_start_only),
1277                 prefix, yes_no(s->remain_after_exit),
1278                 prefix, yes_no(s->guess_main_pid),
1279                 prefix, service_type_to_string(s->type),
1280                 prefix, service_restart_to_string(s->restart),
1281                 prefix, notify_access_to_string(s->notify_access));
1282
1283         if (s->control_pid > 0)
1284                 fprintf(f,
1285                         "%sControl PID: "PID_FMT"\n",
1286                         prefix, s->control_pid);
1287
1288         if (s->main_pid > 0)
1289                 fprintf(f,
1290                         "%sMain PID: "PID_FMT"\n"
1291                         "%sMain PID Known: %s\n"
1292                         "%sMain PID Alien: %s\n",
1293                         prefix, s->main_pid,
1294                         prefix, yes_no(s->main_pid_known),
1295                         prefix, yes_no(s->main_pid_alien));
1296
1297         if (s->pid_file)
1298                 fprintf(f,
1299                         "%sPIDFile: %s\n",
1300                         prefix, s->pid_file);
1301
1302         if (s->bus_name)
1303                 fprintf(f,
1304                         "%sBusName: %s\n"
1305                         "%sBus Name Good: %s\n",
1306                         prefix, s->bus_name,
1307                         prefix, yes_no(s->bus_name_good));
1308
1309         kill_context_dump(&s->kill_context, f, prefix);
1310         exec_context_dump(&s->exec_context, f, prefix);
1311
1312         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1313
1314                 if (!s->exec_command[c])
1315                         continue;
1316
1317                 fprintf(f, "%s-> %s:\n",
1318                         prefix, service_exec_command_to_string(c));
1319
1320                 exec_command_dump_list(s->exec_command[c], f, prefix2);
1321         }
1322
1323 #ifdef HAVE_SYSV_COMPAT
1324         if (s->is_sysv)
1325                 fprintf(f,
1326                         "%sSysV Init Script has LSB Header: %s\n"
1327                         "%sSysVEnabled: %s\n",
1328                         prefix, yes_no(s->sysv_has_lsb),
1329                         prefix, yes_no(s->sysv_enabled));
1330
1331         if (s->sysv_start_priority >= 0)
1332                 fprintf(f,
1333                         "%sSysVStartPriority: %i\n",
1334                         prefix, s->sysv_start_priority);
1335
1336         if (s->sysv_runlevels)
1337                 fprintf(f, "%sSysVRunLevels: %s\n",
1338                         prefix, s->sysv_runlevels);
1339 #endif
1340
1341         if (s->status_text)
1342                 fprintf(f, "%sStatus Text: %s\n",
1343                         prefix, s->status_text);
1344 }
1345
1346 static int service_load_pid_file(Service *s, bool may_warn) {
1347         _cleanup_free_ char *k = NULL;
1348         int r;
1349         pid_t pid;
1350
1351         assert(s);
1352
1353         if (!s->pid_file)
1354                 return -ENOENT;
1355
1356         r = read_one_line_file(s->pid_file, &k);
1357         if (r < 0) {
1358                 if (may_warn)
1359                         log_info_unit(UNIT(s)->id,
1360                                       "PID file %s not readable (yet?) after %s.",
1361                                       s->pid_file, service_state_to_string(s->state));
1362                 return r;
1363         }
1364
1365         r = parse_pid(k, &pid);
1366         if (r < 0) {
1367                 if (may_warn)
1368                         log_info_unit(UNIT(s)->id,
1369                                       "Failed to read PID from file %s: %s",
1370                                       s->pid_file, strerror(-r));
1371                 return r;
1372         }
1373
1374         if (!pid_is_alive(pid)) {
1375                 if (may_warn)
1376                         log_info_unit(UNIT(s)->id, "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
1377
1378                 return -ESRCH;
1379         }
1380
1381         if (s->main_pid_known) {
1382                 if (pid == s->main_pid)
1383                         return 0;
1384
1385                 log_debug_unit(UNIT(s)->id,
1386                                "Main PID changing: "PID_FMT" -> "PID_FMT,
1387                                s->main_pid, pid);
1388                 service_unwatch_main_pid(s);
1389                 s->main_pid_known = false;
1390         } else
1391                 log_debug_unit(UNIT(s)->id,
1392                                "Main PID loaded: "PID_FMT, pid);
1393
1394         r = service_set_main_pid(s, pid);
1395         if (r < 0)
1396                 return r;
1397
1398         r = unit_watch_pid(UNIT(s), pid);
1399         if (r < 0) {
1400                 /* FIXME: we need to do something here */
1401                 log_warning_unit(UNIT(s)->id,
1402                                  "Failed to watch PID "PID_FMT" from service %s",
1403                                  pid, UNIT(s)->id);
1404                 return r;
1405         }
1406
1407         return 0;
1408 }
1409
1410 static int service_search_main_pid(Service *s) {
1411         pid_t pid;
1412         int r;
1413
1414         assert(s);
1415
1416         /* If we know it anyway, don't ever fallback to unreliable
1417          * heuristics */
1418         if (s->main_pid_known)
1419                 return 0;
1420
1421         if (!s->guess_main_pid)
1422                 return 0;
1423
1424         assert(s->main_pid <= 0);
1425
1426         pid = unit_search_main_pid(UNIT(s));
1427         if (pid <= 0)
1428                 return -ENOENT;
1429
1430         log_debug_unit(UNIT(s)->id,
1431                        "Main PID guessed: "PID_FMT, pid);
1432         r = service_set_main_pid(s, pid);
1433         if (r < 0)
1434                 return r;
1435
1436         r = unit_watch_pid(UNIT(s), pid);
1437         if (r < 0)
1438                 /* FIXME: we need to do something here */
1439                 log_warning_unit(UNIT(s)->id,
1440                                  "Failed to watch PID "PID_FMT" from service %s",
1441                                  pid, UNIT(s)->id);
1442         return r;
1443 }
1444
1445 static void service_set_state(Service *s, ServiceState state) {
1446         ServiceState old_state;
1447         const UnitActiveState *table;
1448
1449         assert(s);
1450
1451         table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1452
1453         old_state = s->state;
1454         s->state = state;
1455
1456         service_unwatch_pid_file(s);
1457
1458         if (!IN_SET(state,
1459                     SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1460                     SERVICE_RELOAD,
1461                     SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
1462                     SERVICE_STOP_POST,
1463                     SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
1464                     SERVICE_AUTO_RESTART))
1465                 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1466
1467         if (!IN_SET(state,
1468                     SERVICE_START, SERVICE_START_POST,
1469                     SERVICE_RUNNING, SERVICE_RELOAD,
1470                     SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
1471                     SERVICE_STOP_POST,
1472                     SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
1473                 service_unwatch_main_pid(s);
1474                 s->main_command = NULL;
1475         }
1476
1477         if (!IN_SET(state,
1478                     SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1479                     SERVICE_RELOAD,
1480                     SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
1481                     SERVICE_STOP_POST,
1482                     SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
1483                 service_unwatch_control_pid(s);
1484                 s->control_command = NULL;
1485                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1486         }
1487
1488         if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
1489                 unit_unwatch_all_pids(UNIT(s));
1490
1491         if (!IN_SET(state,
1492                     SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1493                     SERVICE_RUNNING, SERVICE_RELOAD,
1494                     SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1495                     SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
1496             !(state == SERVICE_DEAD && UNIT(s)->job)) {
1497                 service_close_socket_fd(s);
1498                 service_connection_unref(s);
1499         }
1500
1501         if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1502                 service_stop_watchdog(s);
1503
1504         /* For the inactive states unit_notify() will trim the cgroup,
1505          * but for exit we have to do that ourselves... */
1506         if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
1507                 unit_destroy_cgroup(UNIT(s));
1508
1509         /* For remain_after_exit services, let's see if we can "release" the
1510          * hold on the console, since unit_notify() only does that in case of
1511          * change of state */
1512         if (state == SERVICE_EXITED && s->remain_after_exit &&
1513             UNIT(s)->manager->n_on_console > 0) {
1514                 ExecContext *ec = unit_get_exec_context(UNIT(s));
1515                 if (ec && exec_context_may_touch_console(ec)) {
1516                         Manager *m = UNIT(s)->manager;
1517
1518                         m->n_on_console --;
1519                         if (m->n_on_console == 0)
1520                                 /* unset no_console_output flag, since the console is free */
1521                                 m->no_console_output = false;
1522                 }
1523         }
1524
1525         if (old_state != state)
1526                 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
1527
1528         unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
1529         s->reload_result = SERVICE_SUCCESS;
1530 }
1531
1532 static int service_coldplug(Unit *u) {
1533         Service *s = SERVICE(u);
1534         int r;
1535
1536         assert(s);
1537         assert(s->state == SERVICE_DEAD);
1538
1539         if (s->deserialized_state != s->state) {
1540
1541                 if (IN_SET(s->deserialized_state,
1542                            SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1543                            SERVICE_RELOAD,
1544                            SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
1545                            SERVICE_STOP_POST,
1546                            SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
1547
1548                         usec_t k;
1549
1550                         k = IN_SET(s->deserialized_state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec;
1551
1552                         /* For the start/stop timeouts 0 means off */
1553                         if (k > 0) {
1554                                 r = service_arm_timer(s, k);
1555                                 if (r < 0)
1556                                         return r;
1557                         }
1558                 }
1559
1560                 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
1561
1562                         /* The restart timeouts 0 means immediately */
1563                         r = service_arm_timer(s, s->restart_usec);
1564                         if (r < 0)
1565                                 return r;
1566                 }
1567
1568                 if (pid_is_unwaited(s->main_pid) &&
1569                     ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
1570                      IN_SET(s->deserialized_state,
1571                             SERVICE_START, SERVICE_START_POST,
1572                             SERVICE_RUNNING, SERVICE_RELOAD,
1573                             SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
1574                             SERVICE_STOP_POST,
1575                             SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
1576                         r = unit_watch_pid(UNIT(s), s->main_pid);
1577                         if (r < 0)
1578                                 return r;
1579                 }
1580
1581                 if (pid_is_unwaited(s->control_pid) &&
1582                     IN_SET(s->deserialized_state,
1583                            SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1584                            SERVICE_RELOAD,
1585                            SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
1586                            SERVICE_STOP_POST,
1587                            SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
1588                         r = unit_watch_pid(UNIT(s), s->control_pid);
1589                         if (r < 0)
1590                                 return r;
1591                 }
1592
1593                 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
1594                         unit_watch_all_pids(UNIT(s));
1595
1596                 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1597                         service_start_watchdog(s);
1598
1599                 service_set_state(s, s->deserialized_state);
1600         }
1601
1602         return 0;
1603 }
1604
1605 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1606         Iterator i;
1607         int r;
1608         int *rfds = NULL;
1609         unsigned rn_fds = 0;
1610         Unit *u;
1611
1612         assert(s);
1613         assert(fds);
1614         assert(n_fds);
1615
1616         if (s->socket_fd >= 0)
1617                 return 0;
1618
1619         SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1620                 int *cfds;
1621                 unsigned cn_fds;
1622                 Socket *sock;
1623
1624                 if (u->type != UNIT_SOCKET)
1625                         continue;
1626
1627                 sock = SOCKET(u);
1628
1629                 r = socket_collect_fds(sock, &cfds, &cn_fds);
1630                 if (r < 0)
1631                         goto fail;
1632
1633                 if (!cfds)
1634                         continue;
1635
1636                 if (!rfds) {
1637                         rfds = cfds;
1638                         rn_fds = cn_fds;
1639                 } else {
1640                         int *t;
1641
1642                         t = new(int, rn_fds+cn_fds);
1643                         if (!t) {
1644                                 free(cfds);
1645                                 r = -ENOMEM;
1646                                 goto fail;
1647                         }
1648
1649                         memcpy(t, rfds, rn_fds * sizeof(int));
1650                         memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1651                         free(rfds);
1652                         free(cfds);
1653
1654                         rfds = t;
1655                         rn_fds = rn_fds+cn_fds;
1656                 }
1657         }
1658
1659         *fds = rfds;
1660         *n_fds = rn_fds;
1661
1662         return 0;
1663
1664 fail:
1665         free(rfds);
1666
1667         return r;
1668 }
1669
1670 static int service_spawn(
1671                 Service *s,
1672                 ExecCommand *c,
1673                 bool timeout,
1674                 bool pass_fds,
1675                 bool apply_permissions,
1676                 bool apply_chroot,
1677                 bool apply_tty_stdin,
1678                 bool set_notify_socket,
1679                 bool is_control,
1680                 pid_t *_pid) {
1681
1682         pid_t pid;
1683         int r;
1684         int *fds = NULL;
1685         _cleanup_free_ int *fdsbuf = NULL;
1686         unsigned n_fds = 0, n_env = 0;
1687         _cleanup_strv_free_ char
1688                 **argv = NULL, **final_env = NULL, **our_env = NULL;
1689         const char *path;
1690
1691         assert(s);
1692         assert(c);
1693         assert(_pid);
1694
1695         unit_realize_cgroup(UNIT(s));
1696
1697         r = unit_setup_exec_runtime(UNIT(s));
1698         if (r < 0)
1699                 goto fail;
1700
1701         if (pass_fds ||
1702             s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1703             s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1704             s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1705
1706                 if (s->socket_fd >= 0) {
1707                         fds = &s->socket_fd;
1708                         n_fds = 1;
1709                 } else {
1710                         r = service_collect_fds(s, &fdsbuf, &n_fds);
1711                         if (r < 0)
1712                                 goto fail;
1713
1714                         fds = fdsbuf;
1715                 }
1716         }
1717
1718         if (timeout && s->timeout_start_usec > 0) {
1719                 r = service_arm_timer(s, s->timeout_start_usec);
1720                 if (r < 0)
1721                         goto fail;
1722         } else
1723                 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1724
1725         r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1726         if (r < 0)
1727                 goto fail;
1728
1729         our_env = new0(char*, 4);
1730         if (!our_env) {
1731                 r = -ENOMEM;
1732                 goto fail;
1733         }
1734
1735         if (set_notify_socket)
1736                 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1737                         r = -ENOMEM;
1738                         goto fail;
1739                 }
1740
1741         if (s->main_pid > 0)
1742                 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0) {
1743                         r = -ENOMEM;
1744                         goto fail;
1745                 }
1746
1747         if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
1748                 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0) {
1749                         r = -ENOMEM;
1750                         goto fail;
1751                 }
1752
1753         final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1754         if (!final_env) {
1755                 r = -ENOMEM;
1756                 goto fail;
1757         }
1758
1759         if (is_control && UNIT(s)->cgroup_path) {
1760                 path = strappenda(UNIT(s)->cgroup_path, "/control");
1761                 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1762         } else
1763                 path = UNIT(s)->cgroup_path;
1764
1765         r = exec_spawn(c,
1766                        argv,
1767                        &s->exec_context,
1768                        fds, n_fds,
1769                        final_env,
1770                        apply_permissions,
1771                        apply_chroot,
1772                        apply_tty_stdin,
1773                        UNIT(s)->manager->confirm_spawn,
1774                        UNIT(s)->manager->cgroup_supported,
1775                        path,
1776                        manager_get_runtime_prefix(UNIT(s)->manager),
1777                        UNIT(s)->id,
1778                        s->watchdog_usec,
1779                        s->type == SERVICE_IDLE ? UNIT(s)->manager->idle_pipe : NULL,
1780                        s->exec_runtime,
1781                        &pid);
1782         if (r < 0)
1783                 goto fail;
1784
1785         r = unit_watch_pid(UNIT(s), pid);
1786         if (r < 0)
1787                 /* FIXME: we need to do something here */
1788                 goto fail;
1789
1790         *_pid = pid;
1791
1792         return 0;
1793
1794 fail:
1795         if (timeout)
1796                 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1797
1798         return r;
1799 }
1800
1801 static int main_pid_good(Service *s) {
1802         assert(s);
1803
1804         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1805          * don't know */
1806
1807         /* If we know the pid file, then lets just check if it is
1808          * still valid */
1809         if (s->main_pid_known) {
1810
1811                 /* If it's an alien child let's check if it is still
1812                  * alive ... */
1813                 if (s->main_pid_alien && s->main_pid > 0)
1814                         return pid_is_alive(s->main_pid);
1815
1816                 /* .. otherwise assume we'll get a SIGCHLD for it,
1817                  * which we really should wait for to collect exit
1818                  * status and code */
1819                 return s->main_pid > 0;
1820         }
1821
1822         /* We don't know the pid */
1823         return -EAGAIN;
1824 }
1825
1826 _pure_ static int control_pid_good(Service *s) {
1827         assert(s);
1828
1829         return s->control_pid > 0;
1830 }
1831
1832 static int cgroup_good(Service *s) {
1833         int r;
1834
1835         assert(s);
1836
1837         if (!UNIT(s)->cgroup_path)
1838                 return 0;
1839
1840         r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
1841         if (r < 0)
1842                 return r;
1843
1844         return !r;
1845 }
1846
1847 static int service_execute_action(Service *s, FailureAction action, const char *reason, bool log_action_none);
1848
1849 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1850         int r;
1851         assert(s);
1852
1853         if (f != SERVICE_SUCCESS)
1854                 s->result = f;
1855
1856         service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1857
1858         if (s->result != SERVICE_SUCCESS)
1859                 service_execute_action(s, s->failure_action, "failed", false);
1860
1861         if (allow_restart &&
1862             !s->forbid_restart &&
1863             (s->restart == SERVICE_RESTART_ALWAYS ||
1864              (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1865              (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1866              (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
1867              (s->restart == SERVICE_RESTART_ON_ABORT && (s->result == SERVICE_FAILURE_SIGNAL ||
1868                                                          s->result == SERVICE_FAILURE_CORE_DUMP))) &&
1869             (s->result != SERVICE_FAILURE_EXIT_CODE ||
1870              !set_contains(s->restart_ignore_status.code, INT_TO_PTR(s->main_exec_status.status))) &&
1871             (s->result != SERVICE_FAILURE_SIGNAL ||
1872              !set_contains(s->restart_ignore_status.signal, INT_TO_PTR(s->main_exec_status.status)))) {
1873
1874                 r = service_arm_timer(s, s->restart_usec);
1875                 if (r < 0)
1876                         goto fail;
1877
1878                 service_set_state(s, SERVICE_AUTO_RESTART);
1879         }
1880
1881         s->forbid_restart = false;
1882
1883         /* We want fresh tmpdirs in case service is started again immediately */
1884         exec_runtime_destroy(s->exec_runtime);
1885         s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1886
1887         /* Also, remove the runtime directory in */
1888         exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1889
1890         /* Try to delete the pid file. At this point it will be
1891          * out-of-date, and some software might be confused by it, so
1892          * let's remove it. */
1893         if (s->pid_file)
1894                 unlink_noerrno(s->pid_file);
1895
1896         return;
1897
1898 fail:
1899         log_warning_unit(UNIT(s)->id,
1900                          "%s failed to run install restart timer: %s",
1901                          UNIT(s)->id, strerror(-r));
1902         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1903 }
1904
1905 static void service_enter_stop_post(Service *s, ServiceResult f) {
1906         int r;
1907         assert(s);
1908
1909         if (f != SERVICE_SUCCESS)
1910                 s->result = f;
1911
1912         service_unwatch_control_pid(s);
1913         unit_watch_all_pids(UNIT(s));
1914
1915         s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1916         if (s->control_command) {
1917                 s->control_command_id = SERVICE_EXEC_STOP_POST;
1918
1919                 r = service_spawn(s,
1920                                   s->control_command,
1921                                   true,
1922                                   false,
1923                                   !s->permissions_start_only,
1924                                   !s->root_directory_start_only,
1925                                   true,
1926                                   false,
1927                                   true,
1928                                   &s->control_pid);
1929                 if (r < 0)
1930                         goto fail;
1931
1932                 service_set_state(s, SERVICE_STOP_POST);
1933         } else
1934                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1935
1936         return;
1937
1938 fail:
1939         log_warning_unit(UNIT(s)->id,
1940                          "%s failed to run 'stop-post' task: %s",
1941                          UNIT(s)->id, strerror(-r));
1942         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1943 }
1944
1945 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1946         int r;
1947
1948         assert(s);
1949
1950         if (f != SERVICE_SUCCESS)
1951                 s->result = f;
1952
1953         unit_watch_all_pids(UNIT(s));
1954
1955         r = unit_kill_context(
1956                         UNIT(s),
1957                         &s->kill_context,
1958                         state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM,
1959                         s->main_pid,
1960                         s->control_pid,
1961                         s->main_pid_alien);
1962
1963         if (r < 0)
1964                 goto fail;
1965
1966         if (r > 0) {
1967                 if (s->timeout_stop_usec > 0) {
1968                         r = service_arm_timer(s, s->timeout_stop_usec);
1969                         if (r < 0)
1970                                 goto fail;
1971                 }
1972
1973                 service_set_state(s, state);
1974         } else if (state == SERVICE_STOP_SIGTERM)
1975                 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1976         else if (state == SERVICE_STOP_SIGKILL)
1977                 service_enter_stop_post(s, SERVICE_SUCCESS);
1978         else if (state == SERVICE_FINAL_SIGTERM)
1979                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1980         else
1981                 service_enter_dead(s, SERVICE_SUCCESS, true);
1982
1983         return;
1984
1985 fail:
1986         log_warning_unit(UNIT(s)->id,
1987                          "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1988
1989         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1990                 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1991         else
1992                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1993 }
1994
1995 static void service_enter_stop(Service *s, ServiceResult f) {
1996         int r;
1997
1998         assert(s);
1999
2000         if (f != SERVICE_SUCCESS)
2001                 s->result = f;
2002
2003         service_unwatch_control_pid(s);
2004         unit_watch_all_pids(UNIT(s));
2005
2006         s->control_command = s->exec_command[SERVICE_EXEC_STOP];
2007         if (s->control_command) {
2008                 s->control_command_id = SERVICE_EXEC_STOP;
2009
2010                 r = service_spawn(s,
2011                                   s->control_command,
2012                                   true,
2013                                   false,
2014                                   !s->permissions_start_only,
2015                                   !s->root_directory_start_only,
2016                                   false,
2017                                   false,
2018                                   true,
2019                                   &s->control_pid);
2020                 if (r < 0)
2021                         goto fail;
2022
2023                 service_set_state(s, SERVICE_STOP);
2024         } else
2025                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2026
2027         return;
2028
2029 fail:
2030         log_warning_unit(UNIT(s)->id,
2031                          "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
2032         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2033 }
2034
2035 static void service_enter_running(Service *s, ServiceResult f) {
2036         int main_pid_ok, cgroup_ok;
2037         assert(s);
2038
2039         if (f != SERVICE_SUCCESS)
2040                 s->result = f;
2041
2042         main_pid_ok = main_pid_good(s);
2043         cgroup_ok = cgroup_good(s);
2044
2045         if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
2046             (s->bus_name_good || s->type != SERVICE_DBUS))
2047                 service_set_state(s, SERVICE_RUNNING);
2048         else if (s->remain_after_exit)
2049                 service_set_state(s, SERVICE_EXITED);
2050         else
2051                 service_enter_stop(s, SERVICE_SUCCESS);
2052 }
2053
2054 static void service_enter_start_post(Service *s) {
2055         int r;
2056         assert(s);
2057
2058         service_unwatch_control_pid(s);
2059         service_reset_watchdog(s);
2060
2061         s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
2062         if (s->control_command) {
2063                 s->control_command_id = SERVICE_EXEC_START_POST;
2064
2065                 r = service_spawn(s,
2066                                   s->control_command,
2067                                   true,
2068                                   false,
2069                                   !s->permissions_start_only,
2070                                   !s->root_directory_start_only,
2071                                   false,
2072                                   false,
2073                                   true,
2074                                   &s->control_pid);
2075                 if (r < 0)
2076                         goto fail;
2077
2078                 service_set_state(s, SERVICE_START_POST);
2079         } else
2080                 service_enter_running(s, SERVICE_SUCCESS);
2081
2082         return;
2083
2084 fail:
2085         log_warning_unit(UNIT(s)->id,
2086                          "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
2087         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2088 }
2089
2090 static void service_kill_control_processes(Service *s) {
2091         char *p;
2092
2093         if (!UNIT(s)->cgroup_path)
2094                 return;
2095
2096         p = strappenda(UNIT(s)->cgroup_path, "/control");
2097         cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
2098 }
2099
2100 static void service_enter_start(Service *s) {
2101         ExecCommand *c;
2102         pid_t pid;
2103         int r;
2104
2105         assert(s);
2106
2107         assert(s->exec_command[SERVICE_EXEC_START]);
2108         assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2109
2110         service_unwatch_control_pid(s);
2111         service_unwatch_main_pid(s);
2112
2113         /* We want to ensure that nobody leaks processes from
2114          * START_PRE here, so let's go on a killing spree, People
2115          * should not spawn long running processes from START_PRE. */
2116         service_kill_control_processes(s);
2117
2118         if (s->type == SERVICE_FORKING) {
2119                 s->control_command_id = SERVICE_EXEC_START;
2120                 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2121
2122                 s->main_command = NULL;
2123         } else {
2124                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2125                 s->control_command = NULL;
2126
2127                 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2128         }
2129
2130         r = service_spawn(s,
2131                           c,
2132                           s->type == SERVICE_FORKING || s->type == SERVICE_DBUS ||
2133                             s->type == SERVICE_NOTIFY || s->type == SERVICE_ONESHOT,
2134                           true,
2135                           true,
2136                           true,
2137                           true,
2138                           s->notify_access != NOTIFY_NONE,
2139                           false,
2140                           &pid);
2141         if (r < 0)
2142                 goto fail;
2143
2144         if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
2145                 /* For simple services we immediately start
2146                  * the START_POST binaries. */
2147
2148                 service_set_main_pid(s, pid);
2149                 service_enter_start_post(s);
2150
2151         } else  if (s->type == SERVICE_FORKING) {
2152
2153                 /* For forking services we wait until the start
2154                  * process exited. */
2155
2156                 s->control_pid = pid;
2157                 service_set_state(s, SERVICE_START);
2158
2159         } else if (s->type == SERVICE_ONESHOT ||
2160                    s->type == SERVICE_DBUS ||
2161                    s->type == SERVICE_NOTIFY) {
2162
2163                 /* For oneshot services we wait until the start
2164                  * process exited, too, but it is our main process. */
2165
2166                 /* For D-Bus services we know the main pid right away,
2167                  * but wait for the bus name to appear on the
2168                  * bus. Notify services are similar. */
2169
2170                 service_set_main_pid(s, pid);
2171                 service_set_state(s, SERVICE_START);
2172         } else
2173                 assert_not_reached("Unknown service type");
2174
2175         return;
2176
2177 fail:
2178         log_warning_unit(UNIT(s)->id,
2179                          "%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
2180         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2181 }
2182
2183 static void service_enter_start_pre(Service *s) {
2184         int r;
2185
2186         assert(s);
2187
2188         service_unwatch_control_pid(s);
2189
2190         s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
2191         if (s->control_command) {
2192                 /* Before we start anything, let's clear up what might
2193                  * be left from previous runs. */
2194                 service_kill_control_processes(s);
2195
2196                 s->control_command_id = SERVICE_EXEC_START_PRE;
2197
2198                 r = service_spawn(s,
2199                                   s->control_command,
2200                                   true,
2201                                   false,
2202                                   !s->permissions_start_only,
2203                                   !s->root_directory_start_only,
2204                                   true,
2205                                   false,
2206                                   true,
2207                                   &s->control_pid);
2208                 if (r < 0)
2209                         goto fail;
2210
2211                 service_set_state(s, SERVICE_START_PRE);
2212         } else
2213                 service_enter_start(s);
2214
2215         return;
2216
2217 fail:
2218         log_warning_unit(UNIT(s)->id,
2219                          "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
2220         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2221 }
2222
2223 static void service_enter_restart(Service *s) {
2224         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2225         int r;
2226
2227         assert(s);
2228
2229         if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
2230                 /* Don't restart things if we are going down anyway */
2231                 log_info_unit(UNIT(s)->id,
2232                               "Stop job pending for unit, delaying automatic restart.");
2233
2234                 r = service_arm_timer(s, s->restart_usec);
2235                 if (r < 0)
2236                         goto fail;
2237
2238                 return;
2239         }
2240
2241         /* Any units that are bound to this service must also be
2242          * restarted. We use JOB_RESTART (instead of the more obvious
2243          * JOB_START) here so that those dependency jobs will be added
2244          * as well. */
2245         r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
2246         if (r < 0)
2247                 goto fail;
2248
2249         /* Note that we stay in the SERVICE_AUTO_RESTART state here,
2250          * it will be canceled as part of the service_stop() call that
2251          * is executed as part of JOB_RESTART. */
2252
2253         log_debug_unit(UNIT(s)->id,
2254                        "%s scheduled restart job.", UNIT(s)->id);
2255         return;
2256
2257 fail:
2258         log_warning_unit(UNIT(s)->id,
2259                          "%s failed to schedule restart job: %s",
2260                          UNIT(s)->id, bus_error_message(&error, -r));
2261         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
2262 }
2263
2264 static void service_enter_reload(Service *s) {
2265         int r;
2266
2267         assert(s);
2268
2269         service_unwatch_control_pid(s);
2270
2271         s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
2272         if (s->control_command) {
2273                 s->control_command_id = SERVICE_EXEC_RELOAD;
2274
2275                 r = service_spawn(s,
2276                                   s->control_command,
2277                                   true,
2278                                   false,
2279                                   !s->permissions_start_only,
2280                                   !s->root_directory_start_only,
2281                                   false,
2282                                   false,
2283                                   true,
2284                                   &s->control_pid);
2285                 if (r < 0)
2286                         goto fail;
2287
2288                 service_set_state(s, SERVICE_RELOAD);
2289         } else
2290                 service_enter_running(s, SERVICE_SUCCESS);
2291
2292         return;
2293
2294 fail:
2295         log_warning_unit(UNIT(s)->id,
2296                          "%s failed to run 'reload' task: %s",
2297                          UNIT(s)->id, strerror(-r));
2298         s->reload_result = SERVICE_FAILURE_RESOURCES;
2299         service_enter_running(s, SERVICE_SUCCESS);
2300 }
2301
2302 static void service_run_next_control(Service *s) {
2303         int r;
2304
2305         assert(s);
2306         assert(s->control_command);
2307         assert(s->control_command->command_next);
2308
2309         assert(s->control_command_id != SERVICE_EXEC_START);
2310
2311         s->control_command = s->control_command->command_next;
2312         service_unwatch_control_pid(s);
2313
2314         r = service_spawn(s,
2315                           s->control_command,
2316                           true,
2317                           false,
2318                           !s->permissions_start_only,
2319                           !s->root_directory_start_only,
2320                           s->control_command_id == SERVICE_EXEC_START_PRE ||
2321                           s->control_command_id == SERVICE_EXEC_STOP_POST,
2322                           false,
2323                           true,
2324                           &s->control_pid);
2325         if (r < 0)
2326                 goto fail;
2327
2328         return;
2329
2330 fail:
2331         log_warning_unit(UNIT(s)->id,
2332                          "%s failed to run next control task: %s",
2333                          UNIT(s)->id, strerror(-r));
2334
2335         if (s->state == SERVICE_START_PRE)
2336                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2337         else if (s->state == SERVICE_STOP)
2338                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2339         else if (s->state == SERVICE_STOP_POST)
2340                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2341         else if (s->state == SERVICE_RELOAD) {
2342                 s->reload_result = SERVICE_FAILURE_RESOURCES;
2343                 service_enter_running(s, SERVICE_SUCCESS);
2344         } else
2345                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2346 }
2347
2348 static void service_run_next_main(Service *s) {
2349         pid_t pid;
2350         int r;
2351
2352         assert(s);
2353         assert(s->main_command);
2354         assert(s->main_command->command_next);
2355         assert(s->type == SERVICE_ONESHOT);
2356
2357         s->main_command = s->main_command->command_next;
2358         service_unwatch_main_pid(s);
2359
2360         r = service_spawn(s,
2361                           s->main_command,
2362                           true,
2363                           true,
2364                           true,
2365                           true,
2366                           true,
2367                           s->notify_access != NOTIFY_NONE,
2368                           false,
2369                           &pid);
2370         if (r < 0)
2371                 goto fail;
2372
2373         service_set_main_pid(s, pid);
2374
2375         return;
2376
2377 fail:
2378         log_warning_unit(UNIT(s)->id,
2379                          "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
2380         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2381 }
2382
2383 static int service_execute_action(Service *s, FailureAction action, const char *reason, bool log_action_none) {
2384         assert(s);
2385
2386         if (action == SERVICE_FAILURE_ACTION_REBOOT ||
2387             action == SERVICE_FAILURE_ACTION_REBOOT_FORCE)
2388                 update_reboot_param_file(s->reboot_arg);
2389
2390         switch (action) {
2391
2392         case SERVICE_FAILURE_ACTION_NONE:
2393                 if (log_action_none)
2394                         log_warning_unit(UNIT(s)->id,
2395                                          "%s %s, refusing to start.", UNIT(s)->id, reason);
2396                 break;
2397
2398         case SERVICE_FAILURE_ACTION_REBOOT: {
2399                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2400                 int r;
2401
2402                 log_warning_unit(UNIT(s)->id,
2403                                  "%s %s, rebooting.", UNIT(s)->id, reason);
2404
2405                 r = manager_add_job_by_name(UNIT(s)->manager, JOB_START,
2406                                             SPECIAL_REBOOT_TARGET, JOB_REPLACE,
2407                                             true, &error, NULL);
2408                 if (r < 0)
2409                         log_error_unit(UNIT(s)->id,
2410                                        "Failed to reboot: %s.", bus_error_message(&error, r));
2411
2412                 break;
2413         }
2414
2415         case SERVICE_FAILURE_ACTION_REBOOT_FORCE:
2416                 log_warning_unit(UNIT(s)->id,
2417                                  "%s %s, forcibly rebooting.", UNIT(s)->id, reason);
2418                 UNIT(s)->manager->exit_code = MANAGER_REBOOT;
2419                 break;
2420
2421         case SERVICE_FAILURE_ACTION_REBOOT_IMMEDIATE:
2422                 log_warning_unit(UNIT(s)->id,
2423                                  "%s %s, rebooting immediately.", UNIT(s)->id, reason);
2424                 sync();
2425                 if (s->reboot_arg) {
2426                         log_info("Rebooting with argument '%s'.", s->reboot_arg);
2427                         syscall(SYS_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
2428                                 LINUX_REBOOT_CMD_RESTART2, s->reboot_arg);
2429                 }
2430
2431                 log_info("Rebooting.");
2432                 reboot(RB_AUTOBOOT);
2433                 break;
2434
2435         default:
2436                 log_error_unit(UNIT(s)->id,
2437                                "failure action=%i", action);
2438                 assert_not_reached("Unknown FailureAction.");
2439         }
2440
2441         return -ECANCELED;
2442 }
2443
2444 static int service_start_limit_test(Service *s) {
2445         assert(s);
2446
2447         if (ratelimit_test(&s->start_limit))
2448                 return 0;
2449
2450         return service_execute_action(s, s->start_limit_action, "start request repeated too quickly", true);
2451 }
2452
2453 static int service_start(Unit *u) {
2454         Service *s = SERVICE(u);
2455         int r;
2456
2457         assert(s);
2458
2459         /* We cannot fulfill this request right now, try again later
2460          * please! */
2461         if (s->state == SERVICE_STOP ||
2462             s->state == SERVICE_STOP_SIGTERM ||
2463             s->state == SERVICE_STOP_SIGKILL ||
2464             s->state == SERVICE_STOP_POST ||
2465             s->state == SERVICE_FINAL_SIGTERM ||
2466             s->state == SERVICE_FINAL_SIGKILL)
2467                 return -EAGAIN;
2468
2469         /* Already on it! */
2470         if (s->state == SERVICE_START_PRE ||
2471             s->state == SERVICE_START ||
2472             s->state == SERVICE_START_POST)
2473                 return 0;
2474
2475         /* A service that will be restarted must be stopped first to
2476          * trigger BindsTo and/or OnFailure dependencies. If a user
2477          * does not want to wait for the holdoff time to elapse, the
2478          * service should be manually restarted, not started. We
2479          * simply return EAGAIN here, so that any start jobs stay
2480          * queued, and assume that the auto restart timer will
2481          * eventually trigger the restart. */
2482         if (s->state == SERVICE_AUTO_RESTART)
2483                 return -EAGAIN;
2484
2485         assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
2486
2487         /* Make sure we don't enter a busy loop of some kind. */
2488         r = service_start_limit_test(s);
2489         if (r < 0) {
2490                 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
2491                 return r;
2492         }
2493
2494         s->result = SERVICE_SUCCESS;
2495         s->reload_result = SERVICE_SUCCESS;
2496         s->main_pid_known = false;
2497         s->main_pid_alien = false;
2498         s->forbid_restart = false;
2499
2500         service_enter_start_pre(s);
2501         return 0;
2502 }
2503
2504 static int service_stop(Unit *u) {
2505         Service *s = SERVICE(u);
2506
2507         assert(s);
2508
2509         /* Don't create restart jobs from here. */
2510         s->forbid_restart = true;
2511
2512         /* Already on it */
2513         if (s->state == SERVICE_STOP ||
2514             s->state == SERVICE_STOP_SIGTERM ||
2515             s->state == SERVICE_STOP_SIGKILL ||
2516             s->state == SERVICE_STOP_POST ||
2517             s->state == SERVICE_FINAL_SIGTERM ||
2518             s->state == SERVICE_FINAL_SIGKILL)
2519                 return 0;
2520
2521         /* A restart will be scheduled or is in progress. */
2522         if (s->state == SERVICE_AUTO_RESTART) {
2523                 service_set_state(s, SERVICE_DEAD);
2524                 return 0;
2525         }
2526
2527         /* If there's already something running we go directly into
2528          * kill mode. */
2529         if (s->state == SERVICE_START_PRE ||
2530             s->state == SERVICE_START ||
2531             s->state == SERVICE_START_POST ||
2532             s->state == SERVICE_RELOAD) {
2533                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2534                 return 0;
2535         }
2536
2537         assert(s->state == SERVICE_RUNNING ||
2538                s->state == SERVICE_EXITED);
2539
2540         service_enter_stop(s, SERVICE_SUCCESS);
2541         return 0;
2542 }
2543
2544 static int service_reload(Unit *u) {
2545         Service *s = SERVICE(u);
2546
2547         assert(s);
2548
2549         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2550
2551         service_enter_reload(s);
2552         return 0;
2553 }
2554
2555 _pure_ static bool service_can_reload(Unit *u) {
2556         Service *s = SERVICE(u);
2557
2558         assert(s);
2559
2560         return !!s->exec_command[SERVICE_EXEC_RELOAD];
2561 }
2562
2563 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2564         Service *s = SERVICE(u);
2565
2566         assert(u);
2567         assert(f);
2568         assert(fds);
2569
2570         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2571         unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2572         unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2573
2574         if (s->control_pid > 0)
2575                 unit_serialize_item_format(u, f, "control-pid", PID_FMT,
2576                                            s->control_pid);
2577
2578         if (s->main_pid_known && s->main_pid > 0)
2579                 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
2580
2581         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2582
2583         if (s->status_text)
2584                 unit_serialize_item(u, f, "status-text", s->status_text);
2585
2586         /* FIXME: There's a minor uncleanliness here: if there are
2587          * multiple commands attached here, we will start from the
2588          * first one again */
2589         if (s->control_command_id >= 0)
2590                 unit_serialize_item(u, f, "control-command",
2591                                     service_exec_command_to_string(s->control_command_id));
2592
2593         if (s->socket_fd >= 0) {
2594                 int copy;
2595
2596                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2597                         return copy;
2598
2599                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2600         }
2601
2602         if (s->main_exec_status.pid > 0) {
2603                 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT,
2604                                            s->main_exec_status.pid);
2605                 dual_timestamp_serialize(f, "main-exec-status-start",
2606                                          &s->main_exec_status.start_timestamp);
2607                 dual_timestamp_serialize(f, "main-exec-status-exit",
2608                                          &s->main_exec_status.exit_timestamp);
2609
2610                 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2611                         unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
2612                                                    s->main_exec_status.code);
2613                         unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
2614                                                    s->main_exec_status.status);
2615                 }
2616         }
2617         if (dual_timestamp_is_set(&s->watchdog_timestamp))
2618                 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2619
2620         if (s->forbid_restart)
2621                 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
2622
2623         return 0;
2624 }
2625
2626 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2627         Service *s = SERVICE(u);
2628
2629         assert(u);
2630         assert(key);
2631         assert(value);
2632         assert(fds);
2633
2634         if (streq(key, "state")) {
2635                 ServiceState state;
2636
2637                 state = service_state_from_string(value);
2638                 if (state < 0)
2639                         log_debug_unit(u->id, "Failed to parse state value %s", value);
2640                 else
2641                         s->deserialized_state = state;
2642         } else if (streq(key, "result")) {
2643                 ServiceResult f;
2644
2645                 f = service_result_from_string(value);
2646                 if (f < 0)
2647                         log_debug_unit(u->id, "Failed to parse result value %s", value);
2648                 else if (f != SERVICE_SUCCESS)
2649                         s->result = f;
2650
2651         } else if (streq(key, "reload-result")) {
2652                 ServiceResult f;
2653
2654                 f = service_result_from_string(value);
2655                 if (f < 0)
2656                         log_debug_unit(u->id, "Failed to parse reload result value %s", value);
2657                 else if (f != SERVICE_SUCCESS)
2658                         s->reload_result = f;
2659
2660         } else if (streq(key, "control-pid")) {
2661                 pid_t pid;
2662
2663                 if (parse_pid(value, &pid) < 0)
2664                         log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
2665                 else
2666                         s->control_pid = pid;
2667         } else if (streq(key, "main-pid")) {
2668                 pid_t pid;
2669
2670                 if (parse_pid(value, &pid) < 0)
2671                         log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
2672                 else {
2673                         service_set_main_pid(s, pid);
2674                         unit_watch_pid(UNIT(s), pid);
2675                 }
2676         } else if (streq(key, "main-pid-known")) {
2677                 int b;
2678
2679                 b = parse_boolean(value);
2680                 if (b < 0)
2681                         log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
2682                 else
2683                         s->main_pid_known = b;
2684         } else if (streq(key, "status-text")) {
2685                 char *t;
2686
2687                 t = strdup(value);
2688                 if (!t)
2689                         log_oom();
2690                 else {
2691                         free(s->status_text);
2692                         s->status_text = t;
2693                 }
2694
2695         } else if (streq(key, "control-command")) {
2696                 ServiceExecCommand id;
2697
2698                 id = service_exec_command_from_string(value);
2699                 if (id < 0)
2700                         log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
2701                 else {
2702                         s->control_command_id = id;
2703                         s->control_command = s->exec_command[id];
2704                 }
2705         } else if (streq(key, "socket-fd")) {
2706                 int fd;
2707
2708                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2709                         log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
2710                 else {
2711
2712                         safe_close(s->socket_fd);
2713                         s->socket_fd = fdset_remove(fds, fd);
2714                 }
2715         } else if (streq(key, "main-exec-status-pid")) {
2716                 pid_t pid;
2717
2718                 if (parse_pid(value, &pid) < 0)
2719                         log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
2720                 else
2721                         s->main_exec_status.pid = pid;
2722         } else if (streq(key, "main-exec-status-code")) {
2723                 int i;
2724
2725                 if (safe_atoi(value, &i) < 0)
2726                         log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
2727                 else
2728                         s->main_exec_status.code = i;
2729         } else if (streq(key, "main-exec-status-status")) {
2730                 int i;
2731
2732                 if (safe_atoi(value, &i) < 0)
2733                         log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
2734                 else
2735                         s->main_exec_status.status = i;
2736         } else if (streq(key, "main-exec-status-start"))
2737                 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2738         else if (streq(key, "main-exec-status-exit"))
2739                 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2740         else if (streq(key, "watchdog-timestamp"))
2741                 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2742         else if (streq(key, "forbid-restart")) {
2743                 int b;
2744
2745                 b = parse_boolean(value);
2746                 if (b < 0)
2747                         log_debug_unit(u->id, "Failed to parse forbid-restart value %s", value);
2748                 else
2749                         s->forbid_restart = b;
2750         } else
2751                 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
2752
2753         return 0;
2754 }
2755
2756 _pure_ static UnitActiveState service_active_state(Unit *u) {
2757         const UnitActiveState *table;
2758
2759         assert(u);
2760
2761         table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2762
2763         return table[SERVICE(u)->state];
2764 }
2765
2766 static const char *service_sub_state_to_string(Unit *u) {
2767         assert(u);
2768
2769         return service_state_to_string(SERVICE(u)->state);
2770 }
2771
2772 static bool service_check_gc(Unit *u) {
2773         Service *s = SERVICE(u);
2774
2775         assert(s);
2776
2777         /* Never clean up services that still have a process around,
2778          * even if the service is formally dead. */
2779         if (cgroup_good(s) > 0 ||
2780             main_pid_good(s) > 0 ||
2781             control_pid_good(s) > 0)
2782                 return true;
2783
2784 #ifdef HAVE_SYSV_COMPAT
2785         if (s->is_sysv)
2786                 return true;
2787 #endif
2788
2789         return false;
2790 }
2791
2792 _pure_ static bool service_check_snapshot(Unit *u) {
2793         Service *s = SERVICE(u);
2794
2795         assert(s);
2796
2797         return (s->socket_fd < 0);
2798 }
2799
2800 static int service_retry_pid_file(Service *s) {
2801         int r;
2802
2803         assert(s->pid_file);
2804         assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2805
2806         r = service_load_pid_file(s, false);
2807         if (r < 0)
2808                 return r;
2809
2810         service_unwatch_pid_file(s);
2811
2812         service_enter_running(s, SERVICE_SUCCESS);
2813         return 0;
2814 }
2815
2816 static int service_watch_pid_file(Service *s) {
2817         int r;
2818
2819         log_debug_unit(UNIT(s)->id,
2820                        "Setting watch for %s's PID file %s",
2821                        UNIT(s)->id, s->pid_file_pathspec->path);
2822         r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2823         if (r < 0)
2824                 goto fail;
2825
2826         /* the pidfile might have appeared just before we set the watch */
2827         log_debug_unit(UNIT(s)->id,
2828                        "Trying to read %s's PID file %s in case it changed",
2829                        UNIT(s)->id, s->pid_file_pathspec->path);
2830         service_retry_pid_file(s);
2831
2832         return 0;
2833 fail:
2834         log_error_unit(UNIT(s)->id,
2835                        "Failed to set a watch for %s's PID file %s: %s",
2836                        UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2837         service_unwatch_pid_file(s);
2838         return r;
2839 }
2840
2841 static int service_demand_pid_file(Service *s) {
2842         PathSpec *ps;
2843
2844         assert(s->pid_file);
2845         assert(!s->pid_file_pathspec);
2846
2847         ps = new0(PathSpec, 1);
2848         if (!ps)
2849                 return -ENOMEM;
2850
2851         ps->unit = UNIT(s);
2852         ps->path = strdup(s->pid_file);
2853         if (!ps->path) {
2854                 free(ps);
2855                 return -ENOMEM;
2856         }
2857
2858         path_kill_slashes(ps->path);
2859
2860         /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2861          * keep their PID file open all the time. */
2862         ps->type = PATH_MODIFIED;
2863         ps->inotify_fd = -1;
2864
2865         s->pid_file_pathspec = ps;
2866
2867         return service_watch_pid_file(s);
2868 }
2869
2870 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2871         PathSpec *p = userdata;
2872         Service *s;
2873
2874         assert(p);
2875
2876         s = SERVICE(p->unit);
2877
2878         assert(s);
2879         assert(fd >= 0);
2880         assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2881         assert(s->pid_file_pathspec);
2882         assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2883
2884         log_debug_unit(UNIT(s)->id, "inotify event for %s", UNIT(s)->id);
2885
2886         if (path_spec_fd_event(p, events) < 0)
2887                 goto fail;
2888
2889         if (service_retry_pid_file(s) == 0)
2890                 return 0;
2891
2892         if (service_watch_pid_file(s) < 0)
2893                 goto fail;
2894
2895         return 0;
2896
2897 fail:
2898         service_unwatch_pid_file(s);
2899         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2900         return 0;
2901 }
2902
2903 static void service_notify_cgroup_empty_event(Unit *u) {
2904         Service *s = SERVICE(u);
2905
2906         assert(u);
2907
2908         log_debug_unit(u->id, "%s: cgroup is empty", u->id);
2909
2910         switch (s->state) {
2911
2912                 /* Waiting for SIGCHLD is usually more interesting,
2913                  * because it includes return codes/signals. Which is
2914                  * why we ignore the cgroup events for most cases,
2915                  * except when we don't know pid which to expect the
2916                  * SIGCHLD for. */
2917
2918         case SERVICE_START:
2919         case SERVICE_START_POST:
2920                 /* If we were hoping for the daemon to write its PID file,
2921                  * we can give up now. */
2922                 if (s->pid_file_pathspec) {
2923                         log_warning_unit(u->id,
2924                                          "%s never wrote its PID file. Failing.", UNIT(s)->id);
2925                         service_unwatch_pid_file(s);
2926                         if (s->state == SERVICE_START)
2927                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2928                         else
2929                                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2930                 }
2931                 break;
2932
2933         case SERVICE_RUNNING:
2934                 /* service_enter_running() will figure out what to do */
2935                 service_enter_running(s, SERVICE_SUCCESS);
2936                 break;
2937
2938         case SERVICE_STOP_SIGTERM:
2939         case SERVICE_STOP_SIGKILL:
2940
2941                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2942                         service_enter_stop_post(s, SERVICE_SUCCESS);
2943
2944                 break;
2945
2946         case SERVICE_STOP_POST:
2947         case SERVICE_FINAL_SIGTERM:
2948         case SERVICE_FINAL_SIGKILL:
2949                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2950                         service_enter_dead(s, SERVICE_SUCCESS, true);
2951
2952                 break;
2953
2954         default:
2955                 ;
2956         }
2957 }
2958
2959 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2960         Service *s = SERVICE(u);
2961         ServiceResult f;
2962
2963         assert(s);
2964         assert(pid >= 0);
2965
2966         if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2967                                      is_clean_exit_lsb(code, status, &s->success_status))
2968                 f = SERVICE_SUCCESS;
2969         else if (code == CLD_EXITED)
2970                 f = SERVICE_FAILURE_EXIT_CODE;
2971         else if (code == CLD_KILLED)
2972                 f = SERVICE_FAILURE_SIGNAL;
2973         else if (code == CLD_DUMPED)
2974                 f = SERVICE_FAILURE_CORE_DUMP;
2975         else
2976                 assert_not_reached("Unknown code");
2977
2978         if (s->main_pid == pid) {
2979                 /* Forking services may occasionally move to a new PID.
2980                  * As long as they update the PID file before exiting the old
2981                  * PID, they're fine. */
2982                 if (service_load_pid_file(s, false) == 0)
2983                         return;
2984
2985                 s->main_pid = 0;
2986                 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2987
2988                 if (s->main_command) {
2989                         /* If this is not a forking service than the
2990                          * main process got started and hence we copy
2991                          * the exit status so that it is recorded both
2992                          * as main and as control process exit
2993                          * status */
2994
2995                         s->main_command->exec_status = s->main_exec_status;
2996
2997                         if (s->main_command->ignore)
2998                                 f = SERVICE_SUCCESS;
2999                 } else if (s->exec_command[SERVICE_EXEC_START]) {
3000
3001                         /* If this is a forked process, then we should
3002                          * ignore the return value if this was
3003                          * configured for the starter process */
3004
3005                         if (s->exec_command[SERVICE_EXEC_START]->ignore)
3006                                 f = SERVICE_SUCCESS;
3007                 }
3008
3009                 log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
3010                            u->id,
3011                            "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
3012                                   u->id, sigchld_code_to_string(code), status,
3013                                   strna(code == CLD_EXITED
3014                                         ? exit_status_to_string(status, EXIT_STATUS_FULL)
3015                                         : signal_to_string(status)),
3016                            "EXIT_CODE=%s", sigchld_code_to_string(code),
3017                            "EXIT_STATUS=%i", status,
3018                            NULL);
3019
3020                 if (f != SERVICE_SUCCESS)
3021                         s->result = f;
3022
3023                 if (s->main_command &&
3024                     s->main_command->command_next &&
3025                     f == SERVICE_SUCCESS) {
3026
3027                         /* There is another command to *
3028                          * execute, so let's do that. */
3029
3030                         log_debug_unit(u->id,
3031                                        "%s running next main command for state %s",
3032                                        u->id, service_state_to_string(s->state));
3033                         service_run_next_main(s);
3034
3035                 } else {
3036
3037                         /* The service exited, so the service is officially
3038                          * gone. */
3039                         s->main_command = NULL;
3040
3041                         switch (s->state) {
3042
3043                         case SERVICE_START_POST:
3044                         case SERVICE_RELOAD:
3045                         case SERVICE_STOP:
3046                                 /* Need to wait until the operation is
3047                                  * done */
3048                                 break;
3049
3050                         case SERVICE_START:
3051                                 if (s->type == SERVICE_ONESHOT) {
3052                                         /* This was our main goal, so let's go on */
3053                                         if (f == SERVICE_SUCCESS)
3054                                                 service_enter_start_post(s);
3055                                         else
3056                                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3057                                         break;
3058                                 }
3059
3060                                 /* Fall through */
3061
3062                         case SERVICE_RUNNING:
3063                                 service_enter_running(s, f);
3064                                 break;
3065
3066                         case SERVICE_STOP_SIGTERM:
3067                         case SERVICE_STOP_SIGKILL:
3068
3069                                 if (!control_pid_good(s))
3070                                         service_enter_stop_post(s, f);
3071
3072                                 /* If there is still a control process, wait for that first */
3073                                 break;
3074
3075                         case SERVICE_STOP_POST:
3076                         case SERVICE_FINAL_SIGTERM:
3077                         case SERVICE_FINAL_SIGKILL:
3078
3079                                 if (!control_pid_good(s))
3080                                         service_enter_dead(s, f, true);
3081                                 break;
3082
3083                         default:
3084                                 assert_not_reached("Uh, main process died at wrong time.");
3085                         }
3086                 }
3087
3088         } else if (s->control_pid == pid) {
3089                 s->control_pid = 0;
3090
3091                 if (s->control_command) {
3092                         exec_status_exit(&s->control_command->exec_status,
3093                                          &s->exec_context, pid, code, status);
3094
3095                         if (s->control_command->ignore)
3096                                 f = SERVICE_SUCCESS;
3097                 }
3098
3099                 log_full_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
3100                               "%s: control process exited, code=%s status=%i",
3101                               u->id, sigchld_code_to_string(code), status);
3102
3103                 if (f != SERVICE_SUCCESS)
3104                         s->result = f;
3105
3106                 /* Immediately get rid of the cgroup, so that the
3107                  * kernel doesn't delay the cgroup empty messages for
3108                  * the service cgroup any longer than necessary */
3109                 service_kill_control_processes(s);
3110
3111                 if (s->control_command &&
3112                     s->control_command->command_next &&
3113                     f == SERVICE_SUCCESS) {
3114
3115                         /* There is another command to *
3116                          * execute, so let's do that. */
3117
3118                         log_debug_unit(u->id,
3119                                        "%s running next control command for state %s",
3120                                        u->id, service_state_to_string(s->state));
3121                         service_run_next_control(s);
3122
3123                 } else {
3124                         /* No further commands for this step, so let's
3125                          * figure out what to do next */
3126
3127                         s->control_command = NULL;
3128                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
3129
3130                         log_debug_unit(u->id,
3131                                        "%s got final SIGCHLD for state %s",
3132                                        u->id, service_state_to_string(s->state));
3133
3134                         switch (s->state) {
3135
3136                         case SERVICE_START_PRE:
3137                                 if (f == SERVICE_SUCCESS)
3138                                         service_enter_start(s);
3139                                 else
3140                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3141                                 break;
3142
3143                         case SERVICE_START:
3144                                 if (s->type != SERVICE_FORKING)
3145                                         /* Maybe spurious event due to a reload that changed the type? */
3146                                         break;
3147
3148                                 if (f != SERVICE_SUCCESS) {
3149                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3150                                         break;
3151                                 }
3152
3153                                 if (s->pid_file) {
3154                                         bool has_start_post;
3155                                         int r;
3156
3157                                         /* Let's try to load the pid file here if we can.
3158                                          * The PID file might actually be created by a START_POST
3159                                          * script. In that case don't worry if the loading fails. */
3160
3161                                         has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
3162                                         r = service_load_pid_file(s, !has_start_post);
3163                                         if (!has_start_post && r < 0) {
3164                                                 r = service_demand_pid_file(s);
3165                                                 if (r < 0 || !cgroup_good(s))
3166                                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3167                                                 break;
3168                                         }
3169                                 } else
3170                                         service_search_main_pid(s);
3171
3172                                 service_enter_start_post(s);
3173                                 break;
3174
3175                         case SERVICE_START_POST:
3176                                 if (f != SERVICE_SUCCESS) {
3177                                         service_enter_stop(s, f);
3178                                         break;
3179                                 }
3180
3181                                 if (s->pid_file) {
3182                                         int r;
3183
3184                                         r = service_load_pid_file(s, true);
3185                                         if (r < 0) {
3186                                                 r = service_demand_pid_file(s);
3187                                                 if (r < 0 || !cgroup_good(s))
3188                                                         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3189                                                 break;
3190                                         }
3191                                 } else
3192                                         service_search_main_pid(s);
3193
3194                                 service_enter_running(s, SERVICE_SUCCESS);
3195                                 break;
3196
3197                         case SERVICE_RELOAD:
3198                                 if (f == SERVICE_SUCCESS) {
3199                                         service_load_pid_file(s, true);
3200                                         service_search_main_pid(s);
3201                                 }
3202
3203                                 s->reload_result = f;
3204                                 service_enter_running(s, SERVICE_SUCCESS);
3205                                 break;
3206
3207                         case SERVICE_STOP:
3208                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3209                                 break;
3210
3211                         case SERVICE_STOP_SIGTERM:
3212                         case SERVICE_STOP_SIGKILL:
3213                                 if (main_pid_good(s) <= 0)
3214                                         service_enter_stop_post(s, f);
3215
3216                                 /* If there is still a service
3217                                  * process around, wait until
3218                                  * that one quit, too */
3219                                 break;
3220
3221                         case SERVICE_STOP_POST:
3222                         case SERVICE_FINAL_SIGTERM:
3223                         case SERVICE_FINAL_SIGKILL:
3224                                 if (main_pid_good(s) <= 0)
3225                                         service_enter_dead(s, f, true);
3226                                 break;
3227
3228                         default:
3229                                 assert_not_reached("Uh, control process died at wrong time.");
3230                         }
3231                 }
3232         }
3233
3234         /* Notify clients about changed exit status */
3235         unit_add_to_dbus_queue(u);
3236
3237         /* We got one SIGCHLD for the service, let's watch all
3238          * processes that are now running of the service, and watch
3239          * that. Among the PIDs we then watch will be children
3240          * reassigned to us, which hopefully allows us to identify
3241          * when all children are gone */
3242         unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
3243         unit_watch_all_pids(u);
3244
3245         /* If the PID set is empty now, then let's finish this off */
3246         if (set_isempty(u->pids))
3247                 service_notify_cgroup_empty_event(u);
3248 }
3249
3250 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
3251         Service *s = SERVICE(userdata);
3252
3253         assert(s);
3254         assert(source == s->timer_event_source);
3255
3256         switch (s->state) {
3257
3258         case SERVICE_START_PRE:
3259         case SERVICE_START:
3260                 log_warning_unit(UNIT(s)->id,
3261                                  "%s %s operation timed out. Terminating.",
3262                                  UNIT(s)->id,
3263                                  s->state == SERVICE_START ? "start" : "start-pre");
3264                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3265                 break;
3266
3267         case SERVICE_START_POST:
3268                 log_warning_unit(UNIT(s)->id,
3269                                  "%s start-post operation timed out. Stopping.", UNIT(s)->id);
3270                 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
3271                 break;
3272
3273         case SERVICE_RELOAD:
3274                 log_warning_unit(UNIT(s)->id,
3275                                  "%s reload operation timed out. Stopping.", UNIT(s)->id);
3276                 s->reload_result = SERVICE_FAILURE_TIMEOUT;
3277                 service_enter_running(s, SERVICE_SUCCESS);
3278                 break;
3279
3280         case SERVICE_STOP:
3281                 log_warning_unit(UNIT(s)->id,
3282                                  "%s stopping timed out. Terminating.", UNIT(s)->id);
3283                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3284                 break;
3285
3286         case SERVICE_STOP_SIGTERM:
3287                 if (s->kill_context.send_sigkill) {
3288                         log_warning_unit(UNIT(s)->id,
3289                                          "%s stop-sigterm timed out. Killing.", UNIT(s)->id);
3290                         service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3291                 } else {
3292                         log_warning_unit(UNIT(s)->id,
3293                                          "%s stop-sigterm timed out. Skipping SIGKILL.", UNIT(s)->id);
3294                         service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3295                 }
3296
3297                 break;
3298
3299         case SERVICE_STOP_SIGKILL:
3300                 /* Uh, we sent a SIGKILL and it is still not gone?
3301                  * Must be something we cannot kill, so let's just be
3302                  * weirded out and continue */
3303
3304                 log_warning_unit(UNIT(s)->id,
3305                                  "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
3306                 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3307                 break;
3308
3309         case SERVICE_STOP_POST:
3310                 log_warning_unit(UNIT(s)->id,
3311                                  "%s stop-post timed out. Terminating.", UNIT(s)->id);
3312                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3313                 break;
3314
3315         case SERVICE_FINAL_SIGTERM:
3316                 if (s->kill_context.send_sigkill) {
3317                         log_warning_unit(UNIT(s)->id,
3318                                          "%s stop-final-sigterm timed out. Killing.", UNIT(s)->id);
3319                         service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3320                 } else {
3321                         log_warning_unit(UNIT(s)->id,
3322                                          "%s stop-final-sigterm timed out. Skipping SIGKILL. Entering failed mode.",
3323                                          UNIT(s)->id);
3324                         service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3325                 }
3326
3327                 break;
3328
3329         case SERVICE_FINAL_SIGKILL:
3330                 log_warning_unit(UNIT(s)->id,
3331                                  "%s still around after final SIGKILL. Entering failed mode.", UNIT(s)->id);
3332                 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
3333                 break;
3334
3335         case SERVICE_AUTO_RESTART:
3336                 log_info_unit(UNIT(s)->id,
3337                               s->restart_usec > 0 ?
3338                               "%s holdoff time over, scheduling restart." :
3339                               "%s has no holdoff time, scheduling restart.",
3340                               UNIT(s)->id);
3341                 service_enter_restart(s);
3342                 break;
3343
3344         default:
3345                 assert_not_reached("Timeout at wrong time.");
3346         }
3347
3348         return 0;
3349 }
3350
3351 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
3352         Service *s = SERVICE(userdata);
3353
3354         assert(s);
3355         assert(source == s->watchdog_event_source);
3356
3357         log_error_unit(UNIT(s)->id, "%s watchdog timeout!", UNIT(s)->id);
3358         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_WATCHDOG);
3359
3360         return 0;
3361 }
3362
3363 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
3364         Service *s = SERVICE(u);
3365         const char *e;
3366         bool notify_dbus = false;
3367
3368         assert(u);
3369
3370         log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT" (%s...)",
3371                        u->id, pid, tags && *tags ? tags[0] : "(empty)");
3372
3373         if (s->notify_access == NOTIFY_NONE) {
3374                 log_warning_unit(u->id,
3375                                  "%s: Got notification message from PID "PID_FMT", but reception is disabled.",
3376                                  u->id, pid);
3377                 return;
3378         }
3379
3380         if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3381
3382                 if (s->main_pid != 0)
3383                         log_warning_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, u->id, pid, s->main_pid);
3384                 else
3385                         log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", u->id, pid);
3386                 return;
3387         }
3388
3389         /* Interpret MAINPID= */
3390         if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3391             (s->state == SERVICE_START ||
3392              s->state == SERVICE_START_POST ||
3393              s->state == SERVICE_RUNNING ||
3394              s->state == SERVICE_RELOAD)) {
3395
3396                 if (parse_pid(e + 8, &pid) < 0)
3397                         log_warning_unit(u->id, "Failed to parse notification message %s", e);
3398                 else {
3399                         log_debug_unit(u->id, "%s: got %s", u->id, e);
3400                         service_set_main_pid(s, pid);
3401                         unit_watch_pid(UNIT(s), pid);
3402                         notify_dbus = true;
3403                 }
3404         }
3405
3406         /* Interpret READY= */
3407         if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START && strv_find(tags, "READY=1")) {
3408                 log_debug_unit(u->id, "%s: got READY=1", u->id);
3409                 service_enter_start_post(s);
3410                 notify_dbus = true;
3411         }
3412
3413         /* Interpret STATUS= */
3414         e = strv_find_prefix(tags, "STATUS=");
3415         if (e) {
3416                 char *t;
3417
3418                 if (e[7]) {
3419                         if (!utf8_is_valid(e+7)) {
3420                                 log_warning_unit(u->id, "Status message in notification is not UTF-8 clean.");
3421                                 return;
3422                         }
3423
3424                         log_debug_unit(u->id, "%s: got %s", u->id, e);
3425
3426                         t = strdup(e+7);
3427                         if (!t) {
3428                                 log_oom();
3429                                 return;
3430                         }
3431
3432                 } else
3433                         t = NULL;
3434
3435                 if (!streq_ptr(s->status_text, t)) {
3436                         free(s->status_text);
3437                         s->status_text = t;
3438                         notify_dbus = true;
3439                 } else
3440                         free(t);
3441         }
3442
3443         /* Interpret WATCHDOG= */
3444         if (strv_find(tags, "WATCHDOG=1")) {
3445                 log_debug_unit(u->id, "%s: got WATCHDOG=1", u->id);
3446                 service_reset_watchdog(s);
3447         }
3448
3449         /* Notify clients about changed status or main pid */
3450         if (notify_dbus)
3451                 unit_add_to_dbus_queue(u);
3452 }
3453
3454 static int service_get_timeout(Unit *u, uint64_t *timeout) {
3455         Service *s = SERVICE(u);
3456         int r;
3457
3458         if (!s->timer_event_source)
3459                 return 0;
3460
3461         r = sd_event_source_get_time(s->timer_event_source, timeout);
3462         if (r < 0)
3463                 return r;
3464
3465         return 1;
3466 }
3467
3468 #ifdef HAVE_SYSV_COMPAT
3469
3470 static int service_enumerate(Manager *m) {
3471         char **p;
3472         unsigned i;
3473         _cleanup_closedir_ DIR *d = NULL;
3474         _cleanup_free_ char *path = NULL, *fpath = NULL, *name = NULL;
3475         Set *runlevel_services[ELEMENTSOF(rcnd_table)] = {};
3476         _cleanup_set_free_ Set *shutdown_services = NULL;
3477         Unit *service;
3478         Iterator j;
3479         int r;
3480
3481         assert(m);
3482
3483         if (m->running_as != SYSTEMD_SYSTEM)
3484                 return 0;
3485
3486         STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3487                 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3488                         struct dirent *de;
3489
3490                         free(path);
3491                         path = strjoin(*p, "/", rcnd_table[i].path, NULL);
3492                         if (!path) {
3493                                 r = -ENOMEM;
3494                                 goto finish;
3495                         }
3496
3497                         if (d)
3498                                 closedir(d);
3499
3500                         d = opendir(path);
3501                         if (!d) {
3502                                 if (errno != ENOENT)
3503                                         log_warning("opendir(%s) failed: %m", path);
3504
3505                                 continue;
3506                         }
3507
3508                         while ((de = readdir(d))) {
3509                                 int a, b;
3510
3511                                 if (ignore_file(de->d_name))
3512                                         continue;
3513
3514                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3515                                         continue;
3516
3517                                 if (strlen(de->d_name) < 4)
3518                                         continue;
3519
3520                                 a = undecchar(de->d_name[1]);
3521                                 b = undecchar(de->d_name[2]);
3522
3523                                 if (a < 0 || b < 0)
3524                                         continue;
3525
3526                                 free(fpath);
3527                                 fpath = strjoin(path, "/", de->d_name, NULL);
3528                                 if (!fpath) {
3529                                         r = -ENOMEM;
3530                                         goto finish;
3531                                 }
3532
3533                                 if (access(fpath, X_OK) < 0) {
3534
3535                                         if (errno != ENOENT)
3536                                                 log_warning("access() failed on %s: %m", fpath);
3537
3538                                         continue;
3539                                 }
3540
3541                                 free(name);
3542                                 name = sysv_translate_name(de->d_name + 3);
3543                                 if (!name) {
3544                                         r = log_oom();
3545                                         goto finish;
3546                                 }
3547
3548                                 r = manager_load_unit_prepare(m, name, NULL, NULL, &service);
3549                                 if (r < 0) {
3550                                         log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3551                                         continue;
3552                                 }
3553
3554                                 if (de->d_name[0] == 'S')  {
3555
3556                                         if (rcnd_table[i].type == RUNLEVEL_UP) {
3557                                                 SERVICE(service)->sysv_start_priority_from_rcnd =
3558                                                         MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3559
3560                                                 SERVICE(service)->sysv_enabled = true;
3561                                         }
3562
3563                                         r = set_ensure_allocated(&runlevel_services[i],
3564                                                                  trivial_hash_func, trivial_compare_func);
3565                                         if (r < 0)
3566                                                 goto finish;
3567
3568                                         r = set_put(runlevel_services[i], service);
3569                                         if (r < 0)
3570                                                 goto finish;
3571
3572                                 } else if (de->d_name[0] == 'K' &&
3573                                            (rcnd_table[i].type == RUNLEVEL_DOWN)) {
3574
3575                                         r = set_ensure_allocated(&shutdown_services,
3576                                                                  trivial_hash_func, trivial_compare_func);
3577                                         if (r < 0)
3578                                                 goto finish;
3579
3580                                         r = set_put(shutdown_services, service);
3581                                         if (r < 0)
3582                                                 goto finish;
3583                                 }
3584                         }
3585                 }
3586
3587         /* Now we loaded all stubs and are aware of the lowest
3588         start-up priority for all services, not let's actually load
3589         the services, this will also tell us which services are
3590         actually native now */
3591         manager_dispatch_load_queue(m);
3592
3593         /* If this is a native service, rely on native ways to pull in
3594          * a service, don't pull it in via sysv rcN.d links. */
3595         for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3596                 SET_FOREACH(service, runlevel_services[i], j) {
3597                         service = unit_follow_merge(service);
3598
3599                         if (service->fragment_path)
3600                                 continue;
3601
3602                         r = unit_add_two_dependencies_by_name_inverse(
3603                                 service, UNIT_AFTER, UNIT_WANTS,
3604                                 rcnd_table[i].target, NULL, true);
3605                         if (r < 0)
3606                                 goto finish;
3607                 }
3608
3609         /* We honour K links only for halt/reboot. For the normal
3610          * runlevels we assume the stop jobs will be implicitly added
3611          * by the core logic. Also, we don't really distinguish here
3612          * between the runlevels 0 and 6 and just add them to the
3613          * special shutdown target. */
3614         SET_FOREACH(service, shutdown_services, j) {
3615                 service = unit_follow_merge(service);
3616
3617                 if (service->fragment_path)
3618                         continue;
3619
3620                 r = unit_add_two_dependencies_by_name(
3621                         service, UNIT_BEFORE, UNIT_CONFLICTS,
3622                         SPECIAL_SHUTDOWN_TARGET, NULL, true);
3623                 if (r < 0)
3624                         goto finish;
3625         }
3626
3627         r = 0;
3628
3629 finish:
3630
3631         for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3632                 set_free(runlevel_services[i]);
3633
3634         return r;
3635 }
3636 #endif
3637
3638 static void service_bus_name_owner_change(
3639                 Unit *u,
3640                 const char *name,
3641                 const char *old_owner,
3642                 const char *new_owner) {
3643
3644         Service *s = SERVICE(u);
3645         int r;
3646
3647         assert(s);
3648         assert(name);
3649
3650         assert(streq(s->bus_name, name));
3651         assert(old_owner || new_owner);
3652
3653         if (old_owner && new_owner)
3654                 log_debug_unit(u->id,
3655                                "%s's D-Bus name %s changed owner from %s to %s",
3656                                u->id, name, old_owner, new_owner);
3657         else if (old_owner)
3658                 log_debug_unit(u->id,
3659                                "%s's D-Bus name %s no longer registered by %s",
3660                                u->id, name, old_owner);
3661         else
3662                 log_debug_unit(u->id,
3663                                "%s's D-Bus name %s now registered by %s",
3664                                u->id, name, new_owner);
3665
3666         s->bus_name_good = !!new_owner;
3667
3668         if (s->type == SERVICE_DBUS) {
3669
3670                 /* service_enter_running() will figure out what to
3671                  * do */
3672                 if (s->state == SERVICE_RUNNING)
3673                         service_enter_running(s, SERVICE_SUCCESS);
3674                 else if (s->state == SERVICE_START && new_owner)
3675                         service_enter_start_post(s);
3676
3677         } else if (new_owner &&
3678                    s->main_pid <= 0 &&
3679                    (s->state == SERVICE_START ||
3680                     s->state == SERVICE_START_POST ||
3681                     s->state == SERVICE_RUNNING ||
3682                     s->state == SERVICE_RELOAD)) {
3683
3684                 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
3685                 pid_t pid;
3686
3687                 /* Try to acquire PID from bus service */
3688
3689                 r = sd_bus_get_owner(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
3690                 if (r >= 0)
3691                         r = sd_bus_creds_get_pid(creds, &pid);
3692                 if (r >= 0) {
3693                         log_debug_unit(u->id, "%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
3694
3695                         service_set_main_pid(s, pid);
3696                         unit_watch_pid(UNIT(s), pid);
3697                 }
3698         }
3699 }
3700
3701 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3702         _cleanup_free_ char *peer = NULL;
3703         int r;
3704
3705         assert(s);
3706         assert(fd >= 0);
3707
3708         /* This is called by the socket code when instantiating a new
3709          * service for a stream socket and the socket needs to be
3710          * configured. */
3711
3712         if (UNIT(s)->load_state != UNIT_LOADED)
3713                 return -EINVAL;
3714
3715         if (s->socket_fd >= 0)
3716                 return -EBUSY;
3717
3718         if (s->state != SERVICE_DEAD)
3719                 return -EAGAIN;
3720
3721         if (getpeername_pretty(fd, &peer) >= 0) {
3722
3723                 if (UNIT(s)->description) {
3724                         _cleanup_free_ char *a;
3725
3726                         a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
3727                         if (!a)
3728                                 return -ENOMEM;
3729
3730                         r = unit_set_description(UNIT(s), a);
3731                 }  else
3732                         r = unit_set_description(UNIT(s), peer);
3733
3734                 if (r < 0)
3735                         return r;
3736         }
3737
3738         s->socket_fd = fd;
3739
3740         unit_ref_set(&s->accept_socket, UNIT(sock));
3741
3742         return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3743 }
3744
3745 static void service_reset_failed(Unit *u) {
3746         Service *s = SERVICE(u);
3747
3748         assert(s);
3749
3750         if (s->state == SERVICE_FAILED)
3751                 service_set_state(s, SERVICE_DEAD);
3752
3753         s->result = SERVICE_SUCCESS;
3754         s->reload_result = SERVICE_SUCCESS;
3755
3756         RATELIMIT_RESET(s->start_limit);
3757 }
3758
3759 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
3760         Service *s = SERVICE(u);
3761
3762         return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
3763 }
3764
3765 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3766         [SERVICE_DEAD] = "dead",
3767         [SERVICE_START_PRE] = "start-pre",
3768         [SERVICE_START] = "start",
3769         [SERVICE_START_POST] = "start-post",
3770         [SERVICE_RUNNING] = "running",
3771         [SERVICE_EXITED] = "exited",
3772         [SERVICE_RELOAD] = "reload",
3773         [SERVICE_STOP] = "stop",
3774         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3775         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3776         [SERVICE_STOP_POST] = "stop-post",
3777         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3778         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3779         [SERVICE_FAILED] = "failed",
3780         [SERVICE_AUTO_RESTART] = "auto-restart",
3781 };
3782
3783 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3784
3785 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3786         [SERVICE_RESTART_NO] = "no",
3787         [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3788         [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3789         [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
3790         [SERVICE_RESTART_ON_ABORT] = "on-abort",
3791         [SERVICE_RESTART_ALWAYS] = "always"
3792 };
3793
3794 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3795
3796 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3797         [SERVICE_SIMPLE] = "simple",
3798         [SERVICE_FORKING] = "forking",
3799         [SERVICE_ONESHOT] = "oneshot",
3800         [SERVICE_DBUS] = "dbus",
3801         [SERVICE_NOTIFY] = "notify",
3802         [SERVICE_IDLE] = "idle"
3803 };
3804
3805 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3806
3807 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3808         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3809         [SERVICE_EXEC_START] = "ExecStart",
3810         [SERVICE_EXEC_START_POST] = "ExecStartPost",
3811         [SERVICE_EXEC_RELOAD] = "ExecReload",
3812         [SERVICE_EXEC_STOP] = "ExecStop",
3813         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3814 };
3815
3816 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3817
3818 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3819         [NOTIFY_NONE] = "none",
3820         [NOTIFY_MAIN] = "main",
3821         [NOTIFY_ALL] = "all"
3822 };
3823
3824 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3825
3826 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3827         [SERVICE_SUCCESS] = "success",
3828         [SERVICE_FAILURE_RESOURCES] = "resources",
3829         [SERVICE_FAILURE_TIMEOUT] = "timeout",
3830         [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3831         [SERVICE_FAILURE_SIGNAL] = "signal",
3832         [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3833         [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3834         [SERVICE_FAILURE_START_LIMIT] = "start-limit"
3835 };
3836
3837 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3838
3839 static const char* const failure_action_table[_SERVICE_FAILURE_ACTION_MAX] = {
3840         [SERVICE_FAILURE_ACTION_NONE] = "none",
3841         [SERVICE_FAILURE_ACTION_REBOOT] = "reboot",
3842         [SERVICE_FAILURE_ACTION_REBOOT_FORCE] = "reboot-force",
3843         [SERVICE_FAILURE_ACTION_REBOOT_IMMEDIATE] = "reboot-immediate"
3844 };
3845 DEFINE_STRING_TABLE_LOOKUP(failure_action, FailureAction);
3846
3847 const UnitVTable service_vtable = {
3848         .object_size = sizeof(Service),
3849         .exec_context_offset = offsetof(Service, exec_context),
3850         .cgroup_context_offset = offsetof(Service, cgroup_context),
3851         .kill_context_offset = offsetof(Service, kill_context),
3852         .exec_runtime_offset = offsetof(Service, exec_runtime),
3853
3854         .sections =
3855                 "Unit\0"
3856                 "Service\0"
3857                 "Install\0",
3858         .private_section = "Service",
3859
3860         .init = service_init,
3861         .done = service_done,
3862         .load = service_load,
3863
3864         .coldplug = service_coldplug,
3865
3866         .dump = service_dump,
3867
3868         .start = service_start,
3869         .stop = service_stop,
3870         .reload = service_reload,
3871
3872         .can_reload = service_can_reload,
3873
3874         .kill = service_kill,
3875
3876         .serialize = service_serialize,
3877         .deserialize_item = service_deserialize_item,
3878
3879         .active_state = service_active_state,
3880         .sub_state_to_string = service_sub_state_to_string,
3881
3882         .check_gc = service_check_gc,
3883         .check_snapshot = service_check_snapshot,
3884
3885         .sigchld_event = service_sigchld_event,
3886
3887         .reset_failed = service_reset_failed,
3888
3889         .notify_cgroup_empty = service_notify_cgroup_empty_event,
3890         .notify_message = service_notify_message,
3891
3892         .bus_name_owner_change = service_bus_name_owner_change,
3893
3894         .bus_interface = "org.freedesktop.systemd1.Service",
3895         .bus_vtable = bus_service_vtable,
3896         .bus_set_property = bus_service_set_property,
3897         .bus_commit_properties = bus_service_commit_properties,
3898
3899         .get_timeout = service_get_timeout,
3900
3901 #ifdef HAVE_SYSV_COMPAT
3902         .enumerate = service_enumerate,
3903 #endif
3904
3905         .can_transient = true,
3906
3907         .status_message_formats = {
3908                 .starting_stopping = {
3909                         [0] = "Starting %s...",
3910                         [1] = "Stopping %s...",
3911                 },
3912                 .finished_start_job = {
3913                         [JOB_DONE]       = "Started %s.",
3914                         [JOB_FAILED]     = "Failed to start %s.",
3915                         [JOB_DEPENDENCY] = "Dependency failed for %s.",
3916                         [JOB_TIMEOUT]    = "Timed out starting %s.",
3917                 },
3918                 .finished_stop_job = {
3919                         [JOB_DONE]       = "Stopped %s.",
3920                         [JOB_FAILED]     = "Stopped (with error) %s.",
3921                         [JOB_TIMEOUT]    = "Timed out stopping %s.",
3922                 },
3923         },
3924 };