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