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