chiark / gitweb /
8941271679adde950d7471d5b854cc46b254b614
[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
932         if (UNIT(s)->manager->sysv_console)
933                 s->exec_context.std_output = EXEC_OUTPUT_JOURNAL_AND_CONSOLE;
934
935         s->exec_context.kill_mode = KILL_PROCESS;
936
937         /* We use the long description only if
938          * no short description is set. */
939
940         if (short_description)
941                 description = short_description;
942         else if (chkconfig_description)
943                 description = chkconfig_description;
944         else if (long_description)
945                 description = long_description;
946         else
947                 description = NULL;
948
949         if (description) {
950                 char *d;
951
952                 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
953                         r = -ENOMEM;
954                         goto finish;
955                 }
956
957                 u->description = d;
958         }
959
960         /* The priority that has been set in /etc/rcN.d/ hierarchies
961          * takes precedence over what is stored as default in the LSB
962          * header */
963         if (s->sysv_start_priority_from_rcnd >= 0)
964                 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
965
966         u->load_state = UNIT_LOADED;
967         r = 0;
968
969 finish:
970
971         if (f)
972                 fclose(f);
973
974         free(short_description);
975         free(long_description);
976         free(chkconfig_description);
977
978         return r;
979 }
980
981 static int service_load_sysv_name(Service *s, const char *name) {
982         char **p;
983
984         assert(s);
985         assert(name);
986
987         /* For SysV services we strip the boot.*, rc.* and *.sh
988          * prefixes/suffixes. */
989 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
990         if (endswith(name, ".sh.service"))
991                 return -ENOENT;
992 #endif
993
994 #ifdef TARGET_SUSE
995         if (startswith(name, "boot."))
996                 return -ENOENT;
997 #endif
998
999 #ifdef TARGET_FRUGALWARE
1000         if (startswith(name, "rc."))
1001                 return -ENOENT;
1002 #endif
1003
1004         STRV_FOREACH(p, UNIT(s)->manager->lookup_paths.sysvinit_path) {
1005                 char *path;
1006                 int r;
1007
1008                 path = join(*p, "/", name, NULL);
1009                 if (!path)
1010                         return -ENOMEM;
1011
1012                 assert(endswith(path, ".service"));
1013                 path[strlen(path)-8] = 0;
1014
1015                 r = service_load_sysv_path(s, path);
1016
1017 #if defined(TARGET_DEBIAN) || defined(TARGET_UBUNTU) || defined(TARGET_ANGSTROM)
1018                 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
1019                         /* Try Debian style *.sh source'able init scripts */
1020                         strcat(path, ".sh");
1021                         r = service_load_sysv_path(s, path);
1022                 }
1023 #endif
1024                 free(path);
1025
1026 #ifdef TARGET_SUSE
1027                 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
1028                         /* Try SUSE style boot.* init scripts */
1029
1030                         path = join(*p, "/boot.", name, NULL);
1031                         if (!path)
1032                                 return -ENOMEM;
1033
1034                         /* Drop .service suffix */
1035                         path[strlen(path)-8] = 0;
1036                         r = service_load_sysv_path(s, path);
1037                         free(path);
1038                 }
1039 #endif
1040
1041 #ifdef TARGET_FRUGALWARE
1042                 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
1043                         /* Try Frugalware style rc.* init scripts */
1044
1045                         path = join(*p, "/rc.", name, NULL);
1046                         if (!path)
1047                                 return -ENOMEM;
1048
1049                         /* Drop .service suffix */
1050                         path[strlen(path)-8] = 0;
1051                         r = service_load_sysv_path(s, path);
1052                         free(path);
1053                 }
1054 #endif
1055
1056                 if (r < 0)
1057                         return r;
1058
1059                 if ((UNIT(s)->load_state != UNIT_STUB))
1060                         break;
1061         }
1062
1063         return 0;
1064 }
1065
1066 static int service_load_sysv(Service *s) {
1067         const char *t;
1068         Iterator i;
1069         int r;
1070
1071         assert(s);
1072
1073         /* Load service data from SysV init scripts, preferably with
1074          * LSB headers ... */
1075
1076         if (strv_isempty(UNIT(s)->manager->lookup_paths.sysvinit_path))
1077                 return 0;
1078
1079         if ((t = UNIT(s)->id))
1080                 if ((r = service_load_sysv_name(s, t)) < 0)
1081                         return r;
1082
1083         if (UNIT(s)->load_state == UNIT_STUB)
1084                 SET_FOREACH(t, UNIT(s)->names, i) {
1085                         if (t == UNIT(s)->id)
1086                                 continue;
1087
1088                         if ((r = service_load_sysv_name(s, t)) < 0)
1089                                 return r;
1090
1091                         if (UNIT(s)->load_state != UNIT_STUB)
1092                                 break;
1093                 }
1094
1095         return 0;
1096 }
1097 #endif
1098
1099 static int fsck_fix_order(Service *s) {
1100         Unit *other;
1101         int r;
1102
1103         assert(s);
1104
1105         if (s->fsck_passno <= 0)
1106                 return 0;
1107
1108         /* For each pair of services where both have an fsck priority
1109          * we order things based on it. */
1110
1111         LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
1112                 Service *t;
1113                 UnitDependency d;
1114
1115                 t = SERVICE(other);
1116
1117                 if (s == t)
1118                         continue;
1119
1120                 if (UNIT(t)->load_state != UNIT_LOADED)
1121                         continue;
1122
1123                 if (t->fsck_passno <= 0)
1124                         continue;
1125
1126                 if (t->fsck_passno < s->fsck_passno)
1127                         d = UNIT_AFTER;
1128                 else if (t->fsck_passno > s->fsck_passno)
1129                         d = UNIT_BEFORE;
1130                 else
1131                         continue;
1132
1133                 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1134                         return r;
1135         }
1136
1137         return 0;
1138 }
1139
1140 static int service_verify(Service *s) {
1141         assert(s);
1142
1143         if (UNIT(s)->load_state != UNIT_LOADED)
1144                 return 0;
1145
1146         if (!s->exec_command[SERVICE_EXEC_START]) {
1147                 log_error("%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
1148                 return -EINVAL;
1149         }
1150
1151         if (s->type != SERVICE_ONESHOT &&
1152             s->exec_command[SERVICE_EXEC_START]->command_next) {
1153                 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1154                 return -EINVAL;
1155         }
1156
1157         if (s->type == SERVICE_ONESHOT &&
1158             s->exec_command[SERVICE_EXEC_RELOAD]) {
1159                 log_error("%s has an ExecReload setting, which is not allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1160                 return -EINVAL;
1161         }
1162
1163         if (s->type == SERVICE_DBUS && !s->bus_name) {
1164                 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
1165                 return -EINVAL;
1166         }
1167
1168         if (s->bus_name && s->type != SERVICE_DBUS)
1169                 log_warning("%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
1170
1171         if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
1172                 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
1173                 return -EINVAL;
1174         }
1175
1176         return 0;
1177 }
1178
1179 static int service_add_default_dependencies(Service *s) {
1180         int r;
1181
1182         assert(s);
1183
1184         /* Add a number of automatic dependencies useful for the
1185          * majority of services. */
1186
1187         /* First, pull in base system */
1188         if (UNIT(s)->manager->running_as == MANAGER_SYSTEM) {
1189
1190                 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1191                         return r;
1192
1193         } else if (UNIT(s)->manager->running_as == MANAGER_USER) {
1194
1195                 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1196                         return r;
1197         }
1198
1199         /* Second, activate normal shutdown */
1200         return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1201 }
1202
1203 static void service_fix_output(Service *s) {
1204         assert(s);
1205
1206         /* If nothing has been explicitly configured, patch default
1207          * output in. If input is socket/tty we avoid this however,
1208          * since in that case we want output to default to the same
1209          * place as we read input from. */
1210
1211         if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1212             s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1213             s->exec_context.std_input == EXEC_INPUT_NULL)
1214                 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
1215
1216         if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1217             s->exec_context.std_input == EXEC_INPUT_NULL)
1218                 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
1219 }
1220
1221 static int service_load(Unit *u) {
1222         int r;
1223         Service *s = SERVICE(u);
1224
1225         assert(s);
1226
1227         /* Load a .service file */
1228         if ((r = unit_load_fragment(u)) < 0)
1229                 return r;
1230
1231 #ifdef HAVE_SYSV_COMPAT
1232         /* Load a classic init script as a fallback, if we couldn't find anything */
1233         if (u->load_state == UNIT_STUB)
1234                 if ((r = service_load_sysv(s)) < 0)
1235                         return r;
1236 #endif
1237
1238         /* Still nothing found? Then let's give up */
1239         if (u->load_state == UNIT_STUB)
1240                 return -ENOENT;
1241
1242         /* We were able to load something, then let's add in the
1243          * dropin directories. */
1244         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1245                 return r;
1246
1247         /* This is a new unit? Then let's add in some extras */
1248         if (u->load_state == UNIT_LOADED) {
1249                 if (s->type == _SERVICE_TYPE_INVALID)
1250                         s->type = s->bus_name ? SERVICE_DBUS : SERVICE_SIMPLE;
1251
1252                 /* Oneshot services have disabled timeout by default */
1253                 if (s->type == SERVICE_ONESHOT && !s->timeout_defined)
1254                         s->timeout_usec = 0;
1255
1256                 service_fix_output(s);
1257
1258                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1259                         return r;
1260
1261                 if ((r = unit_add_default_cgroups(u)) < 0)
1262                         return r;
1263
1264 #ifdef HAVE_SYSV_COMPAT
1265                 if ((r = sysv_fix_order(s)) < 0)
1266                         return r;
1267 #endif
1268
1269                 if ((r = fsck_fix_order(s)) < 0)
1270                         return r;
1271
1272                 if (s->bus_name)
1273                         if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1274                                 return r;
1275
1276                 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1277                         s->notify_access = NOTIFY_MAIN;
1278
1279                 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
1280                         s->notify_access = NOTIFY_MAIN;
1281
1282                 if (s->type == SERVICE_DBUS || s->bus_name)
1283                         if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1284                                 return r;
1285
1286                 if (UNIT(s)->default_dependencies)
1287                         if ((r = service_add_default_dependencies(s)) < 0)
1288                                 return r;
1289         }
1290
1291         return service_verify(s);
1292 }
1293
1294 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1295
1296         ServiceExecCommand c;
1297         Service *s = SERVICE(u);
1298         const char *prefix2;
1299         char *p2;
1300
1301         assert(s);
1302
1303         p2 = strappend(prefix, "\t");
1304         prefix2 = p2 ? p2 : prefix;
1305
1306         fprintf(f,
1307                 "%sService State: %s\n"
1308                 "%sResult: %s\n"
1309                 "%sReload Result: %s\n"
1310                 "%sPermissionsStartOnly: %s\n"
1311                 "%sRootDirectoryStartOnly: %s\n"
1312                 "%sRemainAfterExit: %s\n"
1313                 "%sGuessMainPID: %s\n"
1314                 "%sType: %s\n"
1315                 "%sRestart: %s\n"
1316                 "%sNotifyAccess: %s\n",
1317                 prefix, service_state_to_string(s->state),
1318                 prefix, service_result_to_string(s->result),
1319                 prefix, service_result_to_string(s->reload_result),
1320                 prefix, yes_no(s->permissions_start_only),
1321                 prefix, yes_no(s->root_directory_start_only),
1322                 prefix, yes_no(s->remain_after_exit),
1323                 prefix, yes_no(s->guess_main_pid),
1324                 prefix, service_type_to_string(s->type),
1325                 prefix, service_restart_to_string(s->restart),
1326                 prefix, notify_access_to_string(s->notify_access));
1327
1328         if (s->control_pid > 0)
1329                 fprintf(f,
1330                         "%sControl PID: %lu\n",
1331                         prefix, (unsigned long) s->control_pid);
1332
1333         if (s->main_pid > 0)
1334                 fprintf(f,
1335                         "%sMain PID: %lu\n"
1336                         "%sMain PID Known: %s\n"
1337                         "%sMain PID Alien: %s\n",
1338                         prefix, (unsigned long) s->main_pid,
1339                         prefix, yes_no(s->main_pid_known),
1340                         prefix, yes_no(s->main_pid_alien));
1341
1342         if (s->pid_file)
1343                 fprintf(f,
1344                         "%sPIDFile: %s\n",
1345                         prefix, s->pid_file);
1346
1347         if (s->bus_name)
1348                 fprintf(f,
1349                         "%sBusName: %s\n"
1350                         "%sBus Name Good: %s\n",
1351                         prefix, s->bus_name,
1352                         prefix, yes_no(s->bus_name_good));
1353
1354         exec_context_dump(&s->exec_context, f, prefix);
1355
1356         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1357
1358                 if (!s->exec_command[c])
1359                         continue;
1360
1361                 fprintf(f, "%s-> %s:\n",
1362                         prefix, service_exec_command_to_string(c));
1363
1364                 exec_command_dump_list(s->exec_command[c], f, prefix2);
1365         }
1366
1367 #ifdef HAVE_SYSV_COMPAT
1368         if (s->is_sysv)
1369                 fprintf(f,
1370                         "%sSysV Init Script has LSB Header: %s\n"
1371                         "%sSysVEnabled: %s\n",
1372                         prefix, yes_no(s->sysv_has_lsb),
1373                         prefix, yes_no(s->sysv_enabled));
1374
1375         if (s->sysv_start_priority >= 0)
1376                 fprintf(f,
1377                         "%sSysVStartPriority: %i\n",
1378                         prefix, s->sysv_start_priority);
1379
1380         if (s->sysv_runlevels)
1381                 fprintf(f, "%sSysVRunLevels: %s\n",
1382                         prefix, s->sysv_runlevels);
1383 #endif
1384
1385         if (s->fsck_passno > 0)
1386                 fprintf(f,
1387                         "%sFsckPassNo: %i\n",
1388                         prefix, s->fsck_passno);
1389
1390         if (s->status_text)
1391                 fprintf(f, "%sStatus Text: %s\n",
1392                         prefix, s->status_text);
1393
1394         free(p2);
1395 }
1396
1397 static int service_load_pid_file(Service *s, bool may_warn) {
1398         char *k;
1399         int r;
1400         pid_t pid;
1401
1402         assert(s);
1403
1404         if (!s->pid_file)
1405                 return -ENOENT;
1406
1407         if ((r = read_one_line_file(s->pid_file, &k)) < 0) {
1408                 if (may_warn)
1409                         log_info("PID file %s not readable (yet?) after %s.",
1410                                  s->pid_file, service_state_to_string(s->state));
1411                 return r;
1412         }
1413
1414         r = parse_pid(k, &pid);
1415         free(k);
1416
1417         if (r < 0)
1418                 return r;
1419
1420         if (kill(pid, 0) < 0 && errno != EPERM) {
1421                 if (may_warn)
1422                         log_info("PID %lu read from file %s does not exist.",
1423                                  (unsigned long) pid, s->pid_file);
1424                 return -ESRCH;
1425         }
1426
1427         if (s->main_pid_known) {
1428                 if (pid == s->main_pid)
1429                         return 0;
1430
1431                 log_debug("Main PID changing: %lu -> %lu",
1432                           (unsigned long) s->main_pid, (unsigned long) pid);
1433                 service_unwatch_main_pid(s);
1434                 s->main_pid_known = false;
1435         } else
1436                 log_debug("Main PID loaded: %lu", (unsigned long) pid);
1437
1438         if ((r = service_set_main_pid(s, pid)) < 0)
1439                 return r;
1440
1441         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1442                 /* FIXME: we need to do something here */
1443                 return r;
1444
1445         return 0;
1446 }
1447
1448 static int service_search_main_pid(Service *s) {
1449         pid_t pid;
1450         int r;
1451
1452         assert(s);
1453
1454         /* If we know it anyway, don't ever fallback to unreliable
1455          * heuristics */
1456         if (s->main_pid_known)
1457                 return 0;
1458
1459         if (!s->guess_main_pid)
1460                 return 0;
1461
1462         assert(s->main_pid <= 0);
1463
1464         if ((pid = cgroup_bonding_search_main_pid_list(UNIT(s)->cgroup_bondings)) <= 0)
1465                 return -ENOENT;
1466
1467         log_debug("Main PID guessed: %lu", (unsigned long) pid);
1468         if ((r = service_set_main_pid(s, pid)) < 0)
1469                 return r;
1470
1471         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1472                 /* FIXME: we need to do something here */
1473                 return r;
1474
1475         return 0;
1476 }
1477
1478 static void service_notify_sockets_dead(Service *s, bool failed_permanent) {
1479         Iterator i;
1480         Unit *u;
1481
1482         assert(s);
1483
1484         /* Notifies all our sockets when we die */
1485
1486         if (s->socket_fd >= 0)
1487                 return;
1488
1489         SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i)
1490                 if (u->type == UNIT_SOCKET)
1491                         socket_notify_service_dead(SOCKET(u), failed_permanent);
1492
1493         return;
1494 }
1495
1496 static void service_set_state(Service *s, ServiceState state) {
1497         ServiceState old_state;
1498         const UnitActiveState *table;
1499         assert(s);
1500
1501         table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1502
1503         old_state = s->state;
1504         s->state = state;
1505
1506         service_unwatch_pid_file(s);
1507
1508         if (state != SERVICE_START_PRE &&
1509             state != SERVICE_START &&
1510             state != SERVICE_START_POST &&
1511             state != SERVICE_RELOAD &&
1512             state != SERVICE_STOP &&
1513             state != SERVICE_STOP_SIGTERM &&
1514             state != SERVICE_STOP_SIGKILL &&
1515             state != SERVICE_STOP_POST &&
1516             state != SERVICE_FINAL_SIGTERM &&
1517             state != SERVICE_FINAL_SIGKILL &&
1518             state != SERVICE_AUTO_RESTART)
1519                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1520
1521         if (state != SERVICE_START &&
1522             state != SERVICE_START_POST &&
1523             state != SERVICE_RUNNING &&
1524             state != SERVICE_RELOAD &&
1525             state != SERVICE_STOP &&
1526             state != SERVICE_STOP_SIGTERM &&
1527             state != SERVICE_STOP_SIGKILL) {
1528                 service_unwatch_main_pid(s);
1529                 s->main_command = NULL;
1530         }
1531
1532         if (state != SERVICE_START_PRE &&
1533             state != SERVICE_START &&
1534             state != SERVICE_START_POST &&
1535             state != SERVICE_RELOAD &&
1536             state != SERVICE_STOP &&
1537             state != SERVICE_STOP_SIGTERM &&
1538             state != SERVICE_STOP_SIGKILL &&
1539             state != SERVICE_STOP_POST &&
1540             state != SERVICE_FINAL_SIGTERM &&
1541             state != SERVICE_FINAL_SIGKILL) {
1542                 service_unwatch_control_pid(s);
1543                 s->control_command = NULL;
1544                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1545         }
1546
1547         if (state == SERVICE_DEAD ||
1548             state == SERVICE_STOP ||
1549             state == SERVICE_STOP_SIGTERM ||
1550             state == SERVICE_STOP_SIGKILL ||
1551             state == SERVICE_STOP_POST ||
1552             state == SERVICE_FINAL_SIGTERM ||
1553             state == SERVICE_FINAL_SIGKILL ||
1554             state == SERVICE_FAILED ||
1555             state == SERVICE_AUTO_RESTART)
1556                 service_notify_sockets_dead(s, false);
1557
1558         if (state != SERVICE_START_PRE &&
1559             state != SERVICE_START &&
1560             state != SERVICE_START_POST &&
1561             state != SERVICE_RUNNING &&
1562             state != SERVICE_RELOAD &&
1563             state != SERVICE_STOP &&
1564             state != SERVICE_STOP_SIGTERM &&
1565             state != SERVICE_STOP_SIGKILL &&
1566             state != SERVICE_STOP_POST &&
1567             state != SERVICE_FINAL_SIGTERM &&
1568             state != SERVICE_FINAL_SIGKILL &&
1569             !(state == SERVICE_DEAD && UNIT(s)->job)) {
1570                 service_close_socket_fd(s);
1571                 service_connection_unref(s);
1572         }
1573
1574         if (state == SERVICE_STOP)
1575                 service_stop_watchdog(s);
1576
1577         /* For the inactive states unit_notify() will trim the cgroup,
1578          * but for exit we have to do that ourselves... */
1579         if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
1580                 cgroup_bonding_trim_list(UNIT(s)->cgroup_bondings, true);
1581
1582         if (old_state != state)
1583                 log_debug("%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
1584
1585         unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
1586         s->reload_result = SERVICE_SUCCESS;
1587 }
1588
1589 static int service_coldplug(Unit *u) {
1590         Service *s = SERVICE(u);
1591         int r;
1592
1593         assert(s);
1594         assert(s->state == SERVICE_DEAD);
1595
1596         if (s->deserialized_state != s->state) {
1597
1598                 if (s->deserialized_state == SERVICE_START_PRE ||
1599                     s->deserialized_state == SERVICE_START ||
1600                     s->deserialized_state == SERVICE_START_POST ||
1601                     s->deserialized_state == SERVICE_RELOAD ||
1602                     s->deserialized_state == SERVICE_STOP ||
1603                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1604                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1605                     s->deserialized_state == SERVICE_STOP_POST ||
1606                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1607                     s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1608                     s->deserialized_state == SERVICE_AUTO_RESTART) {
1609
1610                         if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1611                                 usec_t k;
1612
1613                                 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1614
1615                                 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1616                                         return r;
1617                         }
1618                 }
1619
1620                 if ((s->deserialized_state == SERVICE_START &&
1621                      (s->type == SERVICE_FORKING ||
1622                       s->type == SERVICE_DBUS ||
1623                       s->type == SERVICE_ONESHOT ||
1624                       s->type == SERVICE_NOTIFY)) ||
1625                     s->deserialized_state == SERVICE_START_POST ||
1626                     s->deserialized_state == SERVICE_RUNNING ||
1627                     s->deserialized_state == SERVICE_RELOAD ||
1628                     s->deserialized_state == SERVICE_STOP ||
1629                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1630                     s->deserialized_state == SERVICE_STOP_SIGKILL)
1631                         if (s->main_pid > 0)
1632                                 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1633                                         return r;
1634
1635                 if (s->deserialized_state == SERVICE_START_PRE ||
1636                     s->deserialized_state == SERVICE_START ||
1637                     s->deserialized_state == SERVICE_START_POST ||
1638                     s->deserialized_state == SERVICE_RELOAD ||
1639                     s->deserialized_state == SERVICE_STOP ||
1640                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1641                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1642                     s->deserialized_state == SERVICE_STOP_POST ||
1643                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1644                     s->deserialized_state == SERVICE_FINAL_SIGKILL)
1645                         if (s->control_pid > 0)
1646                                 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1647                                         return r;
1648
1649                 if (s->deserialized_state == SERVICE_START_POST ||
1650                     s->deserialized_state == SERVICE_RUNNING)
1651                         service_handle_watchdog(s);
1652
1653                 service_set_state(s, s->deserialized_state);
1654         }
1655         return 0;
1656 }
1657
1658 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1659         Iterator i;
1660         int r;
1661         int *rfds = NULL;
1662         unsigned rn_fds = 0;
1663         Unit *u;
1664
1665         assert(s);
1666         assert(fds);
1667         assert(n_fds);
1668
1669         if (s->socket_fd >= 0)
1670                 return 0;
1671
1672         SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1673                 int *cfds;
1674                 unsigned cn_fds;
1675                 Socket *sock;
1676
1677                 if (u->type != UNIT_SOCKET)
1678                         continue;
1679
1680                 sock = SOCKET(u);
1681
1682                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1683                         goto fail;
1684
1685                 if (!cfds)
1686                         continue;
1687
1688                 if (!rfds) {
1689                         rfds = cfds;
1690                         rn_fds = cn_fds;
1691                 } else {
1692                         int *t;
1693
1694                         if (!(t = new(int, rn_fds+cn_fds))) {
1695                                 free(cfds);
1696                                 r = -ENOMEM;
1697                                 goto fail;
1698                         }
1699
1700                         memcpy(t, rfds, rn_fds * sizeof(int));
1701                         memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1702                         free(rfds);
1703                         free(cfds);
1704
1705                         rfds = t;
1706                         rn_fds = rn_fds+cn_fds;
1707                 }
1708         }
1709
1710         *fds = rfds;
1711         *n_fds = rn_fds;
1712
1713         return 0;
1714
1715 fail:
1716         free(rfds);
1717
1718         return r;
1719 }
1720
1721 static int service_spawn(
1722                 Service *s,
1723                 ExecCommand *c,
1724                 bool timeout,
1725                 bool pass_fds,
1726                 bool apply_permissions,
1727                 bool apply_chroot,
1728                 bool apply_tty_stdin,
1729                 bool set_notify_socket,
1730                 bool is_control,
1731                 pid_t *_pid) {
1732
1733         pid_t pid;
1734         int r;
1735         int *fds = NULL, *fdsbuf = NULL;
1736         unsigned n_fds = 0, n_env = 0;
1737         char **argv = NULL, **final_env = NULL, **our_env = NULL;
1738
1739         assert(s);
1740         assert(c);
1741         assert(_pid);
1742
1743         if (pass_fds ||
1744             s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1745             s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1746             s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1747
1748                 if (s->socket_fd >= 0) {
1749                         fds = &s->socket_fd;
1750                         n_fds = 1;
1751                 } else {
1752                         if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1753                                 goto fail;
1754
1755                         fds = fdsbuf;
1756                 }
1757         }
1758
1759         if (timeout && s->timeout_usec) {
1760                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1761                         goto fail;
1762         } else
1763                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1764
1765         if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1766                 r = -ENOMEM;
1767                 goto fail;
1768         }
1769
1770         if (!(our_env = new0(char*, 4))) {
1771                 r = -ENOMEM;
1772                 goto fail;
1773         }
1774
1775         if (set_notify_socket)
1776                 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1777                         r = -ENOMEM;
1778                         goto fail;
1779                 }
1780
1781         if (s->main_pid > 0)
1782                 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1783                         r = -ENOMEM;
1784                         goto fail;
1785                 }
1786
1787         if (s->watchdog_usec > 0)
1788                 if (asprintf(our_env + n_env++, "WATCHDOG_USEC=%llu", (unsigned long long) s->watchdog_usec) < 0) {
1789                         r = -ENOMEM;
1790                         goto fail;
1791                 }
1792
1793         if (!(final_env = strv_env_merge(2,
1794                                          UNIT(s)->manager->environment,
1795                                          our_env,
1796                                          NULL))) {
1797                 r = -ENOMEM;
1798                 goto fail;
1799         }
1800
1801         r = exec_spawn(c,
1802                        argv,
1803                        &s->exec_context,
1804                        fds, n_fds,
1805                        final_env,
1806                        apply_permissions,
1807                        apply_chroot,
1808                        apply_tty_stdin,
1809                        UNIT(s)->manager->confirm_spawn,
1810                        UNIT(s)->cgroup_bondings,
1811                        UNIT(s)->cgroup_attributes,
1812                        is_control ? "control" : NULL,
1813                        s->type == SERVICE_IDLE ? UNIT(s)->manager->idle_pipe : NULL,
1814                        &pid);
1815
1816         if (r < 0)
1817                 goto fail;
1818
1819
1820         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1821                 /* FIXME: we need to do something here */
1822                 goto fail;
1823
1824         free(fdsbuf);
1825         strv_free(argv);
1826         strv_free(our_env);
1827         strv_free(final_env);
1828
1829         *_pid = pid;
1830
1831         return 0;
1832
1833 fail:
1834         free(fdsbuf);
1835         strv_free(argv);
1836         strv_free(our_env);
1837         strv_free(final_env);
1838
1839         if (timeout)
1840                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1841
1842         return r;
1843 }
1844
1845 static int main_pid_good(Service *s) {
1846         assert(s);
1847
1848         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1849          * don't know */
1850
1851         /* If we know the pid file, then lets just check if it is
1852          * still valid */
1853         if (s->main_pid_known) {
1854
1855                 /* If it's an alien child let's check if it is still
1856                  * alive ... */
1857                 if (s->main_pid_alien)
1858                         return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1859
1860                 /* .. otherwise assume we'll get a SIGCHLD for it,
1861                  * which we really should wait for to collect exit
1862                  * status and code */
1863                 return s->main_pid > 0;
1864         }
1865
1866         /* We don't know the pid */
1867         return -EAGAIN;
1868 }
1869
1870 static int control_pid_good(Service *s) {
1871         assert(s);
1872
1873         return s->control_pid > 0;
1874 }
1875
1876 static int cgroup_good(Service *s) {
1877         int r;
1878
1879         assert(s);
1880
1881         if ((r = cgroup_bonding_is_empty_list(UNIT(s)->cgroup_bondings)) < 0)
1882                 return r;
1883
1884         return !r;
1885 }
1886
1887 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1888         int r;
1889         assert(s);
1890
1891         if (f != SERVICE_SUCCESS)
1892                 s->result = f;
1893
1894         if (allow_restart &&
1895             !s->forbid_restart &&
1896             (s->restart == SERVICE_RESTART_ALWAYS ||
1897              (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1898              (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1899              (s->restart == SERVICE_RESTART_ON_ABORT && (s->result == SERVICE_FAILURE_SIGNAL ||
1900                                                          s->result == SERVICE_FAILURE_CORE_DUMP)))) {
1901
1902                 r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch);
1903                 if (r < 0)
1904                         goto fail;
1905
1906                 service_set_state(s, SERVICE_AUTO_RESTART);
1907         } else
1908                 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1909
1910         s->forbid_restart = false;
1911
1912         return;
1913
1914 fail:
1915         log_warning("%s failed to run install restart timer: %s", UNIT(s)->id, strerror(-r));
1916         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1917 }
1918
1919 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
1920
1921 static void service_enter_stop_post(Service *s, ServiceResult f) {
1922         int r;
1923         assert(s);
1924
1925         if (f != SERVICE_SUCCESS)
1926                 s->result = f;
1927
1928         service_unwatch_control_pid(s);
1929
1930         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1931                 s->control_command_id = SERVICE_EXEC_STOP_POST;
1932
1933                 r = service_spawn(s,
1934                                   s->control_command,
1935                                   true,
1936                                   false,
1937                                   !s->permissions_start_only,
1938                                   !s->root_directory_start_only,
1939                                   true,
1940                                   false,
1941                                   true,
1942                                   &s->control_pid);
1943                 if (r < 0)
1944                         goto fail;
1945
1946
1947                 service_set_state(s, SERVICE_STOP_POST);
1948         } else
1949                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1950
1951         return;
1952
1953 fail:
1954         log_warning("%s failed to run 'stop-post' task: %s", UNIT(s)->id, strerror(-r));
1955         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1956 }
1957
1958 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1959         int r;
1960         Set *pid_set = NULL;
1961         bool wait_for_exit = false;
1962
1963         assert(s);
1964
1965         if (f != SERVICE_SUCCESS)
1966                 s->result = f;
1967
1968         if (s->exec_context.kill_mode != KILL_NONE) {
1969                 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1970
1971                 if (s->main_pid > 0) {
1972                         if (kill_and_sigcont(s->main_pid, sig) < 0 && errno != ESRCH)
1973                                 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1974                         else
1975                                 wait_for_exit = !s->main_pid_alien;
1976                 }
1977
1978                 if (s->control_pid > 0) {
1979                         if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
1980                                 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1981                         else
1982                                 wait_for_exit = true;
1983                 }
1984
1985                 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1986
1987                         if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1988                                 r = -ENOMEM;
1989                                 goto fail;
1990                         }
1991
1992                         /* Exclude the main/control pids from being killed via the cgroup */
1993                         if (s->main_pid > 0)
1994                                 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1995                                         goto fail;
1996
1997                         if (s->control_pid > 0)
1998                                 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1999                                         goto fail;
2000
2001                         r = cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, sig, true, false, pid_set, NULL);
2002                         if (r < 0) {
2003                                 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
2004                                         log_warning("Failed to kill control group: %s", strerror(-r));
2005                         } else if (r > 0)
2006                                 wait_for_exit = true;
2007
2008                         set_free(pid_set);
2009                         pid_set = NULL;
2010                 }
2011         }
2012
2013         if (wait_for_exit) {
2014                 if (s->timeout_usec > 0)
2015                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
2016                                 goto fail;
2017
2018                 service_set_state(s, state);
2019         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
2020                 service_enter_stop_post(s, SERVICE_SUCCESS);
2021         else
2022                 service_enter_dead(s, SERVICE_SUCCESS, true);
2023
2024         return;
2025
2026 fail:
2027         log_warning("%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
2028
2029         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
2030                 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
2031         else
2032                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2033
2034         if (pid_set)
2035                 set_free(pid_set);
2036 }
2037
2038 static void service_enter_stop(Service *s, ServiceResult f) {
2039         int r;
2040
2041         assert(s);
2042
2043         if (f != SERVICE_SUCCESS)
2044                 s->result = f;
2045
2046         service_unwatch_control_pid(s);
2047
2048         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
2049                 s->control_command_id = SERVICE_EXEC_STOP;
2050
2051                 r = service_spawn(s,
2052                                   s->control_command,
2053                                   true,
2054                                   false,
2055                                   !s->permissions_start_only,
2056                                   !s->root_directory_start_only,
2057                                   false,
2058                                   false,
2059                                   true,
2060                                   &s->control_pid);
2061                 if (r < 0)
2062                         goto fail;
2063
2064                 service_set_state(s, SERVICE_STOP);
2065         } else
2066                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2067
2068         return;
2069
2070 fail:
2071         log_warning("%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
2072         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2073 }
2074
2075 static void service_enter_running(Service *s, ServiceResult f) {
2076         int main_pid_ok, cgroup_ok;
2077         assert(s);
2078
2079         if (f != SERVICE_SUCCESS)
2080                 s->result = f;
2081
2082         main_pid_ok = main_pid_good(s);
2083         cgroup_ok = cgroup_good(s);
2084
2085         if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
2086             (s->bus_name_good || s->type != SERVICE_DBUS))
2087                 service_set_state(s, SERVICE_RUNNING);
2088         else if (s->remain_after_exit)
2089                 service_set_state(s, SERVICE_EXITED);
2090         else
2091                 service_enter_stop(s, SERVICE_SUCCESS);
2092 }
2093
2094 static void service_enter_start_post(Service *s) {
2095         int r;
2096         assert(s);
2097
2098         service_unwatch_control_pid(s);
2099
2100         if (s->watchdog_usec > 0)
2101                 service_reset_watchdog(s);
2102
2103         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
2104                 s->control_command_id = SERVICE_EXEC_START_POST;
2105
2106                 r = service_spawn(s,
2107                                   s->control_command,
2108                                   true,
2109                                   false,
2110                                   !s->permissions_start_only,
2111                                   !s->root_directory_start_only,
2112                                   false,
2113                                   false,
2114                                   true,
2115                                   &s->control_pid);
2116                 if (r < 0)
2117                         goto fail;
2118
2119                 service_set_state(s, SERVICE_START_POST);
2120         } else
2121                 service_enter_running(s, SERVICE_SUCCESS);
2122
2123         return;
2124
2125 fail:
2126         log_warning("%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
2127         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2128 }
2129
2130 static void service_enter_start(Service *s) {
2131         pid_t pid;
2132         int r;
2133         ExecCommand *c;
2134
2135         assert(s);
2136
2137         assert(s->exec_command[SERVICE_EXEC_START]);
2138         assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2139
2140         if (s->type == SERVICE_FORKING)
2141                 service_unwatch_control_pid(s);
2142         else
2143                 service_unwatch_main_pid(s);
2144
2145         /* We want to ensure that nobody leaks processes from
2146          * START_PRE here, so let's go on a killing spree, People
2147          * should not spawn long running processes from START_PRE. */
2148         cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, true, NULL, "control");
2149
2150         if (s->type == SERVICE_FORKING) {
2151                 s->control_command_id = SERVICE_EXEC_START;
2152                 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2153
2154                 s->main_command = NULL;
2155         } else {
2156                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2157                 s->control_command = NULL;
2158
2159                 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2160         }
2161
2162         r = service_spawn(s,
2163                           c,
2164                           s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY || s->type == SERVICE_ONESHOT,
2165                           true,
2166                           true,
2167                           true,
2168                           true,
2169                           s->notify_access != NOTIFY_NONE,
2170                           false,
2171                           &pid);
2172         if (r < 0)
2173                 goto fail;
2174
2175         if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
2176                 /* For simple services we immediately start
2177                  * the START_POST binaries. */
2178
2179                 service_set_main_pid(s, pid);
2180                 service_enter_start_post(s);
2181
2182         } else  if (s->type == SERVICE_FORKING) {
2183
2184                 /* For forking services we wait until the start
2185                  * process exited. */
2186
2187                 s->control_pid = pid;
2188                 service_set_state(s, SERVICE_START);
2189
2190         } else if (s->type == SERVICE_ONESHOT ||
2191                    s->type == SERVICE_DBUS ||
2192                    s->type == SERVICE_NOTIFY) {
2193
2194                 /* For oneshot services we wait until the start
2195                  * process exited, too, but it is our main process. */
2196
2197                 /* For D-Bus services we know the main pid right away,
2198                  * but wait for the bus name to appear on the
2199                  * bus. Notify services are similar. */
2200
2201                 service_set_main_pid(s, pid);
2202                 service_set_state(s, SERVICE_START);
2203         } else
2204                 assert_not_reached("Unknown service type");
2205
2206         return;
2207
2208 fail:
2209         log_warning("%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
2210         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2211 }
2212
2213 static void service_enter_start_pre(Service *s) {
2214         int r;
2215
2216         assert(s);
2217
2218         service_unwatch_control_pid(s);
2219
2220         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2221
2222                 /* Before we start anything, let's clear up what might
2223                  * be left from previous runs. */
2224                 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, true, NULL, "control");
2225
2226                 s->control_command_id = SERVICE_EXEC_START_PRE;
2227
2228                 r = service_spawn(s,
2229                                   s->control_command,
2230                                   true,
2231                                   false,
2232                                   !s->permissions_start_only,
2233                                   !s->root_directory_start_only,
2234                                   true,
2235                                   false,
2236                                   true,
2237                                   &s->control_pid);
2238                 if (r < 0)
2239                         goto fail;
2240
2241                 service_set_state(s, SERVICE_START_PRE);
2242         } else
2243                 service_enter_start(s);
2244
2245         return;
2246
2247 fail:
2248         log_warning("%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
2249         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2250 }
2251
2252 static void service_enter_restart(Service *s) {
2253         int r;
2254         DBusError error;
2255
2256         assert(s);
2257         dbus_error_init(&error);
2258
2259         if (UNIT(s)->job) {
2260                 log_info("Job pending for unit, delaying automatic restart.");
2261
2262                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
2263                         goto fail;
2264
2265                 return;
2266         }
2267
2268         /* Any units that are bound to this service must also be
2269          * restarted. We use JOB_RESTART (instead of the more obvious
2270          * JOB_START) here so that those dependency jobs will be added
2271          * as well. */
2272         r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
2273         if (r < 0)
2274                 goto fail;
2275
2276         log_debug("%s scheduled restart job.", UNIT(s)->id);
2277         return;
2278
2279 fail:
2280         log_warning("%s failed to schedule restart job: %s", UNIT(s)->id, bus_error(&error, -r));
2281         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
2282
2283         dbus_error_free(&error);
2284 }
2285
2286 static void service_enter_reload(Service *s) {
2287         int r;
2288
2289         assert(s);
2290
2291         service_unwatch_control_pid(s);
2292
2293         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2294                 s->control_command_id = SERVICE_EXEC_RELOAD;
2295
2296                 r = service_spawn(s,
2297                                   s->control_command,
2298                                   true,
2299                                   false,
2300                                   !s->permissions_start_only,
2301                                   !s->root_directory_start_only,
2302                                   false,
2303                                   false,
2304                                   true,
2305                                   &s->control_pid);
2306                 if (r < 0)
2307                         goto fail;
2308
2309                 service_set_state(s, SERVICE_RELOAD);
2310         } else
2311                 service_enter_running(s, SERVICE_SUCCESS);
2312
2313         return;
2314
2315 fail:
2316         log_warning("%s failed to run 'reload' task: %s", UNIT(s)->id, strerror(-r));
2317         s->reload_result = SERVICE_FAILURE_RESOURCES;
2318         service_enter_running(s, SERVICE_SUCCESS);
2319 }
2320
2321 static void service_run_next_control(Service *s) {
2322         int r;
2323
2324         assert(s);
2325         assert(s->control_command);
2326         assert(s->control_command->command_next);
2327
2328         assert(s->control_command_id != SERVICE_EXEC_START);
2329
2330         s->control_command = s->control_command->command_next;
2331         service_unwatch_control_pid(s);
2332
2333         r = service_spawn(s,
2334                           s->control_command,
2335                           true,
2336                           false,
2337                           !s->permissions_start_only,
2338                           !s->root_directory_start_only,
2339                           s->control_command_id == SERVICE_EXEC_START_PRE ||
2340                           s->control_command_id == SERVICE_EXEC_STOP_POST,
2341                           false,
2342                           true,
2343                           &s->control_pid);
2344         if (r < 0)
2345                 goto fail;
2346
2347         return;
2348
2349 fail:
2350         log_warning("%s failed to run next control task: %s", UNIT(s)->id, strerror(-r));
2351
2352         if (s->state == SERVICE_START_PRE)
2353                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2354         else if (s->state == SERVICE_STOP)
2355                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2356         else if (s->state == SERVICE_STOP_POST)
2357                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2358         else if (s->state == SERVICE_RELOAD) {
2359                 s->reload_result = SERVICE_FAILURE_RESOURCES;
2360                 service_enter_running(s, SERVICE_SUCCESS);
2361         } else
2362                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2363 }
2364
2365 static void service_run_next_main(Service *s) {
2366         pid_t pid;
2367         int r;
2368
2369         assert(s);
2370         assert(s->main_command);
2371         assert(s->main_command->command_next);
2372         assert(s->type == SERVICE_ONESHOT);
2373
2374         s->main_command = s->main_command->command_next;
2375         service_unwatch_main_pid(s);
2376
2377         r = service_spawn(s,
2378                           s->main_command,
2379                           true,
2380                           true,
2381                           true,
2382                           true,
2383                           true,
2384                           s->notify_access != NOTIFY_NONE,
2385                           false,
2386                           &pid);
2387         if (r < 0)
2388                 goto fail;
2389
2390         service_set_main_pid(s, pid);
2391
2392         return;
2393
2394 fail:
2395         log_warning("%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
2396         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2397 }
2398
2399 static int service_start_limit_test(Service *s) {
2400         assert(s);
2401
2402         if (ratelimit_test(&s->start_limit))
2403                 return 0;
2404
2405         switch (s->start_limit_action) {
2406
2407         case SERVICE_START_LIMIT_NONE:
2408                 log_warning("%s start request repeated too quickly, refusing to start.", UNIT(s)->id);
2409                 break;
2410
2411         case SERVICE_START_LIMIT_REBOOT: {
2412                 DBusError error;
2413                 int r;
2414
2415                 dbus_error_init(&error);
2416
2417                 log_warning("%s start request repeated too quickly, rebooting.", UNIT(s)->id);
2418
2419                 r = manager_add_job_by_name(UNIT(s)->manager, JOB_START, SPECIAL_REBOOT_TARGET, JOB_REPLACE, true, &error, NULL);
2420                 if (r < 0) {
2421                         log_error("Failed to reboot: %s.", bus_error(&error, r));
2422                         dbus_error_free(&error);
2423                 }
2424
2425                 break;
2426         }
2427
2428         case SERVICE_START_LIMIT_REBOOT_FORCE:
2429                 log_warning("%s start request repeated too quickly, forcibly rebooting.", UNIT(s)->id);
2430                 UNIT(s)->manager->exit_code = MANAGER_REBOOT;
2431                 break;
2432
2433         case SERVICE_START_LIMIT_REBOOT_IMMEDIATE:
2434                 log_warning("%s start request repeated too quickly, rebooting immediately.", UNIT(s)->id);
2435                 reboot(RB_AUTOBOOT);
2436                 break;
2437
2438         default:
2439                 log_error("start limit action=%i", s->start_limit_action);
2440                 assert_not_reached("Unknown StartLimitAction.");
2441         }
2442
2443         return -ECANCELED;
2444 }
2445
2446 static int service_start(Unit *u) {
2447         Service *s = SERVICE(u);
2448         int r;
2449
2450         assert(s);
2451
2452         /* We cannot fulfill this request right now, try again later
2453          * please! */
2454         if (s->state == SERVICE_STOP ||
2455             s->state == SERVICE_STOP_SIGTERM ||
2456             s->state == SERVICE_STOP_SIGKILL ||
2457             s->state == SERVICE_STOP_POST ||
2458             s->state == SERVICE_FINAL_SIGTERM ||
2459             s->state == SERVICE_FINAL_SIGKILL)
2460                 return -EAGAIN;
2461
2462         /* Already on it! */
2463         if (s->state == SERVICE_START_PRE ||
2464             s->state == SERVICE_START ||
2465             s->state == SERVICE_START_POST)
2466                 return 0;
2467
2468         /* A service that will be restarted must be stopped first to
2469          * trigger BindTo and/or OnFailure dependencies. If a user
2470          * does not want to wait for the holdoff time to elapse, the
2471          * service should be manually restarted, not started. */
2472         if (s->state == SERVICE_AUTO_RESTART) {
2473                 log_warning("%s automatic restart is pending, must be stopped before issuing start request.", UNIT(s)->id);
2474                 return -ECANCELED;
2475         }
2476
2477         assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
2478
2479         /* Make sure we don't enter a busy loop of some kind. */
2480         r = service_start_limit_test(s);
2481         if (r < 0) {
2482                 service_notify_sockets_dead(s, true);
2483                 return r;
2484         }
2485
2486         s->result = SERVICE_SUCCESS;
2487         s->reload_result = SERVICE_SUCCESS;
2488         s->main_pid_known = false;
2489         s->main_pid_alien = false;
2490         s->forbid_restart = false;
2491
2492         service_enter_start_pre(s);
2493         return 0;
2494 }
2495
2496 static int service_stop(Unit *u) {
2497         Service *s = SERVICE(u);
2498
2499         assert(s);
2500
2501         /* Don't create restart jobs from here. */
2502         s->forbid_restart = true;
2503
2504         /* Already on it */
2505         if (s->state == SERVICE_STOP ||
2506             s->state == SERVICE_STOP_SIGTERM ||
2507             s->state == SERVICE_STOP_SIGKILL ||
2508             s->state == SERVICE_STOP_POST ||
2509             s->state == SERVICE_FINAL_SIGTERM ||
2510             s->state == SERVICE_FINAL_SIGKILL)
2511                 return 0;
2512
2513         /* A restart will be scheduled or is in progress. */
2514         if (s->state == SERVICE_AUTO_RESTART) {
2515                 service_enter_dead(s, SERVICE_SUCCESS, false);
2516                 return 0;
2517         }
2518
2519         /* If there's already something running we go directly into
2520          * kill mode. */
2521         if (s->state == SERVICE_START_PRE ||
2522             s->state == SERVICE_START ||
2523             s->state == SERVICE_START_POST ||
2524             s->state == SERVICE_RELOAD) {
2525                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2526                 return 0;
2527         }
2528
2529         assert(s->state == SERVICE_RUNNING ||
2530                s->state == SERVICE_EXITED);
2531
2532         service_enter_stop(s, SERVICE_SUCCESS);
2533         return 0;
2534 }
2535
2536 static int service_reload(Unit *u) {
2537         Service *s = SERVICE(u);
2538
2539         assert(s);
2540
2541         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2542
2543         service_enter_reload(s);
2544         return 0;
2545 }
2546
2547 static bool service_can_reload(Unit *u) {
2548         Service *s = SERVICE(u);
2549
2550         assert(s);
2551
2552         return !!s->exec_command[SERVICE_EXEC_RELOAD];
2553 }
2554
2555 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2556         Service *s = SERVICE(u);
2557
2558         assert(u);
2559         assert(f);
2560         assert(fds);
2561
2562         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2563         unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2564         unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2565
2566         if (s->control_pid > 0)
2567                 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2568
2569         if (s->main_pid_known && s->main_pid > 0)
2570                 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2571
2572         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2573
2574         if (s->status_text)
2575                 unit_serialize_item(u, f, "status-text", s->status_text);
2576
2577         /* FIXME: There's a minor uncleanliness here: if there are
2578          * multiple commands attached here, we will start from the
2579          * first one again */
2580         if (s->control_command_id >= 0)
2581                 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2582
2583         if (s->socket_fd >= 0) {
2584                 int copy;
2585
2586                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2587                         return copy;
2588
2589                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2590         }
2591
2592         if (s->main_exec_status.pid > 0) {
2593                 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2594                 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2595                 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2596
2597                 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2598                         unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2599                         unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2600                 }
2601         }
2602         if (dual_timestamp_is_set(&s->watchdog_timestamp))
2603                 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2604
2605         return 0;
2606 }
2607
2608 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2609         Service *s = SERVICE(u);
2610
2611         assert(u);
2612         assert(key);
2613         assert(value);
2614         assert(fds);
2615
2616         if (streq(key, "state")) {
2617                 ServiceState state;
2618
2619                 if ((state = service_state_from_string(value)) < 0)
2620                         log_debug("Failed to parse state value %s", value);
2621                 else
2622                         s->deserialized_state = state;
2623         } else if (streq(key, "result")) {
2624                 ServiceResult f;
2625
2626                 f = service_result_from_string(value);
2627                 if (f < 0)
2628                         log_debug("Failed to parse result value %s", value);
2629                 else if (f != SERVICE_SUCCESS)
2630                         s->result = f;
2631
2632         } else if (streq(key, "reload-result")) {
2633                 ServiceResult f;
2634
2635                 f = service_result_from_string(value);
2636                 if (f < 0)
2637                         log_debug("Failed to parse reload result value %s", value);
2638                 else if (f != SERVICE_SUCCESS)
2639                         s->reload_result = f;
2640
2641         } else if (streq(key, "control-pid")) {
2642                 pid_t pid;
2643
2644                 if (parse_pid(value, &pid) < 0)
2645                         log_debug("Failed to parse control-pid value %s", value);
2646                 else
2647                         s->control_pid = pid;
2648         } else if (streq(key, "main-pid")) {
2649                 pid_t pid;
2650
2651                 if (parse_pid(value, &pid) < 0)
2652                         log_debug("Failed to parse main-pid value %s", value);
2653                 else
2654                         service_set_main_pid(s, (pid_t) pid);
2655         } else if (streq(key, "main-pid-known")) {
2656                 int b;
2657
2658                 if ((b = parse_boolean(value)) < 0)
2659                         log_debug("Failed to parse main-pid-known value %s", value);
2660                 else
2661                         s->main_pid_known = b;
2662         } else if (streq(key, "status-text")) {
2663                 char *t;
2664
2665                 if ((t = strdup(value))) {
2666                         free(s->status_text);
2667                         s->status_text = t;
2668                 }
2669
2670         } else if (streq(key, "control-command")) {
2671                 ServiceExecCommand id;
2672
2673                 if ((id = service_exec_command_from_string(value)) < 0)
2674                         log_debug("Failed to parse exec-command value %s", value);
2675                 else {
2676                         s->control_command_id = id;
2677                         s->control_command = s->exec_command[id];
2678                 }
2679         } else if (streq(key, "socket-fd")) {
2680                 int fd;
2681
2682                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2683                         log_debug("Failed to parse socket-fd value %s", value);
2684                 else {
2685
2686                         if (s->socket_fd >= 0)
2687                                 close_nointr_nofail(s->socket_fd);
2688                         s->socket_fd = fdset_remove(fds, fd);
2689                 }
2690         } else if (streq(key, "main-exec-status-pid")) {
2691                 pid_t pid;
2692
2693                 if (parse_pid(value, &pid) < 0)
2694                         log_debug("Failed to parse main-exec-status-pid value %s", value);
2695                 else
2696                         s->main_exec_status.pid = pid;
2697         } else if (streq(key, "main-exec-status-code")) {
2698                 int i;
2699
2700                 if (safe_atoi(value, &i) < 0)
2701                         log_debug("Failed to parse main-exec-status-code value %s", value);
2702                 else
2703                         s->main_exec_status.code = i;
2704         } else if (streq(key, "main-exec-status-status")) {
2705                 int i;
2706
2707                 if (safe_atoi(value, &i) < 0)
2708                         log_debug("Failed to parse main-exec-status-status value %s", value);
2709                 else
2710                         s->main_exec_status.status = i;
2711         } else if (streq(key, "main-exec-status-start"))
2712                 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2713         else if (streq(key, "main-exec-status-exit"))
2714                 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2715         else if (streq(key, "watchdog-timestamp"))
2716                 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2717         else
2718                 log_debug("Unknown serialization key '%s'", key);
2719
2720         return 0;
2721 }
2722
2723 static UnitActiveState service_active_state(Unit *u) {
2724         const UnitActiveState *table;
2725
2726         assert(u);
2727
2728         table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2729
2730         return table[SERVICE(u)->state];
2731 }
2732
2733 static const char *service_sub_state_to_string(Unit *u) {
2734         assert(u);
2735
2736         return service_state_to_string(SERVICE(u)->state);
2737 }
2738
2739 static bool service_check_gc(Unit *u) {
2740         Service *s = SERVICE(u);
2741
2742         assert(s);
2743
2744         /* Never clean up services that still have a process around,
2745          * even if the service is formally dead. */
2746         if (cgroup_good(s) > 0 ||
2747             main_pid_good(s) > 0 ||
2748             control_pid_good(s) > 0)
2749                 return true;
2750
2751 #ifdef HAVE_SYSV_COMPAT
2752         if (s->is_sysv)
2753                 return true;
2754 #endif
2755
2756         return false;
2757 }
2758
2759 static bool service_check_snapshot(Unit *u) {
2760         Service *s = SERVICE(u);
2761
2762         assert(s);
2763
2764         return !s->got_socket_fd;
2765 }
2766
2767 static int service_retry_pid_file(Service *s) {
2768         int r;
2769
2770         assert(s->pid_file);
2771         assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2772
2773         r = service_load_pid_file(s, false);
2774         if (r < 0)
2775                 return r;
2776
2777         service_unwatch_pid_file(s);
2778
2779         service_enter_running(s, SERVICE_SUCCESS);
2780         return 0;
2781 }
2782
2783 static int service_watch_pid_file(Service *s) {
2784         int r;
2785
2786         log_debug("Setting watch for %s's PID file %s", UNIT(s)->id, s->pid_file_pathspec->path);
2787         r = path_spec_watch(s->pid_file_pathspec, UNIT(s));
2788         if (r < 0)
2789                 goto fail;
2790
2791         /* the pidfile might have appeared just before we set the watch */
2792         service_retry_pid_file(s);
2793
2794         return 0;
2795 fail:
2796         log_error("Failed to set a watch for %s's PID file %s: %s",
2797                   UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2798         service_unwatch_pid_file(s);
2799         return r;
2800 }
2801
2802 static int service_demand_pid_file(Service *s) {
2803         PathSpec *ps;
2804
2805         assert(s->pid_file);
2806         assert(!s->pid_file_pathspec);
2807
2808         ps = new0(PathSpec, 1);
2809         if (!ps)
2810                 return -ENOMEM;
2811
2812         ps->path = strdup(s->pid_file);
2813         if (!ps->path) {
2814                 free(ps);
2815                 return -ENOMEM;
2816         }
2817
2818         path_kill_slashes(ps->path);
2819
2820         /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2821          * keep their PID file open all the time. */
2822         ps->type = PATH_MODIFIED;
2823         ps->inotify_fd = -1;
2824
2825         s->pid_file_pathspec = ps;
2826
2827         return service_watch_pid_file(s);
2828 }
2829
2830 static void service_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
2831         Service *s = SERVICE(u);
2832
2833         assert(s);
2834         assert(fd >= 0);
2835         assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2836         assert(s->pid_file_pathspec);
2837         assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2838
2839         log_debug("inotify event for %s", u->id);
2840
2841         if (path_spec_fd_event(s->pid_file_pathspec, events) < 0)
2842                 goto fail;
2843
2844         if (service_retry_pid_file(s) == 0)
2845                 return;
2846
2847         if (service_watch_pid_file(s) < 0)
2848                 goto fail;
2849
2850         return;
2851 fail:
2852         service_unwatch_pid_file(s);
2853         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2854 }
2855
2856 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2857         Service *s = SERVICE(u);
2858         ServiceResult f;
2859
2860         assert(s);
2861         assert(pid >= 0);
2862
2863         if (UNIT(s)->fragment_path ? is_clean_exit(code, status) : is_clean_exit_lsb(code, status))
2864                 f = SERVICE_SUCCESS;
2865         else if (code == CLD_EXITED)
2866                 f = SERVICE_FAILURE_EXIT_CODE;
2867         else if (code == CLD_KILLED)
2868                 f = SERVICE_FAILURE_SIGNAL;
2869         else if (code == CLD_DUMPED)
2870                 f = SERVICE_FAILURE_CORE_DUMP;
2871         else
2872                 assert_not_reached("Unknown code");
2873
2874         if (s->main_pid == pid) {
2875                 /* Forking services may occasionally move to a new PID.
2876                  * As long as they update the PID file before exiting the old
2877                  * PID, they're fine. */
2878                 if (service_load_pid_file(s, false) == 0)
2879                         return;
2880
2881                 s->main_pid = 0;
2882                 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2883
2884                 /* If this is not a forking service than the main
2885                  * process got started and hence we copy the exit
2886                  * status so that it is recorded both as main and as
2887                  * control process exit status */
2888                 if (s->main_command) {
2889                         s->main_command->exec_status = s->main_exec_status;
2890
2891                         if (s->main_command->ignore)
2892                                 f = SERVICE_SUCCESS;
2893                 }
2894
2895                 log_full(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2896                          "%s: main process exited, code=%s, status=%i", u->id, sigchld_code_to_string(code), status);
2897
2898                 if (f != SERVICE_SUCCESS)
2899                         s->result = f;
2900
2901                 if (s->main_command &&
2902                     s->main_command->command_next &&
2903                     f == SERVICE_SUCCESS) {
2904
2905                         /* There is another command to *
2906                          * execute, so let's do that. */
2907
2908                         log_debug("%s running next main command for state %s", u->id, service_state_to_string(s->state));
2909                         service_run_next_main(s);
2910
2911                 } else {
2912
2913                         /* The service exited, so the service is officially
2914                          * gone. */
2915                         s->main_command = NULL;
2916
2917                         switch (s->state) {
2918
2919                         case SERVICE_START_POST:
2920                         case SERVICE_RELOAD:
2921                         case SERVICE_STOP:
2922                                 /* Need to wait until the operation is
2923                                  * done */
2924                                 break;
2925
2926                         case SERVICE_START:
2927                                 if (s->type == SERVICE_ONESHOT) {
2928                                         /* This was our main goal, so let's go on */
2929                                         if (f == SERVICE_SUCCESS)
2930                                                 service_enter_start_post(s);
2931                                         else
2932                                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2933                                         break;
2934                                 } else {
2935                                         assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2936
2937                                         /* Fall through */
2938                                 }
2939
2940                         case SERVICE_RUNNING:
2941                                 service_enter_running(s, f);
2942                                 break;
2943
2944                         case SERVICE_STOP_SIGTERM:
2945                         case SERVICE_STOP_SIGKILL:
2946
2947                                 if (!control_pid_good(s))
2948                                         service_enter_stop_post(s, f);
2949
2950                                 /* If there is still a control process, wait for that first */
2951                                 break;
2952
2953                         default:
2954                                 assert_not_reached("Uh, main process died at wrong time.");
2955                         }
2956                 }
2957
2958         } else if (s->control_pid == pid) {
2959
2960                 s->control_pid = 0;
2961
2962                 if (s->control_command) {
2963                         exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2964
2965                         if (s->control_command->ignore)
2966                                 f = SERVICE_SUCCESS;
2967                 }
2968
2969                 log_full(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2970                          "%s: control process exited, code=%s status=%i", u->id, sigchld_code_to_string(code), status);
2971
2972                 if (f != SERVICE_SUCCESS)
2973                         s->result = f;
2974
2975                 /* Immediately get rid of the cgroup, so that the
2976                  * kernel doesn't delay the cgroup empty messages for
2977                  * the service cgroup any longer than necessary */
2978                 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, true, NULL, "control");
2979
2980                 if (s->control_command &&
2981                     s->control_command->command_next &&
2982                     f == SERVICE_SUCCESS) {
2983
2984                         /* There is another command to *
2985                          * execute, so let's do that. */
2986
2987                         log_debug("%s running next control command for state %s", u->id, service_state_to_string(s->state));
2988                         service_run_next_control(s);
2989
2990                 } else {
2991                         /* No further commands for this step, so let's
2992                          * figure out what to do next */
2993
2994                         s->control_command = NULL;
2995                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2996
2997                         log_debug("%s got final SIGCHLD for state %s", u->id, service_state_to_string(s->state));
2998
2999                         switch (s->state) {
3000
3001                         case SERVICE_START_PRE:
3002                                 if (f == SERVICE_SUCCESS)
3003                                         service_enter_start(s);
3004                                 else
3005                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3006                                 break;
3007
3008                         case SERVICE_START:
3009                                 assert(s->type == SERVICE_FORKING);
3010
3011                                 if (f != SERVICE_SUCCESS) {
3012                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3013                                         break;
3014                                 }
3015
3016                                 if (s->pid_file) {
3017                                         bool has_start_post;
3018                                         int r;
3019
3020                                         /* Let's try to load the pid file here if we can.
3021                                          * The PID file might actually be created by a START_POST
3022                                          * script. In that case don't worry if the loading fails. */
3023
3024                                         has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
3025                                         r = service_load_pid_file(s, !has_start_post);
3026                                         if (!has_start_post && r < 0) {
3027                                                 r = service_demand_pid_file(s);
3028                                                 if (r < 0 || !cgroup_good(s))
3029                                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3030                                                 break;
3031                                         }
3032                                 } else
3033                                         service_search_main_pid(s);
3034
3035                                 service_enter_start_post(s);
3036                                 break;
3037
3038                         case SERVICE_START_POST:
3039                                 if (f != SERVICE_SUCCESS) {
3040                                         service_enter_stop(s, f);
3041                                         break;
3042                                 }
3043
3044                                 if (s->pid_file) {
3045                                         int r;
3046
3047                                         r = service_load_pid_file(s, true);
3048                                         if (r < 0) {
3049                                                 r = service_demand_pid_file(s);
3050                                                 if (r < 0 || !cgroup_good(s))
3051                                                         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3052                                                 break;
3053                                         }
3054                                 } else
3055                                         service_search_main_pid(s);
3056
3057                                 service_enter_running(s, SERVICE_SUCCESS);
3058                                 break;
3059
3060                         case SERVICE_RELOAD:
3061                                 if (f == SERVICE_SUCCESS) {
3062                                         service_load_pid_file(s, true);
3063                                         service_search_main_pid(s);
3064                                 }
3065
3066                                 s->reload_result = f;
3067                                 service_enter_running(s, SERVICE_SUCCESS);
3068                                 break;
3069
3070                         case SERVICE_STOP:
3071                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3072                                 break;
3073
3074                         case SERVICE_STOP_SIGTERM:
3075                         case SERVICE_STOP_SIGKILL:
3076                                 if (main_pid_good(s) <= 0)
3077                                         service_enter_stop_post(s, f);
3078
3079                                 /* If there is still a service
3080                                  * process around, wait until
3081                                  * that one quit, too */
3082                                 break;
3083
3084                         case SERVICE_STOP_POST:
3085                         case SERVICE_FINAL_SIGTERM:
3086                         case SERVICE_FINAL_SIGKILL:
3087                                 service_enter_dead(s, f, true);
3088                                 break;
3089
3090                         default:
3091                                 assert_not_reached("Uh, control process died at wrong time.");
3092                         }
3093                 }
3094         }
3095
3096         /* Notify clients about changed exit status */
3097         unit_add_to_dbus_queue(u);
3098 }
3099
3100 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
3101         Service *s = SERVICE(u);
3102
3103         assert(s);
3104         assert(elapsed == 1);
3105
3106         if (w == &s->watchdog_watch) {
3107                 service_handle_watchdog(s);
3108                 return;
3109         }
3110
3111         assert(w == &s->timer_watch);
3112
3113         switch (s->state) {
3114
3115         case SERVICE_START_PRE:
3116         case SERVICE_START:
3117                 log_warning("%s operation timed out. Terminating.", u->id);
3118                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3119                 break;
3120
3121         case SERVICE_START_POST:
3122                 log_warning("%s operation timed out. Stopping.", u->id);
3123                 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
3124                 break;
3125
3126         case SERVICE_RELOAD:
3127                 log_warning("%s operation timed out. Stopping.", u->id);
3128                 s->reload_result = SERVICE_FAILURE_TIMEOUT;
3129                 service_enter_running(s, SERVICE_SUCCESS);
3130                 break;
3131
3132         case SERVICE_STOP:
3133                 log_warning("%s stopping timed out. Terminating.", u->id);
3134                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3135                 break;
3136
3137         case SERVICE_STOP_SIGTERM:
3138                 if (s->exec_context.send_sigkill) {
3139                         log_warning("%s stopping timed out. Killing.", u->id);
3140                         service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3141                 } else {
3142                         log_warning("%s stopping timed out. Skipping SIGKILL.", u->id);
3143                         service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3144                 }
3145
3146                 break;
3147
3148         case SERVICE_STOP_SIGKILL:
3149                 /* Uh, we sent a SIGKILL and it is still not gone?
3150                  * Must be something we cannot kill, so let's just be
3151                  * weirded out and continue */
3152
3153                 log_warning("%s still around after SIGKILL. Ignoring.", u->id);
3154                 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3155                 break;
3156
3157         case SERVICE_STOP_POST:
3158                 log_warning("%s stopping timed out (2). Terminating.", u->id);
3159                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3160                 break;
3161
3162         case SERVICE_FINAL_SIGTERM:
3163                 if (s->exec_context.send_sigkill) {
3164                         log_warning("%s stopping timed out (2). Killing.", u->id);
3165                         service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3166                 } else {
3167                         log_warning("%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.", u->id);
3168                         service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3169                 }
3170
3171                 break;
3172
3173         case SERVICE_FINAL_SIGKILL:
3174                 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->id);
3175                 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
3176                 break;
3177
3178         case SERVICE_AUTO_RESTART:
3179                 log_info("%s holdoff time over, scheduling restart.", u->id);
3180                 service_enter_restart(s);
3181                 break;
3182
3183         default:
3184                 assert_not_reached("Timeout at wrong time.");
3185         }
3186 }
3187
3188 static void service_cgroup_notify_event(Unit *u) {
3189         Service *s = SERVICE(u);
3190
3191         assert(u);
3192
3193         log_debug("%s: cgroup is empty", u->id);
3194
3195         switch (s->state) {
3196
3197                 /* Waiting for SIGCHLD is usually more interesting,
3198                  * because it includes return codes/signals. Which is
3199                  * why we ignore the cgroup events for most cases,
3200                  * except when we don't know pid which to expect the
3201                  * SIGCHLD for. */
3202
3203         case SERVICE_START:
3204         case SERVICE_START_POST:
3205                 /* If we were hoping for the daemon to write its PID file,
3206                  * we can give up now. */
3207                 if (s->pid_file_pathspec) {
3208                         log_warning("%s never wrote its PID file. Failing.", UNIT(s)->id);
3209                         service_unwatch_pid_file(s);
3210                         if (s->state == SERVICE_START)
3211                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3212                         else
3213                                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3214                 }
3215                 break;
3216
3217         case SERVICE_RUNNING:
3218                 /* service_enter_running() will figure out what to do */
3219                 service_enter_running(s, SERVICE_SUCCESS);
3220                 break;
3221
3222         case SERVICE_STOP_SIGTERM:
3223         case SERVICE_STOP_SIGKILL:
3224
3225                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3226                         service_enter_stop_post(s, SERVICE_SUCCESS);
3227
3228                 break;
3229
3230         case SERVICE_FINAL_SIGTERM:
3231         case SERVICE_FINAL_SIGKILL:
3232                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3233                         service_enter_dead(s, SERVICE_SUCCESS, SERVICE_SUCCESS);
3234
3235                 break;
3236
3237         default:
3238                 ;
3239         }
3240 }
3241
3242 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
3243         Service *s = SERVICE(u);
3244         const char *e;
3245
3246         assert(u);
3247
3248         if (s->notify_access == NOTIFY_NONE) {
3249                 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
3250                             u->id, (unsigned long) pid);
3251                 return;
3252         }
3253
3254         if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3255                 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
3256                             u->id, (unsigned long) pid, (unsigned long) s->main_pid);
3257                 return;
3258         }
3259
3260         log_debug("%s: Got message", u->id);
3261
3262         /* Interpret MAINPID= */
3263         if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3264             (s->state == SERVICE_START ||
3265              s->state == SERVICE_START_POST ||
3266              s->state == SERVICE_RUNNING ||
3267              s->state == SERVICE_RELOAD)) {
3268
3269                 if (parse_pid(e + 8, &pid) < 0)
3270                         log_warning("Failed to parse notification message %s", e);
3271                 else {
3272                         log_debug("%s: got %s", u->id, e);
3273                         service_set_main_pid(s, pid);
3274                 }
3275         }
3276
3277         /* Interpret READY= */
3278         if (s->type == SERVICE_NOTIFY &&
3279             s->state == SERVICE_START &&
3280             strv_find(tags, "READY=1")) {
3281                 log_debug("%s: got READY=1", u->id);
3282
3283                 service_enter_start_post(s);
3284         }
3285
3286         /* Interpret STATUS= */
3287         e = strv_find_prefix(tags, "STATUS=");
3288         if (e) {
3289                 char *t;
3290
3291                 if (e[7]) {
3292
3293                         if (!utf8_is_valid(e+7)) {
3294                                 log_warning("Status message in notification is not UTF-8 clean.");
3295                                 return;
3296                         }
3297
3298                         t = strdup(e+7);
3299                         if (!t) {
3300                                 log_error("Failed to allocate string.");
3301                                 return;
3302                         }
3303
3304                         log_debug("%s: got %s", u->id, e);
3305
3306                         free(s->status_text);
3307                         s->status_text = t;
3308                 } else {
3309                         free(s->status_text);
3310                         s->status_text = NULL;
3311                 }
3312
3313         }
3314         if (strv_find(tags, "WATCHDOG=1")) {
3315                 log_debug("%s: got WATCHDOG=1", u->id);
3316                 service_reset_watchdog(s);
3317         }
3318
3319         /* Notify clients about changed status or main pid */
3320         unit_add_to_dbus_queue(u);
3321 }
3322
3323 #ifdef HAVE_SYSV_COMPAT
3324
3325 #ifdef TARGET_SUSE
3326 static void sysv_facility_in_insserv_conf(Manager *mgr) {
3327         FILE *f=NULL;
3328         int r;
3329
3330         if (!(f = fopen("/etc/insserv.conf", "re"))) {
3331                 r = errno == ENOENT ? 0 : -errno;
3332                 goto finish;
3333         }
3334
3335         while (!feof(f)) {
3336                 char l[LINE_MAX], *t;
3337                 char **parsed = NULL;
3338
3339                 if (!fgets(l, sizeof(l), f)) {
3340                         if (feof(f))
3341                                 break;
3342
3343                         r = -errno;
3344                         log_error("Failed to read configuration file '/etc/insserv.conf': %s", strerror(-r));
3345                         goto finish;
3346                 }
3347
3348                 t = strstrip(l);
3349                 if (*t != '$' && *t != '<')
3350                         continue;
3351
3352                 parsed = strv_split(t,WHITESPACE);
3353                 /* we ignore <interactive>, not used, equivalent to X-Interactive */
3354                 if (parsed && !startswith_no_case (parsed[0], "<interactive>")) {
3355                         char *facility;
3356                         Unit *u;
3357                         if (sysv_translate_facility(parsed[0], NULL, &facility) < 0)
3358                                 continue;
3359                         if ((u = manager_get_unit(mgr, facility)) && (u->type == UNIT_TARGET)) {
3360                                 UnitDependency e;
3361                                 char *dep = NULL, *name, **j;
3362
3363                                 STRV_FOREACH (j, parsed+1) {
3364                                         if (*j[0]=='+') {
3365                                                 e = UNIT_WANTS;
3366                                                 name = *j+1;
3367                                         }
3368                                         else {
3369                                                 e = UNIT_REQUIRES;
3370                                                 name = *j;
3371                                         }
3372                                         if (sysv_translate_facility(name, NULL, &dep) < 0)
3373                                                 continue;
3374
3375                                         r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, e, dep, NULL, true);
3376                                         free(dep);
3377                                 }
3378                         }
3379                         free(facility);
3380                 }
3381                 strv_free(parsed);
3382         }
3383 finish:
3384         if (f)
3385                 fclose(f);
3386
3387 }
3388 #endif
3389
3390 static int service_enumerate(Manager *m) {
3391         char **p;
3392         unsigned i;
3393         DIR *d = NULL;
3394         char *path = NULL, *fpath = NULL, *name = NULL;
3395         Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
3396         Unit *service;
3397         Iterator j;
3398         int r;
3399
3400         assert(m);
3401
3402         if (m->running_as != MANAGER_SYSTEM)
3403                 return 0;
3404
3405         zero(runlevel_services);
3406
3407         STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3408                 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3409                         struct dirent *de;
3410
3411                         free(path);
3412                         path = join(*p, "/", rcnd_table[i].path, NULL);
3413                         if (!path) {
3414                                 r = -ENOMEM;
3415                                 goto finish;
3416                         }
3417
3418                         if (d)
3419                                 closedir(d);
3420
3421                         if (!(d = opendir(path))) {
3422                                 if (errno != ENOENT)
3423                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
3424
3425                                 continue;
3426                         }
3427
3428                         while ((de = readdir(d))) {
3429                                 int a, b;
3430
3431                                 if (ignore_file(de->d_name))
3432                                         continue;
3433
3434                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3435                                         continue;
3436
3437                                 if (strlen(de->d_name) < 4)
3438                                         continue;
3439
3440                                 a = undecchar(de->d_name[1]);
3441                                 b = undecchar(de->d_name[2]);
3442
3443                                 if (a < 0 || b < 0)
3444                                         continue;
3445
3446                                 free(fpath);
3447                                 fpath = join(path, "/", de->d_name, NULL);
3448                                 if (!fpath) {
3449                                         r = -ENOMEM;
3450                                         goto finish;
3451                                 }
3452
3453                                 if (access(fpath, X_OK) < 0) {
3454
3455                                         if (errno != ENOENT)
3456                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3457
3458                                         continue;
3459                                 }
3460
3461                                 free(name);
3462                                 if (!(name = sysv_translate_name(de->d_name + 3))) {
3463                                         r = -ENOMEM;
3464                                         goto finish;
3465                                 }
3466
3467                                 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
3468                                         log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3469                                         continue;
3470                                 }
3471
3472                                 if (de->d_name[0] == 'S')  {
3473
3474                                         if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
3475                                                 SERVICE(service)->sysv_start_priority_from_rcnd =
3476                                                         MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3477
3478                                                 SERVICE(service)->sysv_enabled = true;
3479                                         }
3480
3481                                         if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3482                                                 goto finish;
3483
3484                                         if ((r = set_put(runlevel_services[i], service)) < 0)
3485                                                 goto finish;
3486
3487                                 } else if (de->d_name[0] == 'K' &&
3488                                            (rcnd_table[i].type == RUNLEVEL_DOWN ||
3489                                             rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
3490
3491                                         if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3492                                                 goto finish;
3493
3494                                         if ((r = set_put(shutdown_services, service)) < 0)
3495                                                 goto finish;
3496                                 }
3497                         }
3498                 }
3499
3500         /* Now we loaded all stubs and are aware of the lowest
3501         start-up priority for all services, not let's actually load
3502         the services, this will also tell us which services are
3503         actually native now */
3504         manager_dispatch_load_queue(m);
3505
3506         /* If this is a native service, rely on native ways to pull in
3507          * a service, don't pull it in via sysv rcN.d links. */
3508         for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3509                 SET_FOREACH(service, runlevel_services[i], j) {
3510                         service = unit_follow_merge(service);
3511
3512                         if (service->fragment_path)
3513                                 continue;
3514
3515                         if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3516                                 goto finish;
3517                 }
3518
3519         /* We honour K links only for halt/reboot. For the normal
3520          * runlevels we assume the stop jobs will be implicitly added
3521          * by the core logic. Also, we don't really distinguish here
3522          * between the runlevels 0 and 6 and just add them to the
3523          * special shutdown target. On SUSE the boot.d/ runlevel is
3524          * also used for shutdown, so we add links for that too to the
3525          * shutdown target.*/
3526         SET_FOREACH(service, shutdown_services, j) {
3527                 service = unit_follow_merge(service);
3528
3529                 if (service->fragment_path)
3530                         continue;
3531
3532                 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3533                         goto finish;
3534         }
3535
3536         r = 0;
3537
3538 #ifdef TARGET_SUSE
3539         sysv_facility_in_insserv_conf (m);
3540 #endif
3541
3542 finish:
3543         free(path);
3544         free(fpath);
3545         free(name);
3546
3547         for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3548                 set_free(runlevel_services[i]);
3549         set_free(shutdown_services);
3550
3551         if (d)
3552                 closedir(d);
3553
3554         return r;
3555 }
3556 #endif
3557
3558 static void service_bus_name_owner_change(
3559                 Unit *u,
3560                 const char *name,
3561                 const char *old_owner,
3562                 const char *new_owner) {
3563
3564         Service *s = SERVICE(u);
3565
3566         assert(s);
3567         assert(name);
3568
3569         assert(streq(s->bus_name, name));
3570         assert(old_owner || new_owner);
3571
3572         if (old_owner && new_owner)
3573                 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->id, name, old_owner, new_owner);
3574         else if (old_owner)
3575                 log_debug("%s's D-Bus name %s no longer registered by %s", u->id, name, old_owner);
3576         else
3577                 log_debug("%s's D-Bus name %s now registered by %s", u->id, name, new_owner);
3578
3579         s->bus_name_good = !!new_owner;
3580
3581         if (s->type == SERVICE_DBUS) {
3582
3583                 /* service_enter_running() will figure out what to
3584                  * do */
3585                 if (s->state == SERVICE_RUNNING)
3586                         service_enter_running(s, SERVICE_SUCCESS);
3587                 else if (s->state == SERVICE_START && new_owner)
3588                         service_enter_start_post(s);
3589
3590         } else if (new_owner &&
3591                    s->main_pid <= 0 &&
3592                    (s->state == SERVICE_START ||
3593                     s->state == SERVICE_START_POST ||
3594                     s->state == SERVICE_RUNNING ||
3595                     s->state == SERVICE_RELOAD)) {
3596
3597                 /* Try to acquire PID from bus service */
3598                 log_debug("Trying to acquire PID from D-Bus name...");
3599
3600                 bus_query_pid(u->manager, name);
3601         }
3602 }
3603
3604 static void service_bus_query_pid_done(
3605                 Unit *u,
3606                 const char *name,
3607                 pid_t pid) {
3608
3609         Service *s = SERVICE(u);
3610
3611         assert(s);
3612         assert(name);
3613
3614         log_debug("%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
3615
3616         if (s->main_pid <= 0 &&
3617             (s->state == SERVICE_START ||
3618              s->state == SERVICE_START_POST ||
3619              s->state == SERVICE_RUNNING ||
3620              s->state == SERVICE_RELOAD))
3621                 service_set_main_pid(s, pid);
3622 }
3623
3624 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3625
3626         assert(s);
3627         assert(fd >= 0);
3628
3629         /* This is called by the socket code when instantiating a new
3630          * service for a stream socket and the socket needs to be
3631          * configured. */
3632
3633         if (UNIT(s)->load_state != UNIT_LOADED)
3634                 return -EINVAL;