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