chiark / gitweb /
util: add Debian welcome message
[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_verify(Service *s) {
828         assert(s);
829
830         if (s->meta.load_state != UNIT_LOADED)
831                 return 0;
832
833         if (!s->exec_command[SERVICE_EXEC_START]) {
834                 log_error("%s lacks ExecStart setting. Refusing.", s->meta.id);
835                 return -EINVAL;
836         }
837
838         if (s->type != SERVICE_ONESHOT &&
839             s->exec_command[SERVICE_EXEC_START]->command_next) {
840                 log_error("%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", s->meta.id);
841                 return -EINVAL;
842         }
843
844         if (s->type == SERVICE_DBUS && !s->bus_name) {
845                 log_error("%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", s->meta.id);
846                 return -EINVAL;
847         }
848
849         if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
850                 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
851                 return -EINVAL;
852         }
853
854         return 0;
855 }
856
857 static int service_add_default_dependencies(Service *s) {
858         int r;
859
860         assert(s);
861
862         /* Add a number of automatic dependencies useful for the
863          * majority of services. */
864
865         /* First, pull in base system */
866         if (s->meta.manager->running_as == MANAGER_SYSTEM) {
867
868                 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
869                         return r;
870
871         } else if (s->meta.manager->running_as == MANAGER_SESSION) {
872
873                 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
874                         return r;
875         }
876
877         /* Second, activate normal shutdown */
878         return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTED_BY, SPECIAL_SHUTDOWN_TARGET, NULL, true);
879 }
880
881 static int service_load(Unit *u) {
882         int r;
883         Service *s = SERVICE(u);
884
885         assert(s);
886
887         /* Load a .service file */
888         if ((r = unit_load_fragment(u)) < 0)
889                 return r;
890
891         /* Load a classic init script as a fallback, if we couldn't find anything */
892         if (u->meta.load_state == UNIT_STUB)
893                 if ((r = service_load_sysv(s)) < 0)
894                         return r;
895
896         /* Still nothing found? Then let's give up */
897         if (u->meta.load_state == UNIT_STUB)
898                 return -ENOENT;
899
900         /* We were able to load something, then let's add in the
901          * dropin directories. */
902         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
903                 return r;
904
905         /* This is a new unit? Then let's add in some extras */
906         if (u->meta.load_state == UNIT_LOADED) {
907                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
908                         return r;
909
910                 if ((r = unit_add_default_cgroup(u)) < 0)
911                         return r;
912
913                 if ((r = sysv_fix_order(s)) < 0)
914                         return r;
915
916                 if (s->bus_name)
917                         if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
918                                 return r;
919
920                 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
921                         s->notify_access = NOTIFY_MAIN;
922
923                 if (s->type == SERVICE_DBUS || s->bus_name)
924                         if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_TARGET, NULL, true)) < 0)
925                                 return r;
926
927                 if (s->meta.default_dependencies)
928                         if ((r = service_add_default_dependencies(s)) < 0)
929                                 return r;
930         }
931
932         return service_verify(s);
933 }
934
935 static void service_dump(Unit *u, FILE *f, const char *prefix) {
936
937         ServiceExecCommand c;
938         Service *s = SERVICE(u);
939         const char *prefix2;
940         char *p2;
941
942         assert(s);
943
944         p2 = strappend(prefix, "\t");
945         prefix2 = p2 ? p2 : prefix;
946
947         fprintf(f,
948                 "%sService State: %s\n"
949                 "%sPermissionsStartOnly: %s\n"
950                 "%sRootDirectoryStartOnly: %s\n"
951                 "%sRemainAfterExit: %s\n"
952                 "%sType: %s\n"
953                 "%sRestart: %s\n"
954                 "%sNotifyAccess: %s\n",
955                 prefix, service_state_to_string(s->state),
956                 prefix, yes_no(s->permissions_start_only),
957                 prefix, yes_no(s->root_directory_start_only),
958                 prefix, yes_no(s->remain_after_exit),
959                 prefix, service_type_to_string(s->type),
960                 prefix, service_restart_to_string(s->restart),
961                 prefix, notify_access_to_string(s->notify_access));
962
963         if (s->control_pid > 0)
964                 fprintf(f,
965                         "%sControl PID: %lu\n",
966                         prefix, (unsigned long) s->control_pid);
967
968         if (s->main_pid > 0)
969                 fprintf(f,
970                         "%sMain PID: %lu\n",
971                         prefix, (unsigned long) s->main_pid);
972
973         if (s->pid_file)
974                 fprintf(f,
975                         "%sPIDFile: %s\n",
976                         prefix, s->pid_file);
977
978         if (s->bus_name)
979                 fprintf(f,
980                         "%sBusName: %s\n"
981                         "%sBus Name Good: %s\n",
982                         prefix, s->bus_name,
983                         prefix, yes_no(s->bus_name_good));
984
985         exec_context_dump(&s->exec_context, f, prefix);
986
987         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
988
989                 if (!s->exec_command[c])
990                         continue;
991
992                 fprintf(f, "%s-> %s:\n",
993                         prefix, service_exec_command_to_string(c));
994
995                 exec_command_dump_list(s->exec_command[c], f, prefix2);
996         }
997
998         if (s->sysv_path)
999                 fprintf(f,
1000                         "%sSysV Init Script Path: %s\n"
1001                         "%sSysV Init Script has LSB Header: %s\n",
1002                         prefix, s->sysv_path,
1003                         prefix, yes_no(s->sysv_has_lsb));
1004
1005         if (s->sysv_start_priority >= 0)
1006                 fprintf(f,
1007                         "%sSysVStartPriority: %i\n"
1008                         "%sSysVEnabled: %s\n",
1009                         prefix, s->sysv_start_priority,
1010                         prefix, yes_no(s->sysv_enabled));
1011
1012         if (s->sysv_runlevels)
1013                 fprintf(f, "%sSysVRunLevels: %s\n",
1014                         prefix, s->sysv_runlevels);
1015
1016         if (s->status_text)
1017                 fprintf(f, "%sStatus Text: %s\n",
1018                         prefix, s->status_text);
1019
1020         free(p2);
1021 }
1022
1023 static int service_load_pid_file(Service *s) {
1024         char *k;
1025         int r;
1026         pid_t pid;
1027
1028         assert(s);
1029
1030         if (s->main_pid_known)
1031                 return 0;
1032
1033         assert(s->main_pid <= 0);
1034
1035         if (!s->pid_file)
1036                 return -ENOENT;
1037
1038         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
1039                 return r;
1040
1041         r = parse_pid(k, &pid);
1042         free(k);
1043
1044         if (r < 0)
1045                 return r;
1046
1047         if (kill(pid, 0) < 0 && errno != EPERM) {
1048                 log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
1049                             (unsigned long) pid, s->pid_file);
1050                 return -ESRCH;
1051         }
1052
1053         if ((r = service_set_main_pid(s, pid)) < 0)
1054                 return r;
1055
1056         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1057                 /* FIXME: we need to do something here */
1058                 return r;
1059
1060         return 0;
1061 }
1062
1063 static int service_get_sockets(Service *s, Set **_set) {
1064         Set *set;
1065         Iterator i;
1066         char *t;
1067         int r;
1068
1069         assert(s);
1070         assert(_set);
1071
1072         if (s->socket_fd >= 0)
1073                 return 0;
1074
1075         /* Collects all Socket objects that belong to this
1076          * service. Note that a service might have multiple sockets
1077          * via multiple names. */
1078
1079         if (!(set = set_new(NULL, NULL)))
1080                 return -ENOMEM;
1081
1082         SET_FOREACH(t, s->meta.names, i) {
1083                 char *k;
1084                 Unit *p;
1085
1086                 /* Look for all socket objects that go by any of our
1087                  * units and collect their fds */
1088
1089                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
1090                         r = -ENOMEM;
1091                         goto fail;
1092                 }
1093
1094                 p = manager_get_unit(s->meta.manager, k);
1095                 free(k);
1096
1097                 if (!p)
1098                         continue;
1099
1100                 if ((r = set_put(set, p)) < 0)
1101                         goto fail;
1102         }
1103
1104         *_set = set;
1105         return 0;
1106
1107 fail:
1108         set_free(set);
1109         return r;
1110 }
1111
1112 static int service_notify_sockets_dead(Service *s) {
1113         Iterator i;
1114         Set *set;
1115         Socket *sock;
1116         int r;
1117
1118         assert(s);
1119
1120         if (s->socket_fd >= 0)
1121                 return 0;
1122
1123         /* Notifies all our sockets when we die */
1124         if ((r = service_get_sockets(s, &set)) < 0)
1125                 return r;
1126
1127         SET_FOREACH(sock, set, i)
1128                 socket_notify_service_dead(sock);
1129
1130         set_free(set);
1131
1132         return 0;
1133 }
1134
1135 static void service_set_state(Service *s, ServiceState state) {
1136         ServiceState old_state;
1137         assert(s);
1138
1139         old_state = s->state;
1140         s->state = state;
1141
1142         if (state != SERVICE_START_PRE &&
1143             state != SERVICE_START &&
1144             state != SERVICE_START_POST &&
1145             state != SERVICE_RELOAD &&
1146             state != SERVICE_STOP &&
1147             state != SERVICE_STOP_SIGTERM &&
1148             state != SERVICE_STOP_SIGKILL &&
1149             state != SERVICE_STOP_POST &&
1150             state != SERVICE_FINAL_SIGTERM &&
1151             state != SERVICE_FINAL_SIGKILL &&
1152             state != SERVICE_AUTO_RESTART)
1153                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1154
1155         if (state != SERVICE_START &&
1156             state != SERVICE_START_POST &&
1157             state != SERVICE_RUNNING &&
1158             state != SERVICE_RELOAD &&
1159             state != SERVICE_STOP &&
1160             state != SERVICE_STOP_SIGTERM &&
1161             state != SERVICE_STOP_SIGKILL)
1162                 service_unwatch_main_pid(s);
1163
1164         if (state != SERVICE_START_PRE &&
1165             state != SERVICE_START &&
1166             state != SERVICE_START_POST &&
1167             state != SERVICE_RELOAD &&
1168             state != SERVICE_STOP &&
1169             state != SERVICE_STOP_SIGTERM &&
1170             state != SERVICE_STOP_SIGKILL &&
1171             state != SERVICE_STOP_POST &&
1172             state != SERVICE_FINAL_SIGTERM &&
1173             state != SERVICE_FINAL_SIGKILL) {
1174                 service_unwatch_control_pid(s);
1175                 s->control_command = NULL;
1176                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1177         }
1178
1179         if (state == SERVICE_DEAD ||
1180             state == SERVICE_STOP ||
1181             state == SERVICE_STOP_SIGTERM ||
1182             state == SERVICE_STOP_SIGKILL ||
1183             state == SERVICE_STOP_POST ||
1184             state == SERVICE_FINAL_SIGTERM ||
1185             state == SERVICE_FINAL_SIGKILL ||
1186             state == SERVICE_FAILED ||
1187             state == SERVICE_AUTO_RESTART)
1188                 service_notify_sockets_dead(s);
1189
1190         if (state != SERVICE_START_PRE &&
1191             state != SERVICE_START &&
1192             state != SERVICE_START_POST &&
1193             state != SERVICE_RUNNING &&
1194             state != SERVICE_RELOAD &&
1195             state != SERVICE_STOP &&
1196             state != SERVICE_STOP_SIGTERM &&
1197             state != SERVICE_STOP_SIGKILL &&
1198             state != SERVICE_STOP_POST &&
1199             state != SERVICE_FINAL_SIGTERM &&
1200             state != SERVICE_FINAL_SIGKILL &&
1201             !(state == SERVICE_DEAD && s->meta.job)) {
1202                 service_close_socket_fd(s);
1203                 service_connection_unref(s);
1204         }
1205
1206         /* For the inactive states unit_notify() will trim the cgroup,
1207          * but for exit we have to do that ourselves... */
1208         if (state == SERVICE_EXITED)
1209                 cgroup_bonding_trim_list(s->meta.cgroup_bondings, true);
1210
1211         if (old_state != state)
1212                 log_debug("%s changed %s -> %s", s->meta.id, service_state_to_string(old_state), service_state_to_string(state));
1213
1214         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
1215 }
1216
1217 static int service_coldplug(Unit *u) {
1218         Service *s = SERVICE(u);
1219         int r;
1220
1221         assert(s);
1222         assert(s->state == SERVICE_DEAD);
1223
1224         if (s->deserialized_state != s->state) {
1225
1226                 if (s->deserialized_state == SERVICE_START_PRE ||
1227                     s->deserialized_state == SERVICE_START ||
1228                     s->deserialized_state == SERVICE_START_POST ||
1229                     s->deserialized_state == SERVICE_RELOAD ||
1230                     s->deserialized_state == SERVICE_STOP ||
1231                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1232                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1233                     s->deserialized_state == SERVICE_STOP_POST ||
1234                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1235                     s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1236                     s->deserialized_state == SERVICE_AUTO_RESTART) {
1237
1238                         if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_usec > 0) {
1239                                 usec_t k;
1240
1241                                 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_usec;
1242
1243                                 if ((r = unit_watch_timer(UNIT(s), k, &s->timer_watch)) < 0)
1244                                         return r;
1245                         }
1246                 }
1247
1248                 if ((s->deserialized_state == SERVICE_START &&
1249                      (s->type == SERVICE_FORKING ||
1250                       s->type == SERVICE_DBUS ||
1251                       s->type == SERVICE_ONESHOT ||
1252                       s->type == SERVICE_NOTIFY)) ||
1253                     s->deserialized_state == SERVICE_START_POST ||
1254                     s->deserialized_state == SERVICE_RUNNING ||
1255                     s->deserialized_state == SERVICE_RELOAD ||
1256                     s->deserialized_state == SERVICE_STOP ||
1257                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1258                     s->deserialized_state == SERVICE_STOP_SIGKILL)
1259                         if (s->main_pid > 0)
1260                                 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1261                                         return r;
1262
1263                 if (s->deserialized_state == SERVICE_START_PRE ||
1264                     s->deserialized_state == SERVICE_START ||
1265                     s->deserialized_state == SERVICE_START_POST ||
1266                     s->deserialized_state == SERVICE_RELOAD ||
1267                     s->deserialized_state == SERVICE_STOP ||
1268                     s->deserialized_state == SERVICE_STOP_SIGTERM ||
1269                     s->deserialized_state == SERVICE_STOP_SIGKILL ||
1270                     s->deserialized_state == SERVICE_STOP_POST ||
1271                     s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1272                     s->deserialized_state == SERVICE_FINAL_SIGKILL)
1273                         if (s->control_pid > 0)
1274                                 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1275                                         return r;
1276
1277                 service_set_state(s, s->deserialized_state);
1278         }
1279
1280         return 0;
1281 }
1282
1283 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1284         Iterator i;
1285         int r;
1286         int *rfds = NULL;
1287         unsigned rn_fds = 0;
1288         Set *set;
1289         Socket *sock;
1290
1291         assert(s);
1292         assert(fds);
1293         assert(n_fds);
1294
1295         if (s->socket_fd >= 0)
1296                 return 0;
1297
1298         if ((r = service_get_sockets(s, &set)) < 0)
1299                 return r;
1300
1301         SET_FOREACH(sock, set, i) {
1302                 int *cfds;
1303                 unsigned cn_fds;
1304
1305                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1306                         goto fail;
1307
1308                 if (!cfds)
1309                         continue;
1310
1311                 if (!rfds) {
1312                         rfds = cfds;
1313                         rn_fds = cn_fds;
1314                 } else {
1315                         int *t;
1316
1317                         if (!(t = new(int, rn_fds+cn_fds))) {
1318                                 free(cfds);
1319                                 r = -ENOMEM;
1320                                 goto fail;
1321                         }
1322
1323                         memcpy(t, rfds, rn_fds);
1324                         memcpy(t+rn_fds, cfds, cn_fds);
1325                         free(rfds);
1326                         free(cfds);
1327
1328                         rfds = t;
1329                         rn_fds = rn_fds+cn_fds;
1330                 }
1331         }
1332
1333         *fds = rfds;
1334         *n_fds = rn_fds;
1335
1336         set_free(set);
1337
1338         return 0;
1339
1340 fail:
1341         set_free(set);
1342         free(rfds);
1343
1344         return r;
1345 }
1346
1347 static int service_spawn(
1348                 Service *s,
1349                 ExecCommand *c,
1350                 bool timeout,
1351                 bool pass_fds,
1352                 bool apply_permissions,
1353                 bool apply_chroot,
1354                 bool apply_tty_stdin,
1355                 bool set_notify_socket,
1356                 pid_t *_pid) {
1357
1358         pid_t pid;
1359         int r;
1360         int *fds = NULL, *fdsbuf = NULL;
1361         unsigned n_fds = 0, n_env = 0;
1362         char **argv = NULL, **final_env = NULL, **our_env = NULL;
1363
1364         assert(s);
1365         assert(c);
1366         assert(_pid);
1367
1368         if (pass_fds ||
1369             s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1370             s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1371             s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1372
1373                 if (s->socket_fd >= 0) {
1374                         fds = &s->socket_fd;
1375                         n_fds = 1;
1376                 } else {
1377                         if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1378                                 goto fail;
1379
1380                         fds = fdsbuf;
1381                 }
1382         }
1383
1384         if (timeout && s->timeout_usec) {
1385                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1386                         goto fail;
1387         } else
1388                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1389
1390         if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1391                 r = -ENOMEM;
1392                 goto fail;
1393         }
1394
1395         if (!(our_env = new0(char*, 3))) {
1396                 r = -ENOMEM;
1397                 goto fail;
1398         }
1399
1400         if (set_notify_socket)
1401                 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=@%s", s->meta.manager->notify_socket) < 0) {
1402                         r = -ENOMEM;
1403                         goto fail;
1404                 }
1405
1406         if (s->main_pid > 0)
1407                 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1408                         r = -ENOMEM;
1409                         goto fail;
1410                 }
1411
1412         if (!(final_env = strv_env_merge(2,
1413                                          s->meta.manager->environment,
1414                                          our_env,
1415                                          NULL))) {
1416                 r = -ENOMEM;
1417                 goto fail;
1418         }
1419
1420         r = exec_spawn(c,
1421                        argv,
1422                        &s->exec_context,
1423                        fds, n_fds,
1424                        final_env,
1425                        apply_permissions,
1426                        apply_chroot,
1427                        apply_tty_stdin,
1428                        s->meta.manager->confirm_spawn,
1429                        s->meta.cgroup_bondings,
1430                        &pid);
1431
1432         if (r < 0)
1433                 goto fail;
1434
1435
1436         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1437                 /* FIXME: we need to do something here */
1438                 goto fail;
1439
1440         free(fdsbuf);
1441         strv_free(argv);
1442         strv_free(our_env);
1443         strv_free(final_env);
1444
1445         *_pid = pid;
1446
1447         return 0;
1448
1449 fail:
1450         free(fdsbuf);
1451         strv_free(argv);
1452         strv_free(our_env);
1453         strv_free(final_env);
1454
1455         if (timeout)
1456                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1457
1458         return r;
1459 }
1460
1461 static int main_pid_good(Service *s) {
1462         assert(s);
1463
1464         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1465          * don't know */
1466
1467         /* If we know the pid file, then lets just check if it is
1468          * still valid */
1469         if (s->main_pid_known)
1470                 return s->main_pid > 0;
1471
1472         /* We don't know the pid */
1473         return -EAGAIN;
1474 }
1475
1476 static int control_pid_good(Service *s) {
1477         assert(s);
1478
1479         return s->control_pid > 0;
1480 }
1481
1482 static int cgroup_good(Service *s) {
1483         int r;
1484
1485         assert(s);
1486
1487         if ((r = cgroup_bonding_is_empty_list(s->meta.cgroup_bondings)) < 0)
1488                 return r;
1489
1490         return !r;
1491 }
1492
1493 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
1494         int r;
1495         assert(s);
1496
1497         if (!success)
1498                 s->failure = true;
1499
1500         if (allow_restart &&
1501             !s->forbid_restart &&
1502             (s->restart == SERVICE_RESTART_ALWAYS ||
1503              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
1504
1505                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
1506                         goto fail;
1507
1508                 service_set_state(s, SERVICE_AUTO_RESTART);
1509         } else
1510                 service_set_state(s, s->failure ? SERVICE_FAILED : SERVICE_DEAD);
1511
1512         s->forbid_restart = false;
1513
1514         return;
1515
1516 fail:
1517         log_warning("%s failed to run install restart timer: %s", s->meta.id, strerror(-r));
1518         service_enter_dead(s, false, false);
1519 }
1520
1521 static void service_enter_signal(Service *s, ServiceState state, bool success);
1522
1523 static void service_enter_stop_post(Service *s, bool success) {
1524         int r;
1525         assert(s);
1526
1527         if (!success)
1528                 s->failure = true;
1529
1530         service_unwatch_control_pid(s);
1531
1532         s->control_command_id = SERVICE_EXEC_STOP_POST;
1533         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1534                 if ((r = service_spawn(s,
1535                                        s->control_command,
1536                                        true,
1537                                        false,
1538                                        !s->permissions_start_only,
1539                                        !s->root_directory_start_only,
1540                                        true,
1541                                        false,
1542                                        &s->control_pid)) < 0)
1543                         goto fail;
1544
1545
1546                 service_set_state(s, SERVICE_STOP_POST);
1547         } else
1548                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, true);
1549
1550         return;
1551
1552 fail:
1553         log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1554         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1555 }
1556
1557 static void service_enter_signal(Service *s, ServiceState state, bool success) {
1558         int r;
1559         Set *pid_set = NULL;
1560         bool wait_for_exit = false;
1561
1562         assert(s);
1563
1564         if (!success)
1565                 s->failure = true;
1566
1567         if (s->exec_context.kill_mode != KILL_NONE) {
1568                 int sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1569
1570                 if (s->main_pid > 0) {
1571                         if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1572                                  -s->main_pid :
1573                                  s->main_pid, sig) < 0 && errno != ESRCH)
1574
1575                                 log_warning("Failed to kill main process %li: %m", (long) s->main_pid);
1576                         else
1577                                 wait_for_exit = true;
1578                 }
1579
1580                 if (s->control_pid > 0) {
1581                         if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1582                                  -s->control_pid :
1583                                  s->control_pid, sig) < 0 && errno != ESRCH)
1584
1585                                 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1586                         else
1587                                 wait_for_exit = true;
1588                 }
1589
1590                 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1591
1592                         if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1593                                 r = -ENOMEM;
1594                                 goto fail;
1595                         }
1596
1597                         /* Exclude the main/control pids from being killed via the cgroup */
1598                         if (s->main_pid > 0)
1599                                 if ((r = set_put(pid_set, LONG_TO_PTR(s->main_pid))) < 0)
1600                                         goto fail;
1601
1602                         if (s->control_pid > 0)
1603                                 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1604                                         goto fail;
1605
1606                         if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1607                                 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1608                                         log_warning("Failed to kill control group: %s", strerror(-r));
1609                         } else if (r > 0)
1610                                 wait_for_exit = true;
1611
1612                         set_free(pid_set);
1613                 }
1614         }
1615
1616         if (wait_for_exit) {
1617                 if (s->timeout_usec > 0)
1618                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1619                                 goto fail;
1620
1621                 service_set_state(s, state);
1622         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1623                 service_enter_stop_post(s, true);
1624         else
1625                 service_enter_dead(s, true, true);
1626
1627         return;
1628
1629 fail:
1630         log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1631
1632         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1633                 service_enter_stop_post(s, false);
1634         else
1635                 service_enter_dead(s, false, true);
1636
1637         if (pid_set)
1638                 set_free(pid_set);
1639 }
1640
1641 static void service_enter_stop(Service *s, bool success) {
1642         int r;
1643
1644         assert(s);
1645
1646         if (!success)
1647                 s->failure = true;
1648
1649         service_unwatch_control_pid(s);
1650
1651         s->control_command_id = SERVICE_EXEC_STOP;
1652         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
1653                 if ((r = service_spawn(s,
1654                                        s->control_command,
1655                                        true,
1656                                        false,
1657                                        !s->permissions_start_only,
1658                                        !s->root_directory_start_only,
1659                                        false,
1660                                        false,
1661                                        &s->control_pid)) < 0)
1662                         goto fail;
1663
1664                 service_set_state(s, SERVICE_STOP);
1665         } else
1666                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1667
1668         return;
1669
1670 fail:
1671         log_warning("%s failed to run 'stop' task: %s", s->meta.id, strerror(-r));
1672         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1673 }
1674
1675 static void service_enter_running(Service *s, bool success) {
1676         int main_pid_ok, cgroup_ok;
1677         assert(s);
1678
1679         if (!success)
1680                 s->failure = true;
1681
1682         main_pid_ok = main_pid_good(s);
1683         cgroup_ok = cgroup_good(s);
1684
1685         if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1686             (s->bus_name_good || s->type != SERVICE_DBUS))
1687                 service_set_state(s, SERVICE_RUNNING);
1688         else if (s->remain_after_exit)
1689                 service_set_state(s, SERVICE_EXITED);
1690         else
1691                 service_enter_stop(s, true);
1692 }
1693
1694 static void service_enter_start_post(Service *s) {
1695         int r;
1696         assert(s);
1697
1698         service_unwatch_control_pid(s);
1699
1700         s->control_command_id = SERVICE_EXEC_START_POST;
1701         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
1702                 if ((r = service_spawn(s,
1703                                        s->control_command,
1704                                        true,
1705                                        false,
1706                                        !s->permissions_start_only,
1707                                        !s->root_directory_start_only,
1708                                        false,
1709                                        false,
1710                                        &s->control_pid)) < 0)
1711                         goto fail;
1712
1713                 service_set_state(s, SERVICE_START_POST);
1714         } else
1715                 service_enter_running(s, true);
1716
1717         return;
1718
1719 fail:
1720         log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1721         service_enter_stop(s, false);
1722 }
1723
1724 static void service_enter_start(Service *s) {
1725         pid_t pid;
1726         int r;
1727
1728         assert(s);
1729
1730         assert(s->exec_command[SERVICE_EXEC_START]);
1731         assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1732
1733         if (s->type == SERVICE_FORKING)
1734                 service_unwatch_control_pid(s);
1735         else
1736                 service_unwatch_main_pid(s);
1737
1738         s->control_command_id = SERVICE_EXEC_START;
1739         s->control_command = s->exec_command[SERVICE_EXEC_START];
1740
1741         if ((r = service_spawn(s,
1742                                s->control_command,
1743                                s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY,
1744                                true,
1745                                true,
1746                                true,
1747                                true,
1748                                s->notify_access != NOTIFY_NONE,
1749                                &pid)) < 0)
1750                 goto fail;
1751
1752         if (s->type == SERVICE_SIMPLE) {
1753                 /* For simple services we immediately start
1754                  * the START_POST binaries. */
1755
1756                 service_set_main_pid(s, pid);
1757                 service_enter_start_post(s);
1758
1759         } else  if (s->type == SERVICE_FORKING) {
1760
1761                 /* For forking services we wait until the start
1762                  * process exited. */
1763
1764                 s->control_pid = pid;
1765                 service_set_state(s, SERVICE_START);
1766
1767         } else if (s->type == SERVICE_ONESHOT ||
1768                    s->type == SERVICE_DBUS ||
1769                    s->type == SERVICE_NOTIFY) {
1770
1771                 /* For oneshot services we wait until the start
1772                  * process exited, too, but it is our main process. */
1773
1774                 /* For D-Bus services we know the main pid right away,
1775                  * but wait for the bus name to appear on the
1776                  * bus. Notify services are similar. */
1777
1778                 service_set_main_pid(s, pid);
1779                 service_set_state(s, SERVICE_START);
1780         } else
1781                 assert_not_reached("Unknown service type");
1782
1783         return;
1784
1785 fail:
1786         log_warning("%s failed to run 'start' task: %s", s->meta.id, strerror(-r));
1787         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1788 }
1789
1790 static void service_enter_start_pre(Service *s) {
1791         int r;
1792
1793         assert(s);
1794
1795         service_unwatch_control_pid(s);
1796
1797         s->control_command_id = SERVICE_EXEC_START_PRE;
1798         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
1799                 if ((r = service_spawn(s,
1800                                        s->control_command,
1801                                        true,
1802                                        false,
1803                                        !s->permissions_start_only,
1804                                        !s->root_directory_start_only,
1805                                        true,
1806                                        false,
1807                                        &s->control_pid)) < 0)
1808                         goto fail;
1809
1810                 service_set_state(s, SERVICE_START_PRE);
1811         } else
1812                 service_enter_start(s);
1813
1814         return;
1815
1816 fail:
1817         log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1818         service_enter_dead(s, false, true);
1819 }
1820
1821 static void service_enter_restart(Service *s) {
1822         int r;
1823         DBusError error;
1824
1825         assert(s);
1826         dbus_error_init(&error);
1827
1828         service_enter_dead(s, true, false);
1829
1830         if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, &error, NULL)) < 0)
1831                 goto fail;
1832
1833         log_debug("%s scheduled restart job.", s->meta.id);
1834         return;
1835
1836 fail:
1837         log_warning("%s failed to schedule restart job: %s", s->meta.id, bus_error(&error, -r));
1838         service_enter_dead(s, false, false);
1839
1840         dbus_error_free(&error);
1841 }
1842
1843 static void service_enter_reload(Service *s) {
1844         int r;
1845
1846         assert(s);
1847
1848         service_unwatch_control_pid(s);
1849
1850         s->control_command_id = SERVICE_EXEC_RELOAD;
1851         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
1852                 if ((r = service_spawn(s,
1853                                        s->control_command,
1854                                        true,
1855                                        false,
1856                                        !s->permissions_start_only,
1857                                        !s->root_directory_start_only,
1858                                        false,
1859                                        false,
1860                                        &s->control_pid)) < 0)
1861                         goto fail;
1862
1863                 service_set_state(s, SERVICE_RELOAD);
1864         } else
1865                 service_enter_running(s, true);
1866
1867         return;
1868
1869 fail:
1870         log_warning("%s failed to run 'reload' task: %s", s->meta.id, strerror(-r));
1871         service_enter_stop(s, false);
1872 }
1873
1874 static void service_run_next_control(Service *s, bool success) {
1875         int r;
1876
1877         assert(s);
1878         assert(s->control_command);
1879         assert(s->control_command->command_next);
1880
1881         if (!success)
1882                 s->failure = true;
1883
1884         assert(s->control_command_id != SERVICE_EXEC_START);
1885
1886         s->control_command = s->control_command->command_next;
1887         service_unwatch_control_pid(s);
1888
1889         if ((r = service_spawn(s,
1890                                s->control_command,
1891                                true,
1892                                false,
1893                                !s->permissions_start_only,
1894                                !s->root_directory_start_only,
1895                                s->control_command_id == SERVICE_EXEC_START_PRE ||
1896                                s->control_command_id == SERVICE_EXEC_STOP_POST,
1897                                false,
1898                                &s->control_pid)) < 0)
1899                 goto fail;
1900
1901         return;
1902
1903 fail:
1904         log_warning("%s failed to run next control task: %s", s->meta.id, strerror(-r));
1905
1906         if (s->state == SERVICE_START_PRE)
1907                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1908         else if (s->state == SERVICE_STOP)
1909                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1910         else if (s->state == SERVICE_STOP_POST)
1911                 service_enter_dead(s, false, true);
1912         else
1913                 service_enter_stop(s, false);
1914 }
1915
1916 static void service_run_next_main(Service *s, bool success) {
1917         pid_t pid;
1918         int r;
1919
1920         assert(s);
1921         assert(s->control_command);
1922         assert(s->control_command->command_next);
1923
1924         if (!success)
1925                 s->failure = true;
1926
1927         assert(s->control_command_id == SERVICE_EXEC_START);
1928         assert(s->type == SERVICE_ONESHOT);
1929
1930         s->control_command = s->control_command->command_next;
1931         service_unwatch_main_pid(s);
1932
1933         if ((r = service_spawn(s,
1934                                s->control_command,
1935                                false,
1936                                true,
1937                                true,
1938                                true,
1939                                true,
1940                                s->notify_access != NOTIFY_NONE,
1941                                &pid)) < 0)
1942                 goto fail;
1943
1944         service_set_main_pid(s, pid);
1945
1946         return;
1947
1948 fail:
1949         log_warning("%s failed to run next main task: %s", s->meta.id, strerror(-r));
1950         service_enter_stop(s, false);
1951 }
1952
1953 static int service_start(Unit *u) {
1954         Service *s = SERVICE(u);
1955
1956         assert(s);
1957
1958         /* We cannot fulfill this request right now, try again later
1959          * please! */
1960         if (s->state == SERVICE_STOP ||
1961             s->state == SERVICE_STOP_SIGTERM ||
1962             s->state == SERVICE_STOP_SIGKILL ||
1963             s->state == SERVICE_STOP_POST ||
1964             s->state == SERVICE_FINAL_SIGTERM ||
1965             s->state == SERVICE_FINAL_SIGKILL)
1966                 return -EAGAIN;
1967
1968         /* Already on it! */
1969         if (s->state == SERVICE_START_PRE ||
1970             s->state == SERVICE_START ||
1971             s->state == SERVICE_START_POST)
1972                 return 0;
1973
1974         assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED || s->state == SERVICE_AUTO_RESTART);
1975
1976         /* Make sure we don't enter a busy loop of some kind. */
1977         if (!ratelimit_test(&s->ratelimit)) {
1978                 log_warning("%s start request repeated too quickly, refusing to start.", u->meta.id);
1979                 return -ECANCELED;
1980         }
1981
1982         if ((s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1983              s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1984              s->exec_context.std_error == EXEC_OUTPUT_SOCKET) &&
1985             s->socket_fd < 0) {
1986                 log_warning("%s can only be started with a per-connection socket.", u->meta.id);
1987                 return -EINVAL;
1988         }
1989
1990         s->failure = false;
1991         s->main_pid_known = false;
1992         s->forbid_restart = false;
1993
1994         service_enter_start_pre(s);
1995         return 0;
1996 }
1997
1998 static int service_stop(Unit *u) {
1999         Service *s = SERVICE(u);
2000
2001         assert(s);
2002
2003         /* This is a user request, so don't do restarts on this
2004          * shutdown. */
2005         s->forbid_restart = true;
2006
2007         /* Already on it */
2008         if (s->state == SERVICE_STOP ||
2009             s->state == SERVICE_STOP_SIGTERM ||
2010             s->state == SERVICE_STOP_SIGKILL ||
2011             s->state == SERVICE_STOP_POST ||
2012             s->state == SERVICE_FINAL_SIGTERM ||
2013             s->state == SERVICE_FINAL_SIGKILL)
2014                 return 0;
2015
2016         /* Don't allow a restart */
2017         if (s->state == SERVICE_AUTO_RESTART) {
2018                 service_set_state(s, SERVICE_DEAD);
2019                 return 0;
2020         }
2021
2022         /* If there's already something running we go directly into
2023          * kill mode. */
2024         if (s->state == SERVICE_START_PRE ||
2025             s->state == SERVICE_START ||
2026             s->state == SERVICE_START_POST ||
2027             s->state == SERVICE_RELOAD) {
2028                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
2029                 return 0;
2030         }
2031
2032         assert(s->state == SERVICE_RUNNING ||
2033                s->state == SERVICE_EXITED);
2034
2035         service_enter_stop(s, true);
2036         return 0;
2037 }
2038
2039 static int service_reload(Unit *u) {
2040         Service *s = SERVICE(u);
2041
2042         assert(s);
2043
2044         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2045
2046         service_enter_reload(s);
2047         return 0;
2048 }
2049
2050 static bool service_can_reload(Unit *u) {
2051         Service *s = SERVICE(u);
2052
2053         assert(s);
2054
2055         return !!s->exec_command[SERVICE_EXEC_RELOAD];
2056 }
2057
2058 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2059         Service *s = SERVICE(u);
2060
2061         assert(u);
2062         assert(f);
2063         assert(fds);
2064
2065         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2066         unit_serialize_item(u, f, "failure", yes_no(s->failure));
2067
2068         if (s->control_pid > 0)
2069                 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2070
2071         if (s->main_pid_known && s->main_pid > 0)
2072                 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2073
2074         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2075
2076         if (s->status_text)
2077                 unit_serialize_item(u, f, "status-text", s->status_text);
2078
2079         /* There's a minor uncleanliness here: if there are multiple
2080          * commands attached here, we will start from the first one
2081          * again */
2082         if (s->control_command_id >= 0)
2083                 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2084
2085         if (s->socket_fd >= 0) {
2086                 int copy;
2087
2088                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2089                         return copy;
2090
2091                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2092         }
2093
2094         if (s->main_exec_status.pid > 0) {
2095                 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2096
2097                 if (s->main_exec_status.start_timestamp.realtime > 0) {
2098                         unit_serialize_item_format(u, f, "main-exec-status-start-realtime",
2099                                                    "%llu", (unsigned long long) s->main_exec_status.start_timestamp.realtime);
2100
2101                         unit_serialize_item_format(u, f, "main-exec-status-start-monotonic",
2102                                                    "%llu", (unsigned long long) s->main_exec_status.start_timestamp.monotonic);
2103                 }
2104
2105                 if (s->main_exec_status.exit_timestamp.realtime > 0) {
2106                         unit_serialize_item_format(u, f, "main-exec-status-exit-realtime",
2107                                                    "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.realtime);
2108                         unit_serialize_item_format(u, f, "main-exec-status-exit-monotonic",
2109                                                    "%llu", (unsigned long long) s->main_exec_status.exit_timestamp.monotonic);
2110
2111                         unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2112                         unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2113                 }
2114         }
2115
2116         return 0;
2117 }
2118
2119 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2120         Service *s = SERVICE(u);
2121
2122         assert(u);
2123         assert(key);
2124         assert(value);
2125         assert(fds);
2126
2127         if (streq(key, "state")) {
2128                 ServiceState state;
2129
2130                 if ((state = service_state_from_string(value)) < 0)
2131                         log_debug("Failed to parse state value %s", value);
2132                 else
2133                         s->deserialized_state = state;
2134         } else if (streq(key, "failure")) {
2135                 int b;
2136
2137                 if ((b = parse_boolean(value)) < 0)
2138                         log_debug("Failed to parse failure value %s", value);
2139                 else
2140                         s->failure = b || s->failure;
2141         } else if (streq(key, "control-pid")) {
2142                 pid_t pid;
2143
2144                 if (parse_pid(value, &pid) < 0)
2145                         log_debug("Failed to parse control-pid value %s", value);
2146                 else
2147                         s->control_pid = pid;
2148         } else if (streq(key, "main-pid")) {
2149                 pid_t pid;
2150
2151                 if (parse_pid(value, &pid) < 0)
2152                         log_debug("Failed to parse main-pid value %s", value);
2153                 else
2154                         service_set_main_pid(s, (pid_t) pid);
2155         } else if (streq(key, "main-pid-known")) {
2156                 int b;
2157
2158                 if ((b = parse_boolean(value)) < 0)
2159                         log_debug("Failed to parse main-pid-known value %s", value);
2160                 else
2161                         s->main_pid_known = b;
2162         } else if (streq(key, "status-text")) {
2163                 char *t;
2164
2165                 if ((t = strdup(value))) {
2166                         free(s->status_text);
2167                         s->status_text = t;
2168                 }
2169
2170         } else if (streq(key, "control-command")) {
2171                 ServiceExecCommand id;
2172
2173                 if ((id = service_exec_command_from_string(value)) < 0)
2174                         log_debug("Failed to parse exec-command value %s", value);
2175                 else {
2176                         s->control_command_id = id;
2177                         s->control_command = s->exec_command[id];
2178                 }
2179         } else if (streq(key, "socket-fd")) {
2180                 int fd;
2181
2182                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2183                         log_debug("Failed to parse socket-fd value %s", value);
2184                 else {
2185
2186                         if (s->socket_fd >= 0)
2187                                 close_nointr_nofail(s->socket_fd);
2188                         s->socket_fd = fdset_remove(fds, fd);
2189                 }
2190         } else if (streq(key, "main-exec-status-pid")) {
2191                 pid_t pid;
2192
2193                 if (parse_pid(value, &pid) < 0)
2194                         log_debug("Failed to parse main-exec-status-pid value %s", value);
2195                 else
2196                         s->main_exec_status.pid = pid;
2197         } else if (streq(key, "main-exec-status-code")) {
2198                 int i;
2199
2200                 if (safe_atoi(value, &i) < 0)
2201                         log_debug("Failed to parse main-exec-status-code value %s", value);
2202                 else
2203                         s->main_exec_status.code = i;
2204         } else if (streq(key, "main-exec-status-status")) {
2205                 int i;
2206
2207                 if (safe_atoi(value, &i) < 0)
2208                         log_debug("Failed to parse main-exec-status-status value %s", value);
2209                 else
2210                         s->main_exec_status.status = i;
2211         } else if (streq(key, "main-exec-status-start-realtime")) {
2212                 uint64_t k;
2213
2214                 if (safe_atou64(value, &k) < 0)
2215                         log_debug("Failed to parse main-exec-status-start-realtime value %s", value);
2216                 else
2217                         s->main_exec_status.start_timestamp.realtime = (usec_t) k;
2218         } else if (streq(key, "main-exec-status-start-monotonic")) {
2219                 uint64_t k;
2220
2221                 if (safe_atou64(value, &k) < 0)
2222                         log_debug("Failed to parse main-exec-status-start-monotonic value %s", value);
2223                 else
2224                         s->main_exec_status.start_timestamp.monotonic = (usec_t) k;
2225         } else if (streq(key, "main-exec-status-exit-realtime")) {
2226                 uint64_t k;
2227
2228                 if (safe_atou64(value, &k) < 0)
2229                         log_debug("Failed to parse main-exec-status-exit-realtime value %s", value);
2230                 else
2231                         s->main_exec_status.exit_timestamp.realtime = (usec_t) k;
2232         } else if (streq(key, "main-exec-status-exit-monotonic")) {
2233                 uint64_t k;
2234
2235                 if (safe_atou64(value, &k) < 0)
2236                         log_debug("Failed to parse main-exec-status-exit-monotonic value %s", value);
2237                 else
2238                         s->main_exec_status.exit_timestamp.monotonic = (usec_t) k;
2239         } else
2240                 log_debug("Unknown serialization key '%s'", key);
2241
2242         return 0;
2243 }
2244
2245 static UnitActiveState service_active_state(Unit *u) {
2246         assert(u);
2247
2248         return state_translation_table[SERVICE(u)->state];
2249 }
2250
2251 static const char *service_sub_state_to_string(Unit *u) {
2252         assert(u);
2253
2254         return service_state_to_string(SERVICE(u)->state);
2255 }
2256
2257 static bool service_check_gc(Unit *u) {
2258         Service *s = SERVICE(u);
2259
2260         assert(s);
2261
2262         return !!s->sysv_path;
2263 }
2264
2265 static bool service_check_snapshot(Unit *u) {
2266         Service *s = SERVICE(u);
2267
2268         assert(s);
2269
2270         return !s->got_socket_fd;
2271 }
2272
2273 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2274         Service *s = SERVICE(u);
2275         bool success;
2276
2277         assert(s);
2278         assert(pid >= 0);
2279
2280         if (s->sysv_path)
2281                 success = is_clean_exit_lsb(code, status);
2282         else
2283                 success = is_clean_exit(code, status);
2284
2285         if (s->main_pid == pid) {
2286
2287                 s->main_pid = 0;
2288                 exec_status_exit(&s->main_exec_status, pid, code, status);
2289
2290                 if (s->type != SERVICE_FORKING && s->control_command) {
2291                         s->control_command->exec_status = s->main_exec_status;
2292
2293                         if (s->control_command->ignore)
2294                                 success = true;
2295                 }
2296
2297                 log_full(success ? LOG_DEBUG : LOG_NOTICE,
2298                          "%s: main process exited, code=%s, status=%i", u->meta.id, sigchld_code_to_string(code), status);
2299                 s->failure = s->failure || !success;
2300
2301                 if (s->control_command &&
2302                     s->control_command->command_next &&
2303                     success) {
2304
2305                         /* There is another command to *
2306                          * execute, so let's do that. */
2307
2308                         log_debug("%s running next main command for state %s", u->meta.id, service_state_to_string(s->state));
2309                         service_run_next_main(s, success);
2310
2311                 } else {
2312
2313                         /* The service exited, so the service is officially
2314                          * gone. */
2315
2316                         s->control_command = NULL;
2317                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2318
2319                         switch (s->state) {
2320
2321                         case SERVICE_START_POST:
2322                         case SERVICE_RELOAD:
2323                         case SERVICE_STOP:
2324                                 /* Need to wait until the operation is
2325                                  * done */
2326                                 break;
2327
2328                         case SERVICE_START:
2329                                 if (s->type == SERVICE_ONESHOT) {
2330                                         /* This was our main goal, so let's go on */
2331                                         if (success)
2332                                                 service_enter_start_post(s);
2333                                         else
2334                                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2335                                         break;
2336                                 } else {
2337                                         assert(s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY);
2338
2339                                         /* Fall through */
2340                                 }
2341
2342                         case SERVICE_RUNNING:
2343                                 service_enter_running(s, success);
2344                                 break;
2345
2346                         case SERVICE_STOP_SIGTERM:
2347                         case SERVICE_STOP_SIGKILL:
2348
2349                                 if (!control_pid_good(s))
2350                                         service_enter_stop_post(s, success);
2351
2352                                 /* If there is still a control process, wait for that first */
2353                                 break;
2354
2355                         default:
2356                                 assert_not_reached("Uh, main process died at wrong time.");
2357                         }
2358                 }
2359
2360         } else if (s->control_pid == pid) {
2361
2362                 s->control_pid = 0;
2363
2364                 if (s->control_command) {
2365                         exec_status_exit(&s->control_command->exec_status, pid, code, status);
2366
2367                         if (s->control_command->ignore)
2368                                 success = true;
2369                 }
2370
2371                log_full(success ? LOG_DEBUG : LOG_NOTICE,
2372                          "%s: control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
2373                 s->failure = s->failure || !success;
2374
2375                 if (s->control_command &&
2376                     s->control_command->command_next &&
2377                     success) {
2378
2379                         /* There is another command to *
2380                          * execute, so let's do that. */
2381
2382                         log_debug("%s running next control command for state %s", u->meta.id, service_state_to_string(s->state));
2383                         service_run_next_control(s, success);
2384
2385                 } else {
2386                         /* No further commands for this step, so let's
2387                          * figure out what to do next */
2388
2389                         s->control_command = NULL;
2390                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2391
2392                         log_debug("%s got final SIGCHLD for state %s", u->meta.id, service_state_to_string(s->state));
2393
2394                         switch (s->state) {
2395
2396                         case SERVICE_START_PRE:
2397                                 if (success)
2398                                         service_enter_start(s);
2399                                 else
2400                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2401                                 break;
2402
2403                         case SERVICE_START:
2404                                 assert(s->type == SERVICE_FORKING);
2405
2406                                 /* Let's try to load the pid
2407                                  * file here if we can. We
2408                                  * ignore the return value,
2409                                  * since the PID file might
2410                                  * actually be created by a
2411                                  * START_POST script */
2412
2413                                 if (success) {
2414                                         if (s->pid_file)
2415                                                 service_load_pid_file(s);
2416
2417                                         service_enter_start_post(s);
2418                                 } else
2419                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2420
2421                                 break;
2422
2423                         case SERVICE_START_POST:
2424                                 if (success && s->pid_file && !s->main_pid_known) {
2425                                         int r;
2426
2427                                         /* Hmm, let's see if we can
2428                                          * load the pid now after the
2429                                          * start-post scripts got
2430                                          * executed. */
2431
2432                                         if ((r = service_load_pid_file(s)) < 0)
2433                                                 log_warning("%s: failed to load PID file %s: %s", s->meta.id, s->pid_file, strerror(-r));
2434                                 }
2435
2436                                 /* Fall through */
2437
2438                         case SERVICE_RELOAD:
2439                                 if (success)
2440                                         service_enter_running(s, true);
2441                                 else
2442                                         service_enter_stop(s, false);
2443
2444                                 break;
2445
2446                         case SERVICE_STOP:
2447                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
2448                                 break;
2449
2450                         case SERVICE_STOP_SIGTERM:
2451                         case SERVICE_STOP_SIGKILL:
2452                                 if (main_pid_good(s) <= 0)
2453                                         service_enter_stop_post(s, success);
2454
2455                                 /* If there is still a service
2456                                  * process around, wait until
2457                                  * that one quit, too */
2458                                 break;
2459
2460                         case SERVICE_STOP_POST:
2461                         case SERVICE_FINAL_SIGTERM:
2462                         case SERVICE_FINAL_SIGKILL:
2463                                 service_enter_dead(s, success, true);
2464                                 break;
2465
2466                         default:
2467                                 assert_not_reached("Uh, control process died at wrong time.");
2468                         }
2469                 }
2470         }
2471
2472         /* Notify clients about changed exit status */
2473         unit_add_to_dbus_queue(u);
2474 }
2475
2476 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
2477         Service *s = SERVICE(u);
2478
2479         assert(s);
2480         assert(elapsed == 1);
2481
2482         assert(w == &s->timer_watch);
2483
2484         switch (s->state) {
2485
2486         case SERVICE_START_PRE:
2487         case SERVICE_START:
2488                 log_warning("%s operation timed out. Terminating.", u->meta.id);
2489                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2490                 break;
2491
2492         case SERVICE_START_POST:
2493         case SERVICE_RELOAD:
2494                 log_warning("%s operation timed out. Stopping.", u->meta.id);
2495                 service_enter_stop(s, false);
2496                 break;
2497
2498         case SERVICE_STOP:
2499                 log_warning("%s stopping timed out. Terminating.", u->meta.id);
2500                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
2501                 break;
2502
2503         case SERVICE_STOP_SIGTERM:
2504                 log_warning("%s stopping timed out. Killing.", u->meta.id);
2505                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
2506                 break;
2507
2508         case SERVICE_STOP_SIGKILL:
2509                 /* Uh, wie sent a SIGKILL and it is still not gone?
2510                  * Must be something we cannot kill, so let's just be
2511                  * weirded out and continue */
2512
2513                 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
2514                 service_enter_stop_post(s, false);
2515                 break;
2516
2517         case SERVICE_STOP_POST:
2518                 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
2519                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
2520                 break;
2521
2522         case SERVICE_FINAL_SIGTERM:
2523                 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
2524                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
2525                 break;
2526
2527         case SERVICE_FINAL_SIGKILL:
2528                 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
2529                 service_enter_dead(s, false, true);
2530                 break;
2531
2532         case SERVICE_AUTO_RESTART:
2533                 log_info("%s holdoff time over, scheduling restart.", u->meta.id);
2534                 service_enter_restart(s);
2535                 break;
2536
2537         default:
2538                 assert_not_reached("Timeout at wrong time.");
2539         }
2540 }
2541
2542 static void service_cgroup_notify_event(Unit *u) {
2543         Service *s = SERVICE(u);
2544
2545         assert(u);
2546
2547         log_debug("%s: cgroup is empty", u->meta.id);
2548
2549         switch (s->state) {
2550
2551                 /* Waiting for SIGCHLD is usually more interesting,
2552                  * because it includes return codes/signals. Which is
2553                  * why we ignore the cgroup events for most cases,
2554                  * except when we don't know pid which to expect the
2555                  * SIGCHLD for. */
2556
2557         case SERVICE_RUNNING:
2558                 service_enter_running(s, true);
2559                 break;
2560
2561         case SERVICE_STOP_SIGTERM:
2562         case SERVICE_STOP_SIGKILL:
2563                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2564                         service_enter_stop_post(s, true);
2565
2566                 break;
2567
2568         case SERVICE_FINAL_SIGTERM:
2569         case SERVICE_FINAL_SIGKILL:
2570                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2571                         service_enter_dead(s, true, true);
2572
2573                 break;
2574
2575         default:
2576                 ;
2577         }
2578 }
2579
2580 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2581         Service *s = SERVICE(u);
2582         const char *e;
2583
2584         assert(u);
2585
2586         if (s->notify_access == NOTIFY_NONE) {
2587                 log_warning("%s: Got notification message from PID %lu, but reception is disabled.",
2588                             u->meta.id, (unsigned long) pid);
2589                 return;
2590         }
2591
2592         if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2593                 log_warning("%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
2594                             u->meta.id, (unsigned long) pid, (unsigned long) s->main_pid);
2595                 return;
2596         }
2597
2598         log_debug("%s: Got message", u->meta.id);
2599
2600         /* Interpret MAINPID= */
2601         if ((e = strv_find_prefix(tags, "MAINPID=")) &&
2602             (s->state == SERVICE_START ||
2603              s->state == SERVICE_START_POST ||
2604              s->state == SERVICE_RUNNING ||
2605              s->state == SERVICE_RELOAD)) {
2606
2607                 if (parse_pid(e + 8, &pid) < 0)
2608                         log_warning("Failed to parse notification message %s", e);
2609                 else {
2610                         log_debug("%s: got %s", u->meta.id, e);
2611                         service_set_main_pid(s, pid);
2612                 }
2613         }
2614
2615         /* Interpret READY= */
2616         if (s->type == SERVICE_NOTIFY &&
2617             s->state == SERVICE_START &&
2618             strv_find(tags, "READY=1")) {
2619                 log_debug("%s: got READY=1", u->meta.id);
2620
2621                 service_enter_start_post(s);
2622         }
2623
2624         /* Interpret STATUS= */
2625         if ((e = strv_find_prefix(tags, "STATUS="))) {
2626                 char *t;
2627
2628                 if (e[7]) {
2629                         if (!(t = strdup(e+7))) {
2630                                 log_error("Failed to allocate string.");
2631                                 return;
2632                         }
2633
2634                         log_debug("%s: got %s", u->meta.id, e);
2635
2636                         free(s->status_text);
2637                         s->status_text = t;
2638                 } else {
2639                         free(s->status_text);
2640                         s->status_text = NULL;
2641                 }
2642
2643         }
2644
2645         /* Notify clients about changed status or main pid */
2646         unit_add_to_dbus_queue(u);
2647 }
2648
2649 static int service_enumerate(Manager *m) {
2650         char **p;
2651         unsigned i;
2652         DIR *d = NULL;
2653         char *path = NULL, *fpath = NULL, *name = NULL;
2654         Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
2655         Unit *service;
2656         Iterator j;
2657         int r;
2658
2659         assert(m);
2660
2661         zero(runlevel_services);
2662
2663         STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
2664                 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2665                         struct dirent *de;
2666
2667                         free(path);
2668                         path = NULL;
2669                         if (asprintf(&path, "%s/%s", *p, rcnd_table[i].path) < 0) {
2670                                 r = -ENOMEM;
2671                                 goto finish;
2672                         }
2673
2674                         if (d)
2675                                 closedir(d);
2676
2677                         if (!(d = opendir(path))) {
2678                                 if (errno != ENOENT)
2679                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
2680
2681                                 continue;
2682                         }
2683
2684                         while ((de = readdir(d))) {
2685                                 int a, b;
2686
2687                                 if (ignore_file(de->d_name))
2688                                         continue;
2689
2690                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
2691                                         continue;
2692
2693                                 if (strlen(de->d_name) < 4)
2694                                         continue;
2695
2696                                 a = undecchar(de->d_name[1]);
2697                                 b = undecchar(de->d_name[2]);
2698
2699                                 if (a < 0 || b < 0)
2700                                         continue;
2701
2702                                 free(fpath);
2703                                 fpath = NULL;
2704                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd_table[i].path, de->d_name) < 0) {
2705                                         r = -ENOMEM;
2706                                         goto finish;
2707                                 }
2708
2709                                 if (access(fpath, X_OK) < 0) {
2710
2711                                         if (errno != ENOENT)
2712                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
2713
2714                                         continue;
2715                                 }
2716
2717                                 free(name);
2718                                 if (!(name = sysv_translate_name(de->d_name + 3))) {
2719                                         r = -ENOMEM;
2720                                         goto finish;
2721                                 }
2722
2723                                 if ((r = manager_load_unit_prepare(m, name, NULL, NULL, &service)) < 0) {
2724                                         log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
2725                                         continue;
2726                                 }
2727
2728                                 if (de->d_name[0] == 'S')  {
2729
2730                                         if (rcnd_table[i].type == RUNLEVEL_UP || rcnd_table[i].type == RUNLEVEL_SYSINIT) {
2731                                                 SERVICE(service)->sysv_start_priority =
2732                                                         MAX(a*10 + b, SERVICE(service)->sysv_start_priority);
2733
2734                                                 SERVICE(service)->sysv_enabled = true;
2735                                         }
2736
2737                                         if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
2738                                                 goto finish;
2739
2740                                         if ((r = set_put(runlevel_services[i], service)) < 0)
2741                                                 goto finish;
2742
2743                                 } else if (de->d_name[0] == 'K' &&
2744                                            (rcnd_table[i].type == RUNLEVEL_DOWN ||
2745                                             rcnd_table[i].type == RUNLEVEL_SYSINIT)) {
2746
2747                                         if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
2748                                                 goto finish;
2749
2750                                         if ((r = set_put(shutdown_services, service)) < 0)
2751                                                 goto finish;
2752                                 }
2753                         }
2754                 }
2755
2756         /* Now we loaded all stubs and are aware of the lowest
2757         start-up priority for all services, not let's actually load
2758         the services, this will also tell us which services are
2759         actually native now */
2760         manager_dispatch_load_queue(m);
2761
2762         /* If this is a native service, rely on native ways to pull in
2763          * a service, don't pull it in via sysv rcN.d links. */
2764         for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
2765                 SET_FOREACH(service, runlevel_services[i], j) {
2766                         service = unit_follow_merge(service);
2767
2768                         if (service->meta.fragment_path)
2769                                 continue;
2770
2771                         if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
2772                                 goto finish;
2773                 }
2774
2775         /* We honour K links only for halt/reboot. For the normal
2776          * runlevels we assume the stop jobs will be implicitly added
2777          * by the core logic. Also, we don't really distuingish here
2778          * between the runlevels 0 and 6 and just add them to the
2779          * special shutdown target. On SUSE the boot.d/ runlevel is
2780          * also used for shutdown, so we add links for that too to the
2781          * shutdown target.*/
2782         SET_FOREACH(service, shutdown_services, j) {
2783                 service = unit_follow_merge(service);
2784
2785                 if (service->meta.fragment_path)
2786                         continue;
2787
2788                 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
2789                         goto finish;
2790         }
2791
2792         r = 0;
2793
2794 finish:
2795         free(path);
2796         free(fpath);
2797         free(name);
2798
2799         for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
2800                 set_free(runlevel_services[i]);
2801         set_free(shutdown_services);
2802
2803         if (d)
2804                 closedir(d);
2805
2806         return r;
2807 }
2808
2809 static void service_bus_name_owner_change(
2810                 Unit *u,
2811                 const char *name,
2812                 const char *old_owner,
2813                 const char *new_owner) {
2814
2815         Service *s = SERVICE(u);
2816
2817         assert(s);
2818         assert(name);
2819
2820         assert(streq(s->bus_name, name));
2821         assert(old_owner || new_owner);
2822
2823         if (old_owner && new_owner)
2824                 log_debug("%s's D-Bus name %s changed owner from %s to %s", u->meta.id, name, old_owner, new_owner);
2825         else if (old_owner)
2826                 log_debug("%s's D-Bus name %s no longer registered by %s", u->meta.id, name, old_owner);
2827         else
2828                 log_debug("%s's D-Bus name %s now registered by %s", u->meta.id, name, new_owner);
2829
2830         s->bus_name_good = !!new_owner;
2831
2832         if (s->type == SERVICE_DBUS) {
2833
2834                 /* service_enter_running() will figure out what to
2835                  * do */
2836                 if (s->state == SERVICE_RUNNING)
2837                         service_enter_running(s, true);
2838                 else if (s->state == SERVICE_START && new_owner)
2839                         service_enter_start_post(s);
2840
2841         } else if (new_owner &&
2842                    s->main_pid <= 0 &&
2843                    (s->state == SERVICE_START ||
2844                     s->state == SERVICE_START_POST ||
2845                     s->state == SERVICE_RUNNING ||
2846                     s->state == SERVICE_RELOAD)) {
2847
2848                 /* Try to acquire PID from bus service */
2849                 log_debug("Trying to acquire PID from D-Bus name...");
2850
2851                 bus_query_pid(u->meta.manager, name);
2852         }
2853 }
2854
2855 static void service_bus_query_pid_done(
2856                 Unit *u,
2857                 const char *name,
2858                 pid_t pid) {
2859
2860         Service *s = SERVICE(u);
2861
2862         assert(s);
2863         assert(name);
2864
2865         log_debug("%s's D-Bus name %s is now owned by process %u", u->meta.id, name, (unsigned) pid);
2866
2867         if (s->main_pid <= 0 &&
2868             (s->state == SERVICE_START ||
2869              s->state == SERVICE_START_POST ||
2870              s->state == SERVICE_RUNNING ||
2871              s->state == SERVICE_RELOAD))
2872                 service_set_main_pid(s, pid);
2873 }
2874
2875 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2876         assert(s);
2877         assert(fd >= 0);
2878
2879         /* This is called by the socket code when instantiating a new
2880          * service for a stream socket and the socket needs to be
2881          * configured. */
2882
2883         if (s->meta.load_state != UNIT_LOADED)
2884                 return -EINVAL;
2885
2886         if (s->socket_fd >= 0)
2887                 return -EBUSY;
2888
2889         if (s->state != SERVICE_DEAD)
2890                 return -EAGAIN;
2891
2892         s->socket_fd = fd;
2893         s->got_socket_fd = true;
2894         s->socket = sock;
2895
2896         return 0;
2897 }
2898
2899 static void service_reset_failed(Unit *u) {
2900         Service *s = SERVICE(u);
2901
2902         assert(s);
2903
2904         if (s->state == SERVICE_FAILED)
2905                 service_set_state(s, SERVICE_DEAD);
2906
2907         s->failure = false;
2908 }
2909
2910 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2911         [SERVICE_DEAD] = "dead",
2912         [SERVICE_START_PRE] = "start-pre",
2913         [SERVICE_START] = "start",
2914         [SERVICE_START_POST] = "start-post",
2915         [SERVICE_RUNNING] = "running",
2916         [SERVICE_EXITED] = "exited",
2917         [SERVICE_RELOAD] = "reload",
2918         [SERVICE_STOP] = "stop",
2919         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2920         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2921         [SERVICE_STOP_POST] = "stop-post",
2922         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2923         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2924         [SERVICE_FAILED] = "failed",
2925         [SERVICE_AUTO_RESTART] = "auto-restart",
2926 };
2927
2928 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2929
2930 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2931         [SERVICE_ONCE] = "once",
2932         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
2933         [SERVICE_RESTART_ALWAYS] = "restart-always",
2934 };
2935
2936 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2937
2938 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2939         [SERVICE_SIMPLE] = "simple",
2940         [SERVICE_FORKING] = "forking",
2941         [SERVICE_ONESHOT] = "oneshot",
2942         [SERVICE_DBUS] = "dbus",
2943         [SERVICE_NOTIFY] = "notify"
2944 };
2945
2946 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2947
2948 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2949         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2950         [SERVICE_EXEC_START] = "ExecStart",
2951         [SERVICE_EXEC_START_POST] = "ExecStartPost",
2952         [SERVICE_EXEC_RELOAD] = "ExecReload",
2953         [SERVICE_EXEC_STOP] = "ExecStop",
2954         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2955 };
2956
2957 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2958
2959 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2960         [NOTIFY_NONE] = "none",
2961         [NOTIFY_MAIN] = "main",
2962         [NOTIFY_ALL] = "all"
2963 };
2964
2965 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2966
2967 const UnitVTable service_vtable = {
2968         .suffix = ".service",
2969         .show_status = true,
2970
2971         .init = service_init,
2972         .done = service_done,
2973         .load = service_load,
2974
2975         .coldplug = service_coldplug,
2976
2977         .dump = service_dump,
2978
2979         .start = service_start,
2980         .stop = service_stop,
2981         .reload = service_reload,
2982
2983         .can_reload = service_can_reload,
2984
2985         .serialize = service_serialize,
2986         .deserialize_item = service_deserialize_item,
2987
2988         .active_state = service_active_state,
2989         .sub_state_to_string = service_sub_state_to_string,
2990
2991         .check_gc = service_check_gc,
2992         .check_snapshot = service_check_snapshot,
2993
2994         .sigchld_event = service_sigchld_event,
2995         .timer_event = service_timer_event,
2996
2997         .reset_failed = service_reset_failed,
2998
2999         .cgroup_notify_empty = service_cgroup_notify_event,
3000         .notify_message = service_notify_message,
3001
3002         .bus_name_owner_change = service_bus_name_owner_change,
3003         .bus_query_pid_done = service_bus_query_pid_done,
3004
3005         .bus_interface = "org.freedesktop.systemd1.Service",
3006         .bus_message_handler = bus_service_message_handler,
3007         .bus_invalidating_properties =  bus_service_invalidating_properties,
3008
3009         .enumerate = service_enumerate
3010 };