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