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