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