chiark / gitweb /
systemctl: when called as shutdown, fail if first argument isn't 'now'
[elogind.git] / src / service.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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
37 #define COMMENTS "#;\n"
38 #define NEWLINES "\n\r"
39 #define LINE_MAX 4096
40
41 typedef enum RunlevelType {
42         RUNLEVEL_UP,
43         RUNLEVEL_DOWN,
44         RUNLEVEL_SYSINIT
45 } RunlevelType;
46
47 static const struct {
48         const char *path;
49         const char *target;
50         const RunlevelType type;
51 } rcnd_table[] = {
52         /* Standard SysV runlevels */
53         { "rc0.d",  SPECIAL_POWEROFF_TARGET,  RUNLEVEL_DOWN },
54         { "rc1.d",  SPECIAL_RESCUE_TARGET,    RUNLEVEL_UP },
55         { "rc2.d",  SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
56         { "rc3.d",  SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
57         { "rc4.d",  SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
58         { "rc5.d",  SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
59         { "rc6.d",  SPECIAL_REBOOT_TARGET,    RUNLEVEL_DOWN },
60
61         /* SUSE style boot.d */
62         { "boot.d", SPECIAL_SYSINIT_TARGET,   RUNLEVEL_SYSINIT },
63
64         /* Debian style rcS.d */
65         { "rcS.d",  SPECIAL_SYSINIT_TARGET,   RUNLEVEL_SYSINIT },
66 };
67
68 #define RUNLEVELS_UP "12345"
69 /* #define RUNLEVELS_DOWN "06" */
70 /* #define RUNLEVELS_BOOT "bBsS" */
71
72 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
73         [SERVICE_DEAD] = UNIT_INACTIVE,
74         [SERVICE_START_PRE] = UNIT_ACTIVATING,
75         [SERVICE_START] = UNIT_ACTIVATING,
76         [SERVICE_START_POST] = UNIT_ACTIVATING,
77         [SERVICE_RUNNING] = UNIT_ACTIVE,
78         [SERVICE_EXITED] = UNIT_ACTIVE,
79         [SERVICE_RELOAD] = UNIT_ACTIVE_RELOADING,
80         [SERVICE_STOP] = UNIT_DEACTIVATING,
81         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
82         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
83         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
84         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
85         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
86         [SERVICE_MAINTENANCE] = UNIT_INACTIVE,
87         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
88 };
89
90 static void service_init(Unit *u) {
91         Service *s = SERVICE(u);
92
93         assert(u);
94         assert(u->meta.load_state == UNIT_STUB);
95
96         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
97         s->restart_usec = DEFAULT_RESTART_USEC;
98         s->timer_watch.type = WATCH_INVALID;
99         s->sysv_start_priority = -1;
100         s->socket_fd = -1;
101
102         exec_context_init(&s->exec_context);
103
104         RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
105
106         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
107 }
108
109 static void service_unwatch_control_pid(Service *s) {
110         assert(s);
111
112         if (s->control_pid <= 0)
113                 return;
114
115         unit_unwatch_pid(UNIT(s), s->control_pid);
116         s->control_pid = 0;
117 }
118
119 static void service_unwatch_main_pid(Service *s) {
120         assert(s);
121
122         if (s->main_pid <= 0)
123                 return;
124
125         unit_unwatch_pid(UNIT(s), s->main_pid);
126         s->main_pid = 0;
127 }
128
129 static int service_set_main_pid(Service *s, pid_t pid) {
130         assert(s);
131
132         if (pid <= 1)
133                 return -EINVAL;
134
135         if (pid == getpid())
136                 return -EINVAL;
137
138         s->main_pid = pid;
139         s->main_pid_known = true;
140
141         return 0;
142 }
143
144 static int service_set_control_pid(Service *s, pid_t pid) {
145         assert(s);
146
147         if (pid <= 1)
148                 return -EINVAL;
149
150         if (pid == getpid())
151                 return -EINVAL;
152
153         s->control_pid = pid;
154
155         return 0;
156 }
157
158 static void service_close_socket_fd(Service *s) {
159         assert(s);
160
161         if (s->socket_fd < 0)
162                 return;
163
164         close_nointr_nofail(s->socket_fd);
165         s->socket_fd = -1;
166 }
167
168 static void service_done(Unit *u) {
169         Service *s = SERVICE(u);
170
171         assert(s);
172
173         free(s->pid_file);
174         s->pid_file = NULL;
175
176         free(s->sysv_path);
177         s->sysv_path = NULL;
178
179         free(s->sysv_runlevels);
180         s->sysv_runlevels = NULL;
181
182         free(s->status_text);
183         s->status_text = NULL;
184
185         exec_context_done(&s->exec_context);
186         exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
187         s->control_command = NULL;
188
189         /* This will leak a process, but at least no memory or any of
190          * our resources */
191         service_unwatch_main_pid(s);
192         service_unwatch_control_pid(s);
193
194         if (s->bus_name)  {
195                 unit_unwatch_bus_name(UNIT(u), s->bus_name);
196                 free(s->bus_name);
197                 s->bus_name = NULL;
198         }
199
200         service_close_socket_fd(s);
201
202         unit_unwatch_timer(u, &s->timer_watch);
203 }
204
205 static char *sysv_translate_name(const char *name) {
206         char *r;
207
208         if (!(r = new(char, strlen(name) + sizeof(".service"))))
209                 return NULL;
210
211         if (startswith(name, "boot."))
212                 /* Drop SuSE-style boot. prefix */
213                 strcpy(stpcpy(r, name + 5), ".service");
214         else if (endswith(name, ".sh"))
215                 /* Drop Debian-style .sh suffix */
216                 strcpy(stpcpy(r, name) - 3, ".service");
217         else
218                 /* Normal init scripts */
219                 strcpy(stpcpy(r, name), ".service");
220
221         return r;
222 }
223
224 static int sysv_translate_facility(const char *name, char **_r) {
225
226         static const char * const table[] = {
227                 /* LSB defined facilities */
228                 "$local_fs",  SPECIAL_LOCAL_FS_TARGET,
229                 "$network",   SPECIAL_NETWORK_TARGET,
230                 "$named",     SPECIAL_NSS_LOOKUP_TARGET,
231                 "$portmap",   SPECIAL_RPCBIND_TARGET,
232                 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
233                 "$syslog",    SPECIAL_SYSLOG_TARGET,
234                 "$time",      SPECIAL_RTC_SET_TARGET,
235
236                 /* Debian extensions */
237                 "$mail-transport-agent", SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
238                 "$mail-transfer-agent",  SPECIAL_MAIL_TRANSFER_AGENT_TARGET,
239                 "$x-display-manager",    SPECIAL_DISPLAY_MANAGER_SERVICE
240         };
241
242         unsigned i;
243         char *r;
244
245         for (i = 0; i < ELEMENTSOF(table); i += 2)
246                 if (streq(table[i], name)) {
247                         if (!(r = strdup(table[i+1])))
248                                 return -ENOMEM;
249
250                         goto finish;
251                 }
252
253         if (*name == '$')
254                 return 0;
255
256         if (!(r = sysv_translate_name(name)))
257                 return -ENOMEM;
258
259 finish:
260
261         if (_r)
262                 *_r = r;
263
264         return 1;
265 }
266
267 static int sysv_fix_order(Service *s) {
268         Meta *other;
269         int r;
270
271         assert(s);
272
273         if (s->sysv_start_priority < 0)
274                 return 0;
275
276         /* For each pair of services where at least one lacks a LSB
277          * header, we use the start priority value to order things. */
278
279         LIST_FOREACH(units_per_type, other, UNIT(s)->meta.manager->units_per_type[UNIT_SERVICE]) {
280                 Service *t;
281                 UnitDependency d;
282
283                 t = (Service*) other;
284
285                 if (s == t)
286                         continue;
287
288                 if (t->sysv_start_priority < 0)
289                         continue;
290
291                 /* If both units have modern headers we don't care
292                  * about the priorities */
293                 if ((!s->sysv_path || s->sysv_has_lsb) &&
294                     (!t->sysv_path || t->sysv_has_lsb))
295                         continue;
296
297                 if (t->sysv_start_priority < s->sysv_start_priority)
298                         d = UNIT_AFTER;
299                 else if (t->sysv_start_priority > s->sysv_start_priority)
300                         d = UNIT_BEFORE;
301                 else
302                         continue;
303
304                 /* FIXME: Maybe we should compare the name here lexicographically? */
305
306                 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
307                         return r;
308         }
309
310         return 0;
311 }
312
313 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
314         ExecCommand *c;
315
316         if (!(c = new0(ExecCommand, 1)))
317                 return NULL;
318
319         if (!(c->path = strdup(path))) {
320                 free(c);
321                 return NULL;
322         }
323
324         if (!(c->argv = strv_new(path, arg1, NULL))) {
325                 free(c->path);
326                 free(c);
327                 return NULL;
328         }
329
330         return c;
331 }
332
333 static int sysv_exec_commands(Service *s) {
334         ExecCommand *c;
335
336         assert(s);
337         assert(s->sysv_path);
338
339         if (!(c = exec_command_new(s->sysv_path, "start")))
340                 return -ENOMEM;
341         exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
342
343         if (!(c = exec_command_new(s->sysv_path, "stop")))
344                 return -ENOMEM;
345         exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
346
347         if (!(c = exec_command_new(s->sysv_path, "reload")))
348                 return -ENOMEM;
349         exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
350
351         return 0;
352 }
353
354 static int service_load_sysv_path(Service *s, const char *path) {
355         FILE *f;
356         Unit *u;
357         unsigned line = 0;
358         int r;
359         enum {
360                 NORMAL,
361                 DESCRIPTION,
362                 LSB,
363                 LSB_DESCRIPTION
364         } state = NORMAL;
365
366         assert(s);
367         assert(path);
368
369         u = UNIT(s);
370
371         if (!(f = fopen(path, "re"))) {
372                 r = errno == ENOENT ? 0 : -errno;
373                 goto finish;
374         }
375
376         free(s->sysv_path);
377         if (!(s->sysv_path = strdup(path))) {
378                 r = -ENOMEM;
379                 goto finish;
380         }
381
382         while (!feof(f)) {
383                 char l[LINE_MAX], *t;
384
385                 if (!fgets(l, sizeof(l), f)) {
386                         if (feof(f))
387                                 break;
388
389                         r = -errno;
390                         log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
391                         goto finish;
392                 }
393
394                 line++;
395
396                 t = strstrip(l);
397                 if (*t != '#')
398                         continue;
399
400                 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
401                         state = LSB;
402                         s->sysv_has_lsb = true;
403                         continue;
404                 }
405
406                 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
407                         state = NORMAL;
408                         continue;
409                 }
410
411                 t++;
412                 t += strspn(t, WHITESPACE);
413
414                 if (state == NORMAL) {
415
416                         /* Try to parse Red Hat style chkconfig headers */
417
418                         if (startswith_no_case(t, "chkconfig:")) {
419                                 int start_priority;
420                                 char runlevels[16], *k;
421
422                                 state = NORMAL;
423
424                                 if (sscanf(t+10, "%15s %i %*i",
425                                            runlevels,
426                                            &start_priority) != 2) {
427
428                                         log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
429                                         continue;
430                                 }
431
432                                 /* A start priority gathered from the
433                                  * symlink farms is preferred over the
434                                  * data from the LSB header. */
435                                 if (start_priority < 0 || start_priority > 99)
436                                         log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
437                                 else if (s->sysv_start_priority < 0)
438                                         s->sysv_start_priority = start_priority;
439
440                                 char_array_0(runlevels);
441                                 k = delete_chars(runlevels, WHITESPACE "-");
442
443                                 if (k[0]) {
444                                         char *d;
445
446                                         if (!(d = strdup(k))) {
447                                                 r = -ENOMEM;
448                                                 goto finish;
449                                         }
450
451                                         free(s->sysv_runlevels);
452                                         s->sysv_runlevels = d;
453                                 }
454
455                         } else if (startswith_no_case(t, "description:")) {
456
457                                 size_t k = strlen(t);
458                                 char *d;
459
460                                 if (t[k-1] == '\\') {
461                                         state = DESCRIPTION;
462                                         t[k-1] = 0;
463                                 }
464
465                                 if (!(d = strdup(strstrip(t+12)))) {
466                                         r = -ENOMEM;
467                                         goto finish;
468                                 }
469
470                                 free(u->meta.description);
471                                 u->meta.description = d;
472
473                         } else if (startswith_no_case(t, "pidfile:")) {
474
475                                 char *fn;
476
477                                 state = NORMAL;
478
479                                 fn = strstrip(t+8);
480                                 if (!path_is_absolute(fn)) {
481                                         log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
482                                         continue;
483                                 }
484
485                                 if (!(fn = strdup(fn))) {
486                                         r = -ENOMEM;
487                                         goto finish;
488                                 }
489
490                                 free(s->pid_file);
491                                 s->pid_file = fn;
492                         }
493
494                 } else if (state == DESCRIPTION) {
495
496                         /* Try to parse Red Hat style description
497                          * continuation */
498
499                         size_t k = strlen(t);
500                         char *d;
501
502                         if (t[k-1] == '\\')
503                                 t[k-1] = 0;
504                         else
505                                 state = NORMAL;
506
507                         assert(u->meta.description);
508                         if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
509                                 r = -ENOMEM;
510                                 goto finish;
511                         }
512
513                         free(u->meta.description);
514                         u->meta.description = d;
515
516                 } else if (state == LSB || state == LSB_DESCRIPTION) {
517
518                         if (startswith_no_case(t, "Provides:")) {
519                                 char *i, *w;
520                                 size_t z;
521
522                                 state = LSB;
523
524                                 FOREACH_WORD(w, z, t+9, i) {
525                                         char *n, *m;
526
527                                         if (!(n = strndup(w, z))) {
528                                                 r = -ENOMEM;
529                                                 goto finish;
530                                         }
531
532                                         r = sysv_translate_facility(n, &m);
533                                         free(n);
534
535                                         if (r < 0)
536                                                 goto finish;
537
538                                         if (r == 0)
539                                                 continue;
540
541                                         if (unit_name_to_type(m) == UNIT_SERVICE)
542                                                 r = unit_add_name(u, m);
543                                         else {
544                                                 if ((r = unit_add_dependency_by_name_inverse(u, UNIT_REQUIRES, m, NULL, true)) >= 0)
545                                                         r = unit_add_dependency_by_name(u, UNIT_BEFORE, m, NULL, true);
546                                         }
547
548                                         free(m);
549
550                                         if (r < 0)
551                                                 goto finish;
552                                 }
553
554                         } else if (startswith_no_case(t, "Required-Start:") ||
555                                    startswith_no_case(t, "Should-Start:") ||
556                                    startswith_no_case(t, "X-Start-Before:") ||
557                                    startswith_no_case(t, "X-Start-After:")) {
558                                 char *i, *w;
559                                 size_t z;
560
561                                 state = LSB;
562
563                                 FOREACH_WORD(w, z, strchr(t, ':')+1, i) {
564                                         char *n, *m;
565
566                                         if (!(n = strndup(w, z))) {
567                                                 r = -ENOMEM;
568                                                 goto finish;
569                                         }
570
571                                         r = sysv_translate_facility(n, &m);
572                                         free(n);
573
574                                         if (r < 0)
575                                                 goto finish;
576
577                                         if (r == 0)
578                                                 continue;
579
580                                         r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
581                                         free(m);
582
583                                         if (r < 0)
584                                                 goto finish;
585                                 }
586                         } else if (startswith_no_case(t, "Default-Start:")) {
587                                 char *k, *d;
588
589                                 state = LSB;
590
591                                 k = delete_chars(t+14, WHITESPACE "-");
592
593                                 if (k[0] != 0) {
594                                         if (!(d = strdup(k))) {
595                                                 r = -ENOMEM;
596                                                 goto finish;
597                                         }
598
599                                         free(s->sysv_runlevels);
600                                         s->sysv_runlevels = d;
601                                 }
602
603                         } else if (startswith_no_case(t, "Description:")) {
604                                 char *d;
605
606                                 state = LSB_DESCRIPTION;
607
608                                 if (!(d = strdup(strstrip(t+12)))) {
609                                         r = -ENOMEM;
610                                         goto finish;
611                                 }
612
613                                 free(u->meta.description);
614                                 u->meta.description = d;
615
616                         } else if (startswith_no_case(t, "Short-Description:") &&
617                                    !u->meta.description) {
618                                 char *d;
619
620                                 /* We use the short description only
621                                  * if no long description is set. */
622
623                                 state = LSB;
624
625                                 if (!(d = strdup(strstrip(t+18)))) {
626                                         r = -ENOMEM;
627                                         goto finish;
628                                 }
629
630                                 u->meta.description = d;
631
632                         } else if (startswith_no_case(t, "X-Interactive:")) {
633                                 int b;
634
635                                 if ((b = parse_boolean(strstrip(t+14))) < 0) {
636                                         log_warning("[%s:%u] Couldn't parse interactive flag. Ignoring.", path, line);
637                                         continue;
638                                 }
639
640                                 if (b)
641                                         s->exec_context.std_input = EXEC_INPUT_TTY;
642                                 else
643                                         s->exec_context.std_input = EXEC_INPUT_NULL;
644
645                         } else if (state == LSB_DESCRIPTION) {
646
647                                 if (startswith(l, "#\t") || startswith(l, "#  ")) {
648                                         char *d;
649
650                                         assert(u->meta.description);
651                                         if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
652                                                 r = -ENOMEM;
653                                                 goto finish;
654                                         }
655
656                                         free(u->meta.description);
657                                         u->meta.description = d;
658                                 } else
659                                         state = LSB;
660                         }
661                 }
662         }
663
664         if ((r = sysv_exec_commands(s)) < 0)
665                 goto finish;
666
667         if (!s->sysv_runlevels || chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
668                 /* If there a runlevels configured for this service
669                  * but none of the standard ones, then we assume this
670                  * is some special kind of service (which might be
671                  * needed for early boot) and don't create any links
672                  * to it. */
673
674                 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0 ||
675                     (r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
676                         goto finish;
677
678         } else
679                 /* Don't timeout special services during boot (like fsck) */
680                 s->timeout_usec = 0;
681
682         /* Special setting for all SysV services */
683         s->type = SERVICE_FORKING;
684         s->valid_no_process = true;
685         s->kill_mode = KILL_PROCESS_GROUP;
686         s->restart = SERVICE_ONCE;
687
688         u->meta.load_state = UNIT_LOADED;
689         r = 0;
690
691 finish:
692
693         if (f)
694                 fclose(f);
695
696         return r;
697 }
698
699 static int service_load_sysv_name(Service *s, const char *name) {
700         char **p;
701
702         assert(s);
703         assert(name);
704
705         /* For SysV services we strip the boot. or .sh
706          * prefixes/suffixes. */
707         if (startswith(name, "boot.") ||
708             endswith(name, ".sh.service"))
709                 return -ENOENT;
710
711         STRV_FOREACH(p, UNIT(s)->meta.manager->lookup_paths.sysvinit_path) {
712                 char *path;
713                 int r;
714
715                 if (asprintf(&path, "%s/%s", *p, name) < 0)
716                         return -ENOMEM;
717
718                 assert(endswith(path, ".service"));
719                 path[strlen(path)-8] = 0;
720
721                 r = service_load_sysv_path(s, path);
722
723                 if (r >= 0 && UNIT(s)->meta.load_state == UNIT_STUB) {
724                         /* Try Debian style xxx.sh source'able init scripts */
725                         strcat(path, ".sh");
726                         r = service_load_sysv_path(s, path);
727                 }
728
729                 free(path);
730
731                 if (r >= 0 && UNIT(s)->meta.load_state == UNIT_STUB) {
732                         /* Try SUSE style boot.xxx init scripts */
733
734                         if (asprintf(&path, "%s/boot.%s", *p, name) < 0)
735                                 return -ENOMEM;
736
737                         path[strlen(path)-8] = 0;
738                         r = service_load_sysv_path(s, path);
739                         free(path);
740                 }
741
742                 if (r < 0)
743                         return r;
744
745                 if ((UNIT(s)->meta.load_state != UNIT_STUB))
746                         break;
747         }
748
749         return 0;
750 }
751
752 static int service_load_sysv(Service *s) {
753         const char *t;
754         Iterator i;
755         int r;
756
757         assert(s);
758
759         /* Load service data from SysV init scripts, preferably with
760          * LSB headers ... */
761
762         if (strv_isempty(UNIT(s)->meta.manager->lookup_paths.sysvinit_path))
763                 return 0;
764
765         if ((t = UNIT(s)->meta.id))
766                 if ((r = service_load_sysv_name(s, t)) < 0)
767                         return r;
768
769         if (UNIT(s)->meta.load_state == UNIT_STUB)
770                 SET_FOREACH(t, UNIT(s)->meta.names, i) {
771                         if (t == UNIT(s)->meta.id)
772                                 continue;
773
774                         if ((r == service_load_sysv_name(s, t)) < 0)
775                                 return r;
776
777                         if (UNIT(s)->meta.load_state != UNIT_STUB)
778                                 break;
779                 }
780
781         return 0;
782 }
783
784 static int service_add_bus_name(Service *s) {
785         char *n;
786         int r;
787
788         assert(s);
789         assert(s->bus_name);
790
791         if (asprintf(&n, "dbus-%s.service", s->bus_name) < 0)
792                 return 0;
793
794         r = unit_merge_by_name(UNIT(s), n);
795         free(n);
796
797         return r;
798 }
799
800 static int service_verify(Service *s) {
801         assert(s);
802
803         if (UNIT(s)->meta.load_state != UNIT_LOADED)
804                 return 0;
805
806         if (!s->exec_command[SERVICE_EXEC_START]) {
807                 log_error("%s lacks ExecStart setting. Refusing.", UNIT(s)->meta.id);
808                 return -EINVAL;
809         }
810
811         if (s->type == SERVICE_DBUS && !s->bus_name) {
812                 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->meta.id);
813                 return -EINVAL;
814         }
815
816         return 0;
817 }
818
819 static int service_load(Unit *u) {
820         int r;
821         Service *s = SERVICE(u);
822
823         assert(s);
824
825         /* Load a .service file */
826         if ((r = unit_load_fragment(u)) < 0)
827                 return r;
828
829         /* Load a classic init script as a fallback, if we couldn't find anything */
830         if (u->meta.load_state == UNIT_STUB)
831                 if ((r = service_load_sysv(s)) < 0)
832                         return r;
833
834         /* Still nothing found? Then let's give up */
835         if (u->meta.load_state == UNIT_STUB)
836                 return -ENOENT;
837
838         /* We were able to load something, then let's add in the
839          * dropin directories. */
840         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
841                 return r;
842
843         /* This is a new unit? Then let's add in some extras */
844         if (u->meta.load_state == UNIT_LOADED) {
845                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
846                         return r;
847
848                 if ((r = unit_add_default_cgroup(u)) < 0)
849                         return r;
850
851                 if ((r = sysv_fix_order(s)) < 0)
852                         return r;
853
854                 if (s->bus_name) {
855                         if ((r = service_add_bus_name(s)) < 0)
856                                 return r;
857
858                         if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
859                             return r;
860                 }
861         }
862
863         return service_verify(s);
864 }
865
866 static void service_dump(Unit *u, FILE *f, const char *prefix) {
867
868         ServiceExecCommand c;
869         Service *s = SERVICE(u);
870         const char *prefix2;
871         char *p2;
872
873         assert(s);
874
875         p2 = strappend(prefix, "\t");
876         prefix2 = p2 ? p2 : prefix;
877
878         fprintf(f,
879                 "%sService State: %s\n"
880                 "%sPermissionsStartOnly: %s\n"
881                 "%sRootDirectoryStartOnly: %s\n"
882                 "%sValidNoProcess: %s\n"
883                 "%sKillMode: %s\n"
884                 "%sType: %s\n",
885                 prefix, service_state_to_string(s->state),
886                 prefix, yes_no(s->permissions_start_only),
887                 prefix, yes_no(s->root_directory_start_only),
888                 prefix, yes_no(s->valid_no_process),
889                 prefix, kill_mode_to_string(s->kill_mode),
890                 prefix, service_type_to_string(s->type));
891
892         if (s->control_pid > 0)
893                 fprintf(f,
894                         "%sControl PID: %llu\n",
895                         prefix, (unsigned long long) s->control_pid);
896
897         if (s->main_pid > 0)
898                 fprintf(f,
899                         "%sMain PID: %llu\n",
900                         prefix, (unsigned long long) s->main_pid);
901
902         if (s->pid_file)
903                 fprintf(f,
904                         "%sPIDFile: %s\n",
905                         prefix, s->pid_file);
906
907         if (s->bus_name)
908                 fprintf(f,
909                         "%sBusName: %s\n"
910                         "%sBus Name Good: %s\n",
911                         prefix, s->bus_name,
912                         prefix, yes_no(s->bus_name_good));
913
914         exec_context_dump(&s->exec_context, f, prefix);
915
916         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
917
918                 if (!s->exec_command[c])
919                         continue;
920
921                 fprintf(f, "%s-> %s:\n",
922                         prefix, service_exec_command_to_string(c));
923
924                 exec_command_dump_list(s->exec_command[c], f, prefix2);
925         }
926
927         if (s->sysv_path)
928                 fprintf(f,
929                         "%sSysV Init Script Path: %s\n"
930                         "%sSysV Init Script has LSB Header: %s\n",
931                         prefix, s->sysv_path,
932                         prefix, yes_no(s->sysv_has_lsb));
933
934         if (s->sysv_start_priority >= 0)
935                 fprintf(f,
936                         "%sSysVStartPriority: %i\n",
937                         prefix, s->sysv_start_priority);
938
939         if (s->sysv_runlevels)
940                 fprintf(f, "%sSysVRunLevels: %s\n",
941                         prefix, s->sysv_runlevels);
942
943         if (s->status_text)
944                 fprintf(f, "%sStatus Text: %s\n",
945                         prefix, s->status_text);
946
947         free(p2);
948 }
949
950 static int service_load_pid_file(Service *s) {
951         char *k;
952         int r;
953         pid_t pid;
954
955         assert(s);
956
957         if (s->main_pid_known)
958                 return 0;
959
960         assert(s->main_pid <= 0);
961
962         if (!s->pid_file)
963                 return -ENOENT;
964
965         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
966                 return r;
967
968         r = parse_pid(k, &pid);
969         free(k);
970
971         if (r < 0)
972                 return r;
973
974         if (kill(pid, 0) < 0 && errno != EPERM) {
975                 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
976                             (unsigned long) pid, s->pid_file);
977                 return -ESRCH;
978         }
979
980         if ((r = service_set_main_pid(s, pid)) < 0)
981                 return r;
982
983         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
984                 /* FIXME: we need to do something here */
985                 return r;
986
987         return 0;
988 }
989
990 static int service_get_sockets(Service *s, Set **_set) {
991         Set *set;
992         Iterator i;
993         char *t;
994         int r;
995
996         assert(s);
997         assert(_set);
998
999         /* Collects all Socket objects that belong to this
1000          * service. Note that a service might have multiple sockets
1001          * via multiple names. */
1002
1003         if (!(set = set_new(NULL, NULL)))
1004                 return -ENOMEM;
1005
1006         SET_FOREACH(t, UNIT(s)->meta.names, i) {
1007                 char *k;
1008                 Unit *p;
1009
1010                 /* Look for all socket objects that go by any of our
1011                  * units and collect their fds */
1012
1013                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1014                         r = -ENOMEM;
1015                         goto fail;
1016                 }
1017
1018                 p = manager_get_unit(UNIT(s)->meta.manager, k);
1019                 free(k);
1020
1021                 if (!p)
1022                         continue;
1023
1024                 if ((r = set_put(set, p)) < 0)
1025                         goto fail;
1026         }
1027
1028         *_set = set;
1029         return 0;
1030
1031 fail:
1032         set_free(set);
1033         return r;
1034 }
1035
1036 static int service_notify_sockets_dead(Service *s) {
1037         Iterator i;
1038         Set *set;
1039         Socket *sock;
1040         int r;
1041
1042         assert(s);
1043
1044         /* Notifies all our sockets when we die */
1045         if ((r = service_get_sockets(s, &set)) < 0)
1046                 return r;
1047
1048         SET_FOREACH(sock, set, i)
1049                 socket_notify_service_dead(sock);
1050
1051         set_free(set);
1052
1053         return 0;
1054 }
1055
1056 static void service_set_state(Service *s, ServiceState state) {
1057         ServiceState old_state;
1058         assert(s);
1059
1060         old_state = s->state;
1061         s->state = state;
1062
1063         if (state != SERVICE_START_PRE &&
1064             state != SERVICE_START &&
1065             state != SERVICE_START_POST &&
1066             state != SERVICE_RELOAD &&
1067             state != SERVICE_STOP &&
1068             state != SERVICE_STOP_SIGTERM &&
1069             state != SERVICE_STOP_SIGKILL &&
1070             state != SERVICE_STOP_POST &&
1071             state != SERVICE_FINAL_SIGTERM &&
1072             state != SERVICE_FINAL_SIGKILL &&
1073             state != SERVICE_AUTO_RESTART)
1074                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1075
1076         if (state != SERVICE_START &&
1077             state != SERVICE_START_POST &&
1078             state != SERVICE_RUNNING &&
1079             state != SERVICE_RELOAD &&
1080             state != SERVICE_STOP &&
1081             state != SERVICE_STOP_SIGTERM &&
1082             state != SERVICE_STOP_SIGKILL)
1083                 service_unwatch_main_pid(s);
1084
1085         if (state != SERVICE_START_PRE &&
1086             state != SERVICE_START &&
1087             state != SERVICE_START_POST &&
1088             state != SERVICE_RELOAD &&
1089             state != SERVICE_STOP &&
1090             state != SERVICE_STOP_SIGTERM &&
1091             state != SERVICE_STOP_SIGKILL &&
1092             state != SERVICE_STOP_POST &&
1093             state != SERVICE_FINAL_SIGTERM &&
1094             state != SERVICE_FINAL_SIGKILL) {
1095                 service_unwatch_control_pid(s);
1096                 s->control_command = NULL;
1097                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1098         }
1099
1100         if (state == SERVICE_DEAD ||
1101             state == SERVICE_STOP ||
1102             state == SERVICE_STOP_SIGTERM ||
1103             state == SERVICE_STOP_SIGKILL ||
1104             state == SERVICE_STOP_POST ||
1105             state == SERVICE_FINAL_SIGTERM ||
1106             state == SERVICE_FINAL_SIGKILL ||
1107             state == SERVICE_MAINTENANCE ||
1108             state == SERVICE_AUTO_RESTART)
1109                 service_notify_sockets_dead(s);
1110
1111         if (state != SERVICE_START_PRE &&
1112             state != SERVICE_START &&
1113             !(state == SERVICE_DEAD && UNIT(s)->meta.job))
1114                 service_close_socket_fd(s);
1115
1116         if (old_state != state)
1117                 log_debug("%s changed %s -> %s", UNIT(s)->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1118
1119         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1120 }
1121
1122 static int service_coldplug(Unit *u) {
1123         Service *s = SERVICE(u);
1124         int r;
1125
1126         assert(s);
1127         assert(s->state == SERVICE_DEAD);
1128
1129         if (s->deserialized_state != s->state) {
1130
1131                 if (s->deserialized_state == SERVICE_START_PRE ||
1132                     s->deserialized_state == SERVICE_START ||
1133                     s->deserialized_state == SERVICE_START_POST ||
1134                     s->deserialized_state == SERVICE_RELOAD ||
1135                     s->deserialized_state == SERVICE_STOP ||
1136                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1137                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1138                     s->deserialized_state == SERVICE_STOP_POST ||
1139                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1140                     s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1141                     s->deserialized_state == SERVICE_AUTO_RESTART) {
1142
1143                         if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1144                                 usec_t k;
1145
1146                                 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1147
1148                                 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1149                                         return r;
1150                         }
1151                 }
1152
1153                 if ((s->deserialized_state == SERVICE_START &&
1154                      (s->type == SERVICE_FORKING ||
1155                       s->type == SERVICE_DBUS ||
1156                       s->type == SERVICE_FINISH ||
1157                       s->type == SERVICE_NOTIFY)) ||
1158                     s->deserialized_state == SERVICE_START_POST ||
1159                     s->deserialized_state == SERVICE_RUNNING ||
1160                     s->deserialized_state == SERVICE_RELOAD ||
1161                     s->deserialized_state == SERVICE_STOP ||
1162                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1163                     s->deserialized_state == SERVICE_STOP_SIGKILL)
1164                         if (s->main_pid > 0)
1165                                 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1166                                         return r;
1167
1168                 if (s->deserialized_state == SERVICE_START_PRE ||
1169                     s->deserialized_state == SERVICE_START ||
1170                     s->deserialized_state == SERVICE_START_POST ||
1171                     s->deserialized_state == SERVICE_RELOAD ||
1172                     s->deserialized_state == SERVICE_STOP ||
1173                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1174                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1175                     s->deserialized_state == SERVICE_STOP_POST ||
1176                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1177                     s->deserialized_state == SERVICE_FINAL_SIGKILL)
1178                         if (s->control_pid > 0)
1179                                 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1180                                         return r;
1181
1182                 service_set_state(s, s->deserialized_state);
1183         }
1184
1185         return 0;
1186 }
1187
1188 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1189         Iterator i;
1190         int r;
1191         int *rfds = NULL;
1192         unsigned rn_fds = 0;
1193         Set *set;
1194         Socket *sock;
1195
1196         assert(s);
1197         assert(fds);
1198         assert(n_fds);
1199
1200         if ((r = service_get_sockets(s, &set)) < 0)
1201                 return r;
1202
1203         SET_FOREACH(sock, set, i) {
1204                 int *cfds;
1205                 unsigned cn_fds;
1206
1207                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1208                         goto fail;
1209
1210                 if (!cfds)
1211                         continue;
1212
1213                 if (!rfds) {
1214                         rfds = cfds;
1215                         rn_fds = cn_fds;
1216                 } else {
1217                         int *t;
1218
1219                         if (!(t = new(int, rn_fds+cn_fds))) {
1220                                 free(cfds);
1221                                 r = -ENOMEM;
1222                                 goto fail;
1223                         }
1224
1225                         memcpy(t, rfds, rn_fds);
1226                         memcpy(t+rn_fds, cfds, cn_fds);
1227                         free(rfds);
1228                         free(cfds);
1229
1230                         rfds = t;
1231                         rn_fds = rn_fds+cn_fds;
1232                 }
1233         }
1234
1235         *fds = rfds;
1236         *n_fds = rn_fds;
1237
1238         set_free(set);
1239
1240         return 0;
1241
1242 fail:
1243         set_free(set);
1244         free(rfds);
1245
1246         return r;
1247 }
1248
1249 static int service_spawn(
1250                 Service *s,
1251                 ExecCommand *c,
1252                 bool timeout,
1253                 bool pass_fds,
1254                 bool apply_permissions,
1255                 bool apply_chroot,
1256                 pid_t *_pid) {
1257
1258         pid_t pid;
1259         int r;
1260         int *fds = NULL;
1261         unsigned n_fds = 0;
1262         char **argv;
1263
1264         assert(s);
1265         assert(c);
1266         assert(_pid);
1267
1268         if (pass_fds) {
1269                 if (s->socket_fd >= 0) {
1270                         fds = &s->socket_fd;
1271                         n_fds = 1;
1272                 } else if ((r = service_collect_fds(s, &fds, &n_fds)) < 0)
1273                         goto fail;
1274         }
1275
1276         if (timeout && s->timeout_usec) {
1277                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1278                         goto fail;
1279         } else
1280                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1281
1282         if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1283                 r = -ENOMEM;
1284                 goto fail;
1285         }
1286
1287         r = exec_spawn(c,
1288                        argv,
1289                        &s->exec_context,
1290                        fds, n_fds,
1291                        s->meta.manager->environment,
1292                        apply_permissions,
1293                        apply_chroot,
1294                        UNIT(s)->meta.manager->confirm_spawn,
1295                        UNIT(s)->meta.cgroup_bondings,
1296                        &pid);
1297
1298         strv_free(argv);
1299         if (r < 0)
1300                 goto fail;
1301
1302         if (fds) {
1303                 if (s->socket_fd >= 0)
1304                         service_close_socket_fd(s);
1305                 else
1306                         free(fds);
1307         }
1308
1309         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1310                 /* FIXME: we need to do something here */
1311                 goto fail;
1312
1313         *_pid = pid;
1314
1315         return 0;
1316
1317 fail:
1318         free(fds);
1319
1320         if (timeout)
1321                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1322
1323         return r;
1324 }
1325
1326 static int main_pid_good(Service *s) {
1327         assert(s);
1328
1329         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1330          * don't know */
1331
1332         /* If we know the pid file, then lets just check if it is
1333          * still valid */
1334         if (s->main_pid_known)
1335                 return s->main_pid > 0;
1336
1337         /* We don't know the pid */
1338         return -EAGAIN;
1339 }
1340
1341 static int control_pid_good(Service *s) {
1342         assert(s);
1343
1344         return s->control_pid > 0;
1345 }
1346
1347 static int cgroup_good(Service *s) {
1348         int r;
1349
1350         assert(s);
1351
1352         if (s->valid_no_process)
1353                 return -EAGAIN;
1354
1355         if ((r = cgroup_bonding_is_empty_list(UNIT(s)->meta.cgroup_bondings)) < 0)
1356                 return r;
1357
1358         return !r;
1359 }
1360
1361 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1362         int r;
1363         assert(s);
1364
1365         if (!success)
1366                 s->failure = true;
1367
1368         if (allow_restart &&
1369             s->allow_restart &&
1370             (s->restart == SERVICE_RESTART_ALWAYS ||
1371              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1372
1373                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1374                         goto fail;
1375
1376                 service_set_state(s, SERVICE_AUTO_RESTART);
1377         } else
1378                 service_set_state(s, s->failure ? SERVICE_MAINTENANCE : SERVICE_DEAD);
1379
1380         return;
1381
1382 fail:
1383         log_warning("%s failed to run install restart timer: %s", UNIT(s)->meta.id, strerror(-r));
1384         service_enter_dead(s, false, false);
1385 }
1386
1387 static void service_enter_signal(Service *s, ServiceState state, bool success);
1388
1389 static void service_enter_stop_post(Service *s, bool success) {
1390         int r;
1391         assert(s);
1392
1393         if (!success)
1394                 s->failure = true;
1395
1396         service_unwatch_control_pid(s);
1397
1398         s->control_command_id = SERVICE_EXEC_STOP_POST;
1399         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1400                 if ((r = service_spawn(s,
1401                                        s->control_command,
1402                                        true,
1403                                        false,
1404                                        !s->permissions_start_only,
1405                                        !s->root_directory_start_only,
1406                                        &s->control_pid)) < 0)
1407                         goto fail;
1408
1409
1410                 service_set_state(s, SERVICE_STOP_POST);
1411         } else
1412                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1413
1414         return;
1415
1416 fail:
1417         log_warning("%s failed to run 'stop-post' task: %s", UNIT(s)->meta.id, strerror(-r));
1418         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1419 }
1420
1421 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1422         int r;
1423         bool sent = false;
1424
1425         assert(s);
1426
1427         if (!success)
1428                 s->failure = true;
1429
1430         if (s->kill_mode != KILL_NONE) {
1431                 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1432
1433                 if (s->kill_mode == KILL_CONTROL_GROUP) {
1434
1435                         if ((r = cgroup_bonding_kill_list(UNIT(s)->meta.cgroup_bondings, sig)) < 0) {
1436                                 if (r != -EAGAIN && r != -ESRCH)
1437                                         goto fail;
1438                         } else
1439                                 sent = true;
1440                 }
1441
1442                 if (!sent) {
1443                         r = 0;
1444
1445                         if (s->main_pid > 0) {
1446                                 if (kill(s->kill_mode == KILL_PROCESS ? s->main_pid : -s->main_pid, sig) < 0 && errno != ESRCH)
1447                                         r = -errno;
1448                                 else
1449                                         sent = true;
1450                         }
1451
1452                         if (s->control_pid > 0) {
1453                                 if (kill(s->kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH)
1454                                         r = -errno;
1455                                 else
1456                                         sent = true;
1457                         }
1458
1459                         if (r < 0)
1460                                 goto fail;
1461                 }
1462         }
1463
1464         if (sent && (s->main_pid > 0 || s->control_pid > 0)) {
1465                 if (s->timeout_usec > 0)
1466                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1467                                 goto fail;
1468
1469                 service_set_state(s, state);
1470         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1471                 service_enter_stop_post(s, true);
1472         else
1473                 service_enter_dead(s, true, true);
1474
1475         return;
1476
1477 fail:
1478         log_warning("%s failed to kill processes: %s", UNIT(s)->meta.id, strerror(-r));
1479
1480         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1481                 service_enter_stop_post(s, false);
1482         else
1483                 service_enter_dead(s, false, true);
1484 }
1485
1486 static void service_enter_stop(Service *s, bool success) {
1487         int r;
1488         pid_t pid;
1489
1490         assert(s);
1491
1492         if (!success)
1493                 s->failure = true;
1494
1495         service_unwatch_control_pid(s);
1496
1497         s->control_command_id = SERVICE_EXEC_STOP;
1498         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1499                 if ((r = service_spawn(s,
1500                                        s->control_command,
1501                                        true,
1502                                        false,
1503                                        !s->permissions_start_only,
1504                                        !s->root_directory_start_only,
1505                                        &pid)) < 0)
1506                         goto fail;
1507
1508                 service_set_control_pid(s, pid);
1509                 service_set_state(s, SERVICE_STOP);
1510         } else
1511                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1512
1513         return;
1514
1515 fail:
1516         log_warning("%s failed to run 'stop' task: %s", UNIT(s)->meta.id, strerror(-r));
1517         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1518 }
1519
1520 static void service_enter_running(Service *s, bool success) {
1521         assert(s);
1522
1523         if (!success)
1524                 s->failure = true;
1525
1526         if (main_pid_good(s) != 0 &&
1527             cgroup_good(s) != 0 &&
1528             (s->bus_name_good || s->type != SERVICE_DBUS))
1529                 service_set_state(s, SERVICE_RUNNING);
1530         else if (s->valid_no_process)
1531                 service_set_state(s, SERVICE_EXITED);
1532         else
1533                 service_enter_stop(s, true);
1534 }
1535
1536 static void service_enter_start_post(Service *s) {
1537         int r;
1538         pid_t pid;
1539         assert(s);
1540
1541         service_unwatch_control_pid(s);
1542
1543         s->control_command_id = SERVICE_EXEC_START_POST;
1544         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1545                 if ((r = service_spawn(s,
1546                                        s->control_command,
1547                                        true,
1548                                        false,
1549                                        !s->permissions_start_only,
1550                                        !s->root_directory_start_only,
1551                                        &pid)) < 0)
1552                         goto fail;
1553
1554                 service_set_control_pid(s, pid);
1555                 service_set_state(s, SERVICE_START_POST);
1556         } else
1557                 service_enter_running(s, true);
1558
1559         return;
1560
1561 fail:
1562         log_warning("%s failed to run 'start-post' task: %s", UNIT(s)->meta.id, strerror(-r));
1563         service_enter_stop(s, false);
1564 }
1565
1566 static void service_enter_start(Service *s) {
1567         pid_t pid;
1568         int r;
1569
1570         assert(s);
1571
1572         assert(s->exec_command[SERVICE_EXEC_START]);
1573         assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1574
1575         if (s->type == SERVICE_FORKING)
1576                 service_unwatch_control_pid(s);
1577         else
1578                 service_unwatch_main_pid(s);
1579
1580         if ((r = service_spawn(s,
1581                                s->exec_command[SERVICE_EXEC_START],
1582                                s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1583                                true,
1584                                true,
1585                                true,
1586                                &pid)) < 0)
1587                 goto fail;
1588
1589         if (s->type == SERVICE_SIMPLE) {
1590                 /* For simple services we immediately start
1591                  * the START_POST binaries. */
1592
1593                 service_set_main_pid(s, pid);
1594                 service_enter_start_post(s);
1595
1596         } else  if (s->type == SERVICE_FORKING) {
1597
1598                 /* For forking services we wait until the start
1599                  * process exited. */
1600
1601                 s->control_command_id = SERVICE_EXEC_START;
1602                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1603
1604                 service_set_control_pid(s, pid);
1605                 service_set_state(s, SERVICE_START);
1606
1607         } else if (s->type == SERVICE_FINISH ||
1608                    s->type == SERVICE_DBUS ||
1609                    s->type == SERVICE_NOTIFY) {
1610
1611                 /* For finishing services we wait until the start
1612                  * process exited, too, but it is our main process. */
1613
1614                 /* For D-Bus services we know the main pid right away,
1615                  * but wait for the bus name to appear on the
1616                  * bus. Notify services are similar. */
1617
1618                 service_set_main_pid(s, pid);
1619                 service_set_state(s, SERVICE_START);
1620         } else
1621                 assert_not_reached("Unknown service type");
1622
1623         return;
1624
1625 fail:
1626         log_warning("%s failed to run 'start' task: %s", UNIT(s)->meta.id, strerror(-r));
1627         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1628 }
1629
1630 static void service_enter_start_pre(Service *s) {
1631         int r;
1632         pid_t pid;
1633
1634         assert(s);
1635
1636         service_unwatch_control_pid(s);
1637
1638         s->control_command_id = SERVICE_EXEC_START_PRE;
1639         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1640                 if ((r = service_spawn(s,
1641                                        s->control_command,
1642                                        true,
1643                                        false,
1644                                        !s->permissions_start_only,
1645                                        !s->root_directory_start_only,
1646                                        &pid)) < 0)
1647                         goto fail;
1648
1649                 service_set_control_pid(s, pid);
1650                 service_set_state(s, SERVICE_START_PRE);
1651         } else
1652                 service_enter_start(s);
1653
1654         return;
1655
1656 fail:
1657         log_warning("%s failed to run 'start-pre' task: %s", UNIT(s)->meta.id, strerror(-r));
1658         service_enter_dead(s, false, true);
1659 }
1660
1661 static void service_enter_restart(Service *s) {
1662         int r;
1663         assert(s);
1664
1665         service_enter_dead(s, true, false);
1666
1667         if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL)) < 0)
1668                 goto fail;
1669
1670         log_debug("%s scheduled restart job.", UNIT(s)->meta.id);
1671         return;
1672
1673 fail:
1674
1675         log_warning("%s failed to schedule restart job: %s", UNIT(s)->meta.id, strerror(-r));
1676         service_enter_dead(s, false, false);
1677 }
1678
1679 static void service_enter_reload(Service *s) {
1680         int r;
1681         pid_t pid;
1682
1683         assert(s);
1684
1685         service_unwatch_control_pid(s);
1686
1687         s->control_command_id = SERVICE_EXEC_RELOAD;
1688         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1689                 if ((r = service_spawn(s,
1690                                        s->control_command,
1691                                        true,
1692                                        false,
1693                                        !s->permissions_start_only,
1694                                        !s->root_directory_start_only,
1695                                        &pid)) < 0)
1696                         goto fail;
1697
1698                 service_set_control_pid(s, pid);
1699                 service_set_state(s, SERVICE_RELOAD);
1700         } else
1701                 service_enter_running(s, true);
1702
1703         return;
1704
1705 fail:
1706         log_warning("%s failed to run 'reload' task: %s", UNIT(s)->meta.id, strerror(-r));
1707         service_enter_stop(s, false);
1708 }
1709
1710 static void service_run_next(Service *s, bool success) {
1711         int r;
1712         pid_t pid;
1713
1714         assert(s);
1715         assert(s->control_command);
1716         assert(s->control_command->command_next);
1717
1718         if (!success)
1719                 s->failure = true;
1720
1721         s->control_command = s->control_command->command_next;
1722
1723         service_unwatch_control_pid(s);
1724
1725         if ((r = service_spawn(s,
1726                                s->control_command,
1727                                true,
1728                                false,
1729                                !s->permissions_start_only,
1730                                !s->root_directory_start_only,
1731                                &pid)) < 0)
1732                 goto fail;
1733
1734         service_set_control_pid(s, pid);
1735         return;
1736
1737 fail:
1738         log_warning("%s failed to run spawn next task: %s", UNIT(s)->meta.id, strerror(-r));
1739
1740         if (s->state == SERVICE_START_PRE)
1741                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1742         else if (s->state == SERVICE_STOP)
1743                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1744         else if (s->state == SERVICE_STOP_POST)
1745                 service_enter_dead(s, false, true);
1746         else
1747                 service_enter_stop(s, false);
1748 }
1749
1750 static int service_start(Unit *u) {
1751         Service *s = SERVICE(u);
1752
1753         assert(s);
1754
1755         /* We cannot fulfill this request right now, try again later
1756          * please! */
1757         if (s->state == SERVICE_STOP ||
1758             s->state == SERVICE_STOP_SIGTERM ||
1759             s->state == SERVICE_STOP_SIGKILL ||
1760             s->state == SERVICE_STOP_POST ||
1761             s->state == SERVICE_FINAL_SIGTERM ||
1762             s->state == SERVICE_FINAL_SIGKILL)
1763                 return -EAGAIN;
1764
1765         /* Already on it! */
1766         if (s->state == SERVICE_START_PRE ||
1767             s->state == SERVICE_START ||
1768             s->state == SERVICE_START_POST)
1769                 return 0;
1770
1771         assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTENANCE || s->state == SERVICE_AUTO_RESTART);
1772
1773         /* Make sure we don't enter a busy loop of some kind. */
1774         if (!ratelimit_test(&s->ratelimit)) {
1775                 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1776                 return -ECANCELED;
1777         }
1778
1779         s->failure = false;
1780         s->main_pid_known = false;
1781         s->allow_restart = true;
1782
1783         service_enter_start_pre(s);
1784         return 0;
1785 }
1786
1787 static int service_stop(Unit *u) {
1788         Service *s = SERVICE(u);
1789
1790         assert(s);
1791
1792         /* Cannot do this now */
1793         if (s->state == SERVICE_START_PRE ||
1794             s->state == SERVICE_START ||
1795             s->state == SERVICE_START_POST ||
1796             s->state == SERVICE_RELOAD)
1797                 return -EAGAIN;
1798
1799         /* Already on it */
1800         if (s->state == SERVICE_STOP ||
1801             s->state == SERVICE_STOP_SIGTERM ||
1802             s->state == SERVICE_STOP_SIGKILL ||
1803             s->state == SERVICE_STOP_POST ||
1804             s->state == SERVICE_FINAL_SIGTERM ||
1805             s->state == SERVICE_FINAL_SIGKILL)
1806                 return 0;
1807
1808         if (s->state == SERVICE_AUTO_RESTART) {
1809                 service_set_state(s, SERVICE_DEAD);
1810                 return 0;
1811         }
1812
1813         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1814
1815         /* This is a user request, so don't do restarts on this
1816          * shutdown. */
1817         s->allow_restart = false;
1818
1819         service_enter_stop(s, true);
1820         return 0;
1821 }
1822
1823 static int service_reload(Unit *u) {
1824         Service *s = SERVICE(u);
1825
1826         assert(s);
1827
1828         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1829
1830         service_enter_reload(s);
1831         return 0;
1832 }
1833
1834 static bool service_can_reload(Unit *u) {
1835         Service *s = SERVICE(u);
1836
1837         assert(s);
1838
1839         return !!s->exec_command[SERVICE_EXEC_RELOAD];
1840 }
1841
1842 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1843         Service *s = SERVICE(u);
1844
1845         assert(u);
1846         assert(f);
1847         assert(fds);
1848
1849         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1850         unit_serialize_item(u, f, "failure", yes_no(s->failure));
1851
1852         if (s->control_pid > 0)
1853                 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1854
1855         if (s->main_pid_known && s->main_pid > 0)
1856                 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
1857
1858         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1859
1860         /* There's a minor uncleanliness here: if there are multiple
1861          * commands attached here, we will start from the first one
1862          * again */
1863         if (s->control_command_id >= 0)
1864                 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
1865
1866         if (s->socket_fd >= 0) {
1867                 int copy;
1868
1869                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1870                         return copy;
1871
1872                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1873         }
1874
1875         return 0;
1876 }
1877
1878 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1879         Service *s = SERVICE(u);
1880         int r;
1881
1882         assert(u);
1883         assert(key);
1884         assert(value);
1885         assert(fds);
1886
1887         if (streq(key, "state")) {
1888                 ServiceState state;
1889
1890                 if ((state = service_state_from_string(value)) < 0)
1891                         log_debug("Failed to parse state value %s", value);
1892                 else
1893                         s->deserialized_state = state;
1894         } else if (streq(key, "failure")) {
1895                 int b;
1896
1897                 if ((b = parse_boolean(value)) < 0)
1898                         log_debug("Failed to parse failure value %s", value);
1899                 else
1900                         s->failure = b || s->failure;
1901         } else if (streq(key, "control-pid")) {
1902                 pid_t pid;
1903
1904                 if ((r = parse_pid(value, &pid)) < 0)
1905                         log_debug("Failed to parse control-pid value %s", value);
1906                 else
1907                         service_set_control_pid(s, pid);
1908         } else if (streq(key, "main-pid")) {
1909                 pid_t pid;
1910
1911                 if ((r = parse_pid(value, &pid)) < 0)
1912                         log_debug("Failed to parse main-pid value %s", value);
1913                 else
1914                         service_set_main_pid(s, (pid_t) pid);
1915         } else if (streq(key, "main-pid-known")) {
1916                 int b;
1917
1918                 if ((b = parse_boolean(value)) < 0)
1919                         log_debug("Failed to parse main-pid-known value %s", value);
1920                 else
1921                         s->main_pid_known = b;
1922         } else if (streq(key, "control-command")) {
1923                 ServiceExecCommand id;
1924
1925                 if ((id = service_exec_command_from_string(value)) < 0)
1926                         log_debug("Failed to parse exec-command value %s", value);
1927                 else {
1928                         s->control_command_id = id;
1929                         s->control_command = s->exec_command[id];
1930                 }
1931         } else if (streq(key, "socket-fd")) {
1932                 int fd;
1933
1934                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1935                         log_debug("Failed to parse socket-fd value %s", value);
1936                 else {
1937
1938                         if (s->socket_fd >= 0)
1939                                 close_nointr_nofail(s->socket_fd);
1940                         s->socket_fd = fdset_remove(fds, fd);
1941                 }
1942         } else
1943                 log_debug("Unknown serialization key '%s'", key);
1944
1945         return 0;
1946 }
1947
1948 static UnitActiveState service_active_state(Unit *u) {
1949         assert(u);
1950
1951         return state_translation_table[SERVICE(u)->state];
1952 }
1953
1954 static const char *service_sub_state_to_string(Unit *u) {
1955         assert(u);
1956
1957         return service_state_to_string(SERVICE(u)->state);
1958 }
1959
1960 static bool service_check_gc(Unit *u) {
1961         Service *s = SERVICE(u);
1962
1963         assert(s);
1964
1965         return !!s->sysv_path;
1966 }
1967
1968 static bool service_check_snapshot(Unit *u) {
1969         Service *s = SERVICE(u);
1970
1971         assert(s);
1972
1973         return !s->got_socket_fd;
1974 }
1975
1976 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1977         Service *s = SERVICE(u);
1978         bool success;
1979
1980         assert(s);
1981         assert(pid >= 0);
1982
1983         success = is_clean_exit(code, status);
1984         s->failure = s->failure || !success;
1985
1986         if (s->main_pid == pid) {
1987
1988                 exec_status_fill(&s->main_exec_status, pid, code, status);
1989                 s->main_pid = 0;
1990
1991                 if (s->type != SERVICE_FORKING) {
1992                         assert(s->exec_command[SERVICE_EXEC_START]);
1993                         s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
1994                 }
1995
1996                 log_debug("%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
1997
1998                 /* The service exited, so the service is officially
1999                  * gone. */
2000
2001                 switch (s->state) {
2002
2003                 case SERVICE_START_POST:
2004                 case SERVICE_RELOAD:
2005                 case SERVICE_STOP:
2006                         /* Need to wait until the operation is
2007                          * done */
2008                         break;
2009
2010                 case SERVICE_START:
2011                         if (s->type == SERVICE_FINISH) {
2012                                 /* This was our main goal, so let's go on */
2013                                 if (success)
2014                                         service_enter_start_post(s);
2015                                 else
2016                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2017                                 break;
2018                         } else {
2019                                 assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2020
2021                                 /* Fall through */
2022                         }
2023
2024                 case SERVICE_RUNNING:
2025                         service_enter_running(s, success);
2026                         break;
2027
2028                 case SERVICE_STOP_SIGTERM:
2029                 case SERVICE_STOP_SIGKILL:
2030
2031                         if (!control_pid_good(s))
2032                                 service_enter_stop_post(s, success);
2033
2034                         /* If there is still a control process, wait for that first */
2035                         break;
2036
2037                 default:
2038                         assert_not_reached("Uh, main process died at wrong time.");
2039                 }
2040
2041         } else if (s->control_pid == pid) {
2042
2043                 if (s->control_command)
2044                         exec_status_fill(&s->control_command->exec_status, pid, code, status);
2045
2046                 s->control_pid = 0;
2047
2048                 log_debug("%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2049
2050                 /* If we are shutting things down anyway we
2051                  * don't care about failing commands. */
2052
2053                 if (s->control_command && s->control_command->command_next && success) {
2054
2055                         /* There is another command to *
2056                          * execute, so let's do that. */
2057
2058                         log_debug("%s running next command for state %s", u->meta.id, service_state_to_string(s->state));
2059                         service_run_next(s, success);
2060
2061                 } else {
2062                         /* No further commands for this step, so let's
2063                          * figure out what to do next */
2064
2065                         s->control_command = NULL;
2066                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2067
2068                         log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2069
2070                         switch (s->state) {
2071
2072                         case SERVICE_START_PRE:
2073                                 if (success)
2074                                         service_enter_start(s);
2075                                 else
2076                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2077                                 break;
2078
2079                         case SERVICE_START:
2080                                 assert(s->type == SERVICE_FORKING);
2081
2082                                 /* Let's try to load the pid
2083                                  * file here if we can. We
2084                                  * ignore the return value,
2085                                  * since the PID file might
2086                                  * actually be created by a
2087                                  * START_POST script */
2088
2089                                 if (success) {
2090                                         if (s->pid_file)
2091                                                 service_load_pid_file(s);
2092
2093                                         service_enter_start_post(s);
2094                                 } else
2095                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2096
2097                                 break;
2098
2099                         case SERVICE_START_POST:
2100                                 if (success && s->pid_file && !s->main_pid_known) {
2101                                         int r;
2102
2103                                         /* Hmm, let's see if we can
2104                                          * load the pid now after the
2105                                          * start-post scripts got
2106                                          * executed. */
2107
2108                                         if ((r = service_load_pid_file(s)) < 0)
2109                                                 log_warning("%s: failed to load PID file %s: %s", UNIT(s)->meta.id, s->pid_file, strerror(-r));
2110                                 }
2111
2112                                 /* Fall through */
2113
2114                         case SERVICE_RELOAD:
2115                                 if (success)
2116                                         service_enter_running(s, true);
2117                                 else
2118                                         service_enter_stop(s, false);
2119
2120                                 break;
2121
2122                         case SERVICE_STOP:
2123                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2124                                 break;
2125
2126                         case SERVICE_STOP_SIGTERM:
2127                         case SERVICE_STOP_SIGKILL:
2128                                 if (main_pid_good(s) <= 0)
2129                                         service_enter_stop_post(s, success);
2130
2131                                 /* If there is still a service
2132                                  * process around, wait until
2133                                  * that one quit, too */
2134                                 break;
2135
2136                         case SERVICE_STOP_POST:
2137                         case SERVICE_FINAL_SIGTERM:
2138                         case SERVICE_FINAL_SIGKILL:
2139                                 service_enter_dead(s, success, true);
2140                                 break;
2141
2142                         default:
2143                                 assert_not_reached("Uh, control process died at wrong time.");
2144                         }
2145                 }
2146         }
2147 }
2148
2149 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2150         Service *s = SERVICE(u);
2151
2152         assert(s);
2153         assert(elapsed == 1);
2154
2155         assert(w == &s->timer_watch);
2156
2157         switch (s->state) {
2158
2159         case SERVICE_START_PRE:
2160         case SERVICE_START:
2161                 log_warning("%s operation timed out. Terminating.", u->meta.id);
2162                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2163                 break;
2164
2165         case SERVICE_START_POST:
2166         case SERVICE_RELOAD:
2167                 log_warning("%s operation timed out. Stopping.", u->meta.id);
2168                 service_enter_stop(s, false);
2169                 break;
2170
2171         case SERVICE_STOP:
2172                 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2173                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2174                 break;
2175
2176         case SERVICE_STOP_SIGTERM:
2177                 log_warning("%s stopping timed out. Killing.", u->meta.id);
2178                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2179                 break;
2180
2181         case SERVICE_STOP_SIGKILL:
2182                 /* Uh, wie sent a SIGKILL and it is still not gone?
2183                  * Must be something we cannot kill, so let's just be
2184                  * weirded out and continue */
2185
2186                 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2187                 service_enter_stop_post(s, false);
2188                 break;
2189
2190         case SERVICE_STOP_POST:
2191                 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2192                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2193                 break;
2194
2195         case SERVICE_FINAL_SIGTERM:
2196                 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2197                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2198                 break;
2199
2200         case SERVICE_FINAL_SIGKILL:
2201                 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
2202                 service_enter_dead(s, false, true);
2203                 break;
2204
2205         case SERVICE_AUTO_RESTART:
2206                 log_debug("%s holdoff time over, scheduling restart.", u->meta.id);
2207                 service_enter_restart(s);
2208                 break;
2209
2210         default:
2211                 assert_not_reached("Timeout at wrong time.");
2212         }
2213 }
2214
2215 static void service_cgroup_notify_event(Unit *u) {
2216         Service *s = SERVICE(u);
2217
2218         assert(u);
2219
2220         log_debug("%s: cgroup is empty", u->meta.id);
2221
2222         switch (s->state) {
2223
2224                 /* Waiting for SIGCHLD is usually more interesting,
2225                  * because it includes return codes/signals. Which is
2226                  * why we ignore the cgroup events for most cases,
2227                  * except when we don't know pid which to expect the
2228                  * SIGCHLD for. */
2229
2230         case SERVICE_RUNNING:
2231                 service_enter_running(s, true);
2232                 break;
2233
2234         default:
2235                 ;
2236         }
2237 }
2238
2239 static void service_notify_message(Unit *u, char **tags) {
2240         Service *s = SERVICE(u);
2241         const char *e;
2242
2243         assert(u);
2244
2245         log_debug("%s: Got message", u->meta.id);
2246
2247         /* Interpret MAINPID= */
2248         if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2249             (s->state == SERVICE_START ||
2250              s->state == SERVICE_START_POST ||
2251              s->state == SERVICE_RUNNING ||
2252              s->state == SERVICE_RELOAD)) {
2253                 pid_t pid;
2254
2255                 if (parse_pid(e + 8, &pid) < 0)
2256                         log_warning("Failed to parse %s", e);
2257                 else {
2258                         log_debug("%s: got %s", u->meta.id, e);
2259                         service_set_main_pid(s, pid);
2260                 }
2261         }
2262
2263         /* Interpret READY= */
2264         if (s->type == SERVICE_NOTIFY &&
2265             s->state == SERVICE_START &&
2266             strv_find(tags, "READY=1")) {
2267                 log_debug("%s: got READY=1", u->meta.id);
2268
2269                 service_enter_start_post(s);
2270         }
2271
2272         /* Interpret STATUS= */
2273         if ((e = strv_find_prefix(tags, "STATUS="))) {
2274                 char *t;
2275
2276                 if (!(t = strdup(e+7))) {
2277                         log_error("Failed to allocate string.");
2278                         return;
2279                 }
2280
2281                 log_debug("%s: got %s", u->meta.id, e);
2282
2283                 free(s->status_text);
2284                 s->status_text = t;
2285         }
2286 }
2287
2288 static int service_enumerate(Manager *m) {
2289         char **p;
2290         unsigned i;
2291         DIR *d = NULL;
2292         char *path = NULL, *fpath = NULL, *name = NULL;
2293         int r;
2294
2295         assert(m);
2296
2297         STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2298                 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2299                         struct dirent *de;
2300
2301                         free(path);
2302                         path = NULL;
2303                         if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2304                                 r = -ENOMEM;
2305                                 goto finish;
2306                         }
2307
2308                         if (d)
2309                                 closedir(d);
2310
2311                         if (!(d = opendir(path))) {
2312                                 if (errno != ENOENT)
2313                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
2314
2315                                 continue;
2316                         }
2317
2318                         while ((de = readdir(d))) {
2319                                 Unit *service;
2320                                 int a, b;
2321
2322                                 if (ignore_file(de->d_name))
2323                                         continue;
2324
2325                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2326                                         continue;
2327
2328                                 if (strlen(de->d_name) < 4)
2329                                         continue;
2330
2331                                 a = undecchar(de->d_name[1]);
2332                                 b = undecchar(de->d_name[2]);
2333
2334                                 if (a < 0 || b < 0)
2335                                         continue;
2336
2337                                 free(fpath);
2338                                 fpath = NULL;
2339                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2340                                         r = -ENOMEM;
2341                                         goto finish;
2342                                 }
2343
2344                                 if (access(fpath, X_OK) < 0) {
2345
2346                                         if (errno != ENOENT)
2347                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2348
2349                                         continue;
2350                                 }
2351
2352                                 free(name);
2353                                 if (!(name = sysv_translate_name(de->d_name + 3))) {
2354                                         r = -ENOMEM;
2355                                         goto finish;
2356                                 }
2357
2358                                 if ((r = manager_load_unit_prepare(m, name, NULL, &service)) < 0) {
2359                                         log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2360                                         continue;
2361                                 }
2362
2363                                 if (de->d_name[0] == 'S' &&
2364                                     (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT))
2365                                         SERVICE(service)->sysv_start_priority =
2366                                                 MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2367
2368                                 manager_dispatch_load_queue(m);
2369                                 service = unit_follow_merge(service);
2370
2371                                 if (de->d_name[0] == 'S') {
2372                                         Unit *runlevel_target;
2373
2374                                         if ((r = manager_load_unit(m, rcnd_table[i].target, NULL, &runlevel_target)) < 0)
2375                                                 goto finish;
2376
2377                                         if ((r = unit_add_dependency(runlevel_target, UNIT_WANTS, service, true)) < 0)
2378                                                 goto finish;
2379
2380                                         if ((r = unit_add_dependency(service, UNIT_BEFORE, runlevel_target, true)) < 0)
2381                                                 goto finish;
2382
2383                                 } else if (de->d_name[0] == 'K' &&
2384                                            (rcnd_table[i].type == RUNLEVEL_DOWN ||
2385                                             rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2386                                         Unit *shutdown_target;
2387
2388                                         /* We honour K links only for
2389                                          * halt/reboot. For the normal
2390                                          * runlevels we assume the
2391                                          * stop jobs will be
2392                                          * implicitly added by the
2393                                          * core logic. Also, we don't
2394                                          * really distuingish here
2395                                          * between the runlevels 0 and
2396                                          * 6 and just add them to the
2397                                          * special shutdown target. On
2398                                          * SUSE the boot.d/ runlevel
2399                                          * is also used for shutdown,
2400                                          * so we add links for that
2401                                          * too to the shutdown
2402                                          * target.*/
2403
2404                                         if ((r = manager_load_unit(m, SPECIAL_SHUTDOWN_TARGET, NULL, &shutdown_target)) < 0)
2405                                                 goto finish;
2406
2407                                         if ((r = unit_add_dependency(service, UNIT_CONFLICTS, shutdown_target, true)) < 0)
2408                                                 goto finish;
2409
2410                                         if ((r = unit_add_dependency(service, UNIT_BEFORE, shutdown_target, true)) < 0)
2411                                                 goto finish;
2412                                 }
2413                         }
2414                 }
2415
2416         r = 0;
2417
2418 finish:
2419         free(path);
2420         free(fpath);
2421         free(name);
2422
2423         if (d)
2424                 closedir(d);
2425
2426         return r;
2427 }
2428
2429 static void service_bus_name_owner_change(
2430                 Unit *u,
2431                 const char *name,
2432                 const char *old_owner,
2433                 const char *new_owner) {
2434
2435         Service *s = SERVICE(u);
2436
2437         assert(s);
2438         assert(name);
2439
2440         assert(streq(s->bus_name, name));
2441         assert(old_owner || new_owner);
2442
2443         if (old_owner && new_owner)
2444                 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2445         else if (old_owner)
2446                 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2447         else
2448                 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2449
2450         s->bus_name_good = !!new_owner;
2451
2452         if (s->type == SERVICE_DBUS) {
2453
2454                 /* service_enter_running() will figure out what to
2455                  * do */
2456                 if (s->state == SERVICE_RUNNING)
2457                         service_enter_running(s, true);
2458                 else if (s->state == SERVICE_START && new_owner)
2459                         service_enter_start_post(s);
2460
2461         } else if (new_owner &&
2462                    s->main_pid <= 0 &&
2463                    (s->state == SERVICE_START ||
2464                     s->state == SERVICE_START_POST ||
2465                     s->state == SERVICE_RUNNING ||
2466                     s->state == SERVICE_RELOAD)) {
2467
2468                 /* Try to acquire PID from bus service */
2469                 log_debug("Trying to acquire PID from D-Bus name...");
2470
2471                 bus_query_pid(u->meta.manager, name);
2472         }
2473 }
2474
2475 static void service_bus_query_pid_done(
2476                 Unit *u,
2477                 const char *name,
2478                 pid_t pid) {
2479
2480         Service *s = SERVICE(u);
2481
2482         assert(s);
2483         assert(name);
2484
2485         log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2486
2487         if (s->main_pid <= 0 &&
2488             (s->state == SERVICE_START ||
2489              s->state == SERVICE_START_POST ||
2490              s->state == SERVICE_RUNNING ||
2491              s->state == SERVICE_RELOAD))
2492                 service_set_main_pid(s, pid);
2493 }
2494
2495 int service_set_socket_fd(Service *s, int fd) {
2496         assert(s);
2497         assert(fd >= 0);
2498
2499         /* This is called by the socket code when instantiating a new
2500          * service for a stream socket and the socket needs to be
2501          * configured. */
2502
2503         if (UNIT(s)->meta.load_state != UNIT_LOADED)
2504                 return -EINVAL;
2505
2506         if (s->socket_fd >= 0)
2507                 return -EBUSY;
2508
2509         if (s->state != SERVICE_DEAD)
2510                 return -EAGAIN;
2511
2512         s->socket_fd = fd;
2513         s->got_socket_fd = true;
2514         return 0;
2515 }
2516
2517 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2518         [SERVICE_DEAD] = "dead",
2519         [SERVICE_START_PRE] = "start-pre",
2520         [SERVICE_START] = "start",
2521         [SERVICE_START_POST] = "start-post",
2522         [SERVICE_RUNNING] = "running",
2523         [SERVICE_EXITED] = "exited",
2524         [SERVICE_RELOAD] = "reload",
2525         [SERVICE_STOP] = "stop",
2526         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2527         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2528         [SERVICE_STOP_POST] = "stop-post",
2529         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2530         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2531         [SERVICE_MAINTENANCE] = "maintenance",
2532         [SERVICE_AUTO_RESTART] = "auto-restart",
2533 };
2534
2535 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2536
2537 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2538         [SERVICE_ONCE] = "once",
2539         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2540         [SERVICE_RESTART_ALWAYS] = "restart-always",
2541 };
2542
2543 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2544
2545 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2546         [SERVICE_FORKING] = "forking",
2547         [SERVICE_SIMPLE] = "simple",
2548         [SERVICE_FINISH] = "finish",
2549         [SERVICE_DBUS] = "dbus",
2550         [SERVICE_NOTIFY] = "notify"
2551 };
2552
2553 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2554
2555 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2556         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2557         [SERVICE_EXEC_START] = "ExecStart",
2558         [SERVICE_EXEC_START_POST] = "ExecStartPost",
2559         [SERVICE_EXEC_RELOAD] = "ExecReload",
2560         [SERVICE_EXEC_STOP] = "ExecStop",
2561         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2562 };
2563
2564 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2565
2566 const UnitVTable service_vtable = {
2567         .suffix = ".service",
2568
2569         .init = service_init,
2570         .done = service_done,
2571         .load = service_load,
2572
2573         .coldplug = service_coldplug,
2574
2575         .dump = service_dump,
2576
2577         .start = service_start,
2578         .stop = service_stop,
2579         .reload = service_reload,
2580
2581         .can_reload = service_can_reload,
2582
2583         .serialize = service_serialize,
2584         .deserialize_item = service_deserialize_item,
2585
2586         .active_state = service_active_state,
2587         .sub_state_to_string = service_sub_state_to_string,
2588
2589         .check_gc = service_check_gc,
2590         .check_snapshot = service_check_snapshot,
2591
2592         .sigchld_event = service_sigchld_event,
2593         .timer_event = service_timer_event,
2594
2595         .cgroup_notify_empty = service_cgroup_notify_event,
2596         .notify_message = service_notify_message,
2597
2598         .bus_name_owner_change = service_bus_name_owner_change,
2599         .bus_query_pid_done = service_bus_query_pid_done,
2600
2601         .bus_message_handler = bus_service_message_handler,
2602
2603         .enumerate = service_enumerate
2604 };