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