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