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