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