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