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