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