]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/service.c
honor SELinux labels, when creating and writing config files
[thirdparty/systemd.git] / src / core / 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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser 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 #include <sys/reboot.h>
27
28 #include "manager.h"
29 #include "unit.h"
30 #include "service.h"
31 #include "load-fragment.h"
32 #include "load-dropin.h"
33 #include "log.h"
34 #include "strv.h"
35 #include "unit-name.h"
36 #include "unit-printf.h"
37 #include "dbus-service.h"
38 #include "special.h"
39 #include "bus-errors.h"
40 #include "exit-status.h"
41 #include "def.h"
42 #include "path-util.h"
43 #include "util.h"
44 #include "utf8.h"
45 #include "env-util.h"
46 #include "fileio.h"
47
48 #ifdef HAVE_SYSV_COMPAT
49
50 #define DEFAULT_SYSV_TIMEOUT_USEC (5*USEC_PER_MINUTE)
51
52 typedef enum RunlevelType {
53 RUNLEVEL_UP,
54 RUNLEVEL_DOWN
55 } RunlevelType;
56
57 static const struct {
58 const char *path;
59 const char *target;
60 const RunlevelType type;
61 } rcnd_table[] = {
62 /* Standard SysV runlevels for start-up */
63 { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
64 { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
65 { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
66 { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
67 { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
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 must be read before DOWN */
78 };
79
80 #define RUNLEVELS_UP "12345"
81 #endif
82
83 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
84 [SERVICE_DEAD] = UNIT_INACTIVE,
85 [SERVICE_START_PRE] = UNIT_ACTIVATING,
86 [SERVICE_START] = UNIT_ACTIVATING,
87 [SERVICE_START_POST] = UNIT_ACTIVATING,
88 [SERVICE_RUNNING] = UNIT_ACTIVE,
89 [SERVICE_EXITED] = UNIT_ACTIVE,
90 [SERVICE_RELOAD] = UNIT_RELOADING,
91 [SERVICE_STOP] = UNIT_DEACTIVATING,
92 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
93 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
94 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
95 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
96 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
97 [SERVICE_FAILED] = UNIT_FAILED,
98 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
99 };
100
101 /* For Type=idle we never want to delay any other jobs, hence we
102 * consider idle jobs active as soon as we start working on them */
103 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
104 [SERVICE_DEAD] = UNIT_INACTIVE,
105 [SERVICE_START_PRE] = UNIT_ACTIVE,
106 [SERVICE_START] = UNIT_ACTIVE,
107 [SERVICE_START_POST] = UNIT_ACTIVE,
108 [SERVICE_RUNNING] = UNIT_ACTIVE,
109 [SERVICE_EXITED] = UNIT_ACTIVE,
110 [SERVICE_RELOAD] = UNIT_RELOADING,
111 [SERVICE_STOP] = UNIT_DEACTIVATING,
112 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
113 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
114 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
115 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
116 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
117 [SERVICE_FAILED] = UNIT_FAILED,
118 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
119 };
120
121 static void service_init(Unit *u) {
122 Service *s = SERVICE(u);
123
124 assert(u);
125 assert(u->load_state == UNIT_STUB);
126
127 s->timeout_start_usec = DEFAULT_TIMEOUT_USEC;
128 s->timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
129 s->restart_usec = DEFAULT_RESTART_USEC;
130 s->type = _SERVICE_TYPE_INVALID;
131
132 watch_init(&s->watchdog_watch);
133 watch_init(&s->timer_watch);
134
135 #ifdef HAVE_SYSV_COMPAT
136 s->sysv_start_priority = -1;
137 s->sysv_start_priority_from_rcnd = -1;
138 #endif
139 s->socket_fd = -1;
140 s->guess_main_pid = true;
141
142 exec_context_init(&s->exec_context);
143 kill_context_init(&s->kill_context);
144
145 RATELIMIT_INIT(s->start_limit, 10*USEC_PER_SEC, 5);
146
147 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
148 }
149
150 static void service_unwatch_control_pid(Service *s) {
151 assert(s);
152
153 if (s->control_pid <= 0)
154 return;
155
156 unit_unwatch_pid(UNIT(s), s->control_pid);
157 s->control_pid = 0;
158 }
159
160 static void service_unwatch_main_pid(Service *s) {
161 assert(s);
162
163 if (s->main_pid <= 0)
164 return;
165
166 unit_unwatch_pid(UNIT(s), s->main_pid);
167 s->main_pid = 0;
168 }
169
170 static void service_unwatch_pid_file(Service *s) {
171 if (!s->pid_file_pathspec)
172 return;
173
174 log_debug_unit(UNIT(s)->id, "Stopping watch for %s's PID file %s",
175 UNIT(s)->id, s->pid_file_pathspec->path);
176 path_spec_unwatch(s->pid_file_pathspec, UNIT(s));
177 path_spec_done(s->pid_file_pathspec);
178 free(s->pid_file_pathspec);
179 s->pid_file_pathspec = NULL;
180 }
181
182 static int service_set_main_pid(Service *s, pid_t pid) {
183 pid_t ppid;
184
185 assert(s);
186
187 if (pid <= 1)
188 return -EINVAL;
189
190 if (pid == getpid())
191 return -EINVAL;
192
193 s->main_pid = pid;
194 s->main_pid_known = true;
195
196 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
197 log_warning_unit(UNIT(s)->id,
198 "%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
199 UNIT(s)->id, (unsigned long) pid);
200
201 s->main_pid_alien = true;
202 } else
203 s->main_pid_alien = false;
204
205 exec_status_start(&s->main_exec_status, pid);
206
207 return 0;
208 }
209
210 static void service_close_socket_fd(Service *s) {
211 assert(s);
212
213 if (s->socket_fd < 0)
214 return;
215
216 close_nointr_nofail(s->socket_fd);
217 s->socket_fd = -1;
218 }
219
220 static void service_connection_unref(Service *s) {
221 assert(s);
222
223 if (!UNIT_DEREF(s->accept_socket))
224 return;
225
226 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
227 unit_ref_unset(&s->accept_socket);
228 }
229
230 static void service_stop_watchdog(Service *s) {
231 assert(s);
232
233 unit_unwatch_timer(UNIT(s), &s->watchdog_watch);
234 s->watchdog_timestamp.realtime = 0;
235 s->watchdog_timestamp.monotonic = 0;
236 }
237
238 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart);
239
240 static void service_handle_watchdog(Service *s) {
241 usec_t offset;
242 int r;
243
244 assert(s);
245
246 if (s->watchdog_usec == 0)
247 return;
248
249 offset = now(CLOCK_MONOTONIC) - s->watchdog_timestamp.monotonic;
250 if (offset >= s->watchdog_usec) {
251 log_error_unit(UNIT(s)->id, "%s watchdog timeout!", UNIT(s)->id);
252 service_enter_dead(s, SERVICE_FAILURE_WATCHDOG, true);
253 return;
254 }
255
256 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->watchdog_usec - offset, &s->watchdog_watch);
257 if (r < 0)
258 log_warning_unit(UNIT(s)->id,
259 "%s failed to install watchdog timer: %s",
260 UNIT(s)->id, strerror(-r));
261 }
262
263 static void service_reset_watchdog(Service *s) {
264 assert(s);
265
266 dual_timestamp_get(&s->watchdog_timestamp);
267 service_handle_watchdog(s);
268 }
269
270 static void service_done(Unit *u) {
271 Service *s = SERVICE(u);
272
273 assert(s);
274
275 free(s->pid_file);
276 s->pid_file = NULL;
277
278 #ifdef HAVE_SYSV_COMPAT
279 free(s->sysv_runlevels);
280 s->sysv_runlevels = NULL;
281 #endif
282
283 free(s->status_text);
284 s->status_text = NULL;
285
286 exec_context_done(&s->exec_context);
287 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
288 s->control_command = NULL;
289 s->main_command = NULL;
290
291 set_free(s->restart_ignore_status.code);
292 s->restart_ignore_status.code = NULL;
293 set_free(s->restart_ignore_status.signal);
294 s->restart_ignore_status.signal = NULL;
295
296 set_free(s->success_status.code);
297 s->success_status.code = NULL;
298 set_free(s->success_status.signal);
299 s->success_status.signal = NULL;
300
301 /* This will leak a process, but at least no memory or any of
302 * our resources */
303 service_unwatch_main_pid(s);
304 service_unwatch_control_pid(s);
305 service_unwatch_pid_file(s);
306
307 if (s->bus_name) {
308 unit_unwatch_bus_name(u, s->bus_name);
309 free(s->bus_name);
310 s->bus_name = NULL;
311 }
312
313 service_close_socket_fd(s);
314 service_connection_unref(s);
315
316 unit_ref_unset(&s->accept_socket);
317
318 service_stop_watchdog(s);
319
320 unit_unwatch_timer(u, &s->timer_watch);
321 }
322
323 #ifdef HAVE_SYSV_COMPAT
324 static char *sysv_translate_name(const char *name) {
325 char *r;
326
327 r = new(char, strlen(name) + sizeof(".service"));
328 if (!r)
329 return NULL;
330
331 if (endswith(name, ".sh"))
332 /* Drop .sh suffix */
333 strcpy(stpcpy(r, name) - 3, ".service");
334 if (startswith(name, "rc."))
335 /* Drop rc. prefix */
336 strcpy(stpcpy(r, name + 3), ".service");
337 else
338 /* Normal init script name */
339 strcpy(stpcpy(r, name), ".service");
340
341 return r;
342 }
343
344 static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
345
346 /* We silently ignore the $ prefix here. According to the LSB
347 * spec it simply indicates whether something is a
348 * standardized name or a distribution-specific one. Since we
349 * just follow what already exists and do not introduce new
350 * uses or names we don't care who introduced a new name. */
351
352 static const char * const table[] = {
353 /* LSB defined facilities */
354 "local_fs", NULL,
355 "network", SPECIAL_NETWORK_TARGET,
356 "named", SPECIAL_NSS_LOOKUP_TARGET,
357 "portmap", SPECIAL_RPCBIND_TARGET,
358 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
359 "syslog", NULL,
360 "time", SPECIAL_TIME_SYNC_TARGET,
361 };
362
363 unsigned i;
364 char *r;
365 const char *n;
366
367 assert(name);
368 assert(_r);
369
370 n = *name == '$' ? name + 1 : name;
371
372 for (i = 0; i < ELEMENTSOF(table); i += 2) {
373
374 if (!streq(table[i], n))
375 continue;
376
377 if (!table[i+1])
378 return 0;
379
380 r = strdup(table[i+1]);
381 if (!r)
382 return log_oom();
383
384 goto finish;
385 }
386
387 /* If we don't know this name, fallback heuristics to figure
388 * out whether something is a target or a service alias. */
389
390 if (*name == '$') {
391 if (!unit_prefix_is_valid(n))
392 return -EINVAL;
393
394 /* Facilities starting with $ are most likely targets */
395 r = unit_name_build(n, NULL, ".target");
396 } else if (filename && streq(name, filename))
397 /* Names equaling the file name of the services are redundant */
398 return 0;
399 else
400 /* Everything else we assume to be normal service names */
401 r = sysv_translate_name(n);
402
403 if (!r)
404 return -ENOMEM;
405
406 finish:
407 *_r = r;
408
409 return 1;
410 }
411
412 static int sysv_fix_order(Service *s) {
413 Unit *other;
414 int r;
415
416 assert(s);
417
418 if (s->sysv_start_priority < 0)
419 return 0;
420
421 /* For each pair of services where at least one lacks a LSB
422 * header, we use the start priority value to order things. */
423
424 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
425 Service *t;
426 UnitDependency d;
427 bool special_s, special_t;
428
429 t = SERVICE(other);
430
431 if (s == t)
432 continue;
433
434 if (UNIT(t)->load_state != UNIT_LOADED)
435 continue;
436
437 if (t->sysv_start_priority < 0)
438 continue;
439
440 /* If both units have modern headers we don't care
441 * about the priorities */
442 if ((UNIT(s)->fragment_path || s->sysv_has_lsb) &&
443 (UNIT(t)->fragment_path || t->sysv_has_lsb))
444 continue;
445
446 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
447 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
448
449 if (special_t && !special_s)
450 d = UNIT_AFTER;
451 else if (special_s && !special_t)
452 d = UNIT_BEFORE;
453 else if (t->sysv_start_priority < s->sysv_start_priority)
454 d = UNIT_AFTER;
455 else if (t->sysv_start_priority > s->sysv_start_priority)
456 d = UNIT_BEFORE;
457 else
458 continue;
459
460 /* FIXME: Maybe we should compare the name here lexicographically? */
461
462 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
463 return r;
464 }
465
466 return 0;
467 }
468
469 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
470 ExecCommand *c;
471
472 if (!(c = new0(ExecCommand, 1)))
473 return NULL;
474
475 if (!(c->path = strdup(path))) {
476 free(c);
477 return NULL;
478 }
479
480 if (!(c->argv = strv_new(path, arg1, NULL))) {
481 free(c->path);
482 free(c);
483 return NULL;
484 }
485
486 return c;
487 }
488
489 static int sysv_exec_commands(Service *s, const bool supports_reload) {
490 ExecCommand *c;
491
492 assert(s);
493 assert(s->is_sysv);
494 assert(UNIT(s)->source_path);
495
496 c = exec_command_new(UNIT(s)->source_path, "start");
497 if (!c)
498 return -ENOMEM;
499 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
500
501 c = exec_command_new(UNIT(s)->source_path, "stop");
502 if (!c)
503 return -ENOMEM;
504 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
505
506 if (supports_reload) {
507 c = exec_command_new(UNIT(s)->source_path, "reload");
508 if (!c)
509 return -ENOMEM;
510 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
511 }
512
513 return 0;
514 }
515
516 static bool usage_contains_reload(const char *line) {
517 return (strcasestr(line, "{reload|") ||
518 strcasestr(line, "{reload}") ||
519 strcasestr(line, "{reload\"") ||
520 strcasestr(line, "|reload|") ||
521 strcasestr(line, "|reload}") ||
522 strcasestr(line, "|reload\""));
523 }
524
525 static int service_load_sysv_path(Service *s, const char *path) {
526 FILE *f;
527 Unit *u;
528 unsigned line = 0;
529 int r;
530 enum {
531 NORMAL,
532 DESCRIPTION,
533 LSB,
534 LSB_DESCRIPTION,
535 USAGE_CONTINUATION
536 } state = NORMAL;
537 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
538 struct stat st;
539 bool supports_reload = false;
540
541 assert(s);
542 assert(path);
543
544 u = UNIT(s);
545
546 f = fopen(path, "re");
547 if (!f) {
548 r = errno == ENOENT ? 0 : -errno;
549 goto finish;
550 }
551
552 if (fstat(fileno(f), &st) < 0) {
553 r = -errno;
554 goto finish;
555 }
556
557 free(u->source_path);
558 u->source_path = strdup(path);
559 if (!u->source_path) {
560 r = -ENOMEM;
561 goto finish;
562 }
563 u->source_mtime = timespec_load(&st.st_mtim);
564
565 if (null_or_empty(&st)) {
566 u->load_state = UNIT_MASKED;
567 r = 0;
568 goto finish;
569 }
570
571 s->is_sysv = true;
572
573 while (!feof(f)) {
574 char l[LINE_MAX], *t;
575
576 if (!fgets(l, sizeof(l), f)) {
577 if (feof(f))
578 break;
579
580 r = -errno;
581 log_error_unit(u->id,
582 "Failed to read configuration file '%s': %s",
583 path, strerror(-r));
584 goto finish;
585 }
586
587 line++;
588
589 t = strstrip(l);
590 if (*t != '#') {
591 /* Try to figure out whether this init script supports
592 * the reload operation. This heuristic looks for
593 * "Usage" lines which include the reload option. */
594 if ( state == USAGE_CONTINUATION ||
595 (state == NORMAL && strcasestr(t, "usage"))) {
596 if (usage_contains_reload(t)) {
597 supports_reload = true;
598 state = NORMAL;
599 } else if (t[strlen(t)-1] == '\\')
600 state = USAGE_CONTINUATION;
601 else
602 state = NORMAL;
603 }
604
605 continue;
606 }
607
608 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
609 state = LSB;
610 s->sysv_has_lsb = true;
611 continue;
612 }
613
614 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
615 state = NORMAL;
616 continue;
617 }
618
619 t++;
620 t += strspn(t, WHITESPACE);
621
622 if (state == NORMAL) {
623
624 /* Try to parse Red Hat style chkconfig headers */
625
626 if (startswith_no_case(t, "chkconfig:")) {
627 int start_priority;
628 char runlevels[16], *k;
629
630 state = NORMAL;
631
632 if (sscanf(t+10, "%15s %i %*i",
633 runlevels,
634 &start_priority) != 2) {
635
636 log_warning_unit(u->id,
637 "[%s:%u] Failed to parse chkconfig line. Ignoring.",
638 path, line);
639 continue;
640 }
641
642 /* A start priority gathered from the
643 * symlink farms is preferred over the
644 * data from the LSB header. */
645 if (start_priority < 0 || start_priority > 99)
646 log_warning_unit(u->id,
647 "[%s:%u] Start priority out of range. Ignoring.",
648 path, line);
649 else
650 s->sysv_start_priority = start_priority;
651
652 char_array_0(runlevels);
653 k = delete_chars(runlevels, WHITESPACE "-");
654
655 if (k[0]) {
656 char *d;
657
658 if (!(d = strdup(k))) {
659 r = -ENOMEM;
660 goto finish;
661 }
662
663 free(s->sysv_runlevels);
664 s->sysv_runlevels = d;
665 }
666
667 } else if (startswith_no_case(t, "description:")) {
668
669 size_t k = strlen(t);
670 char *d;
671 const char *j;
672
673 if (t[k-1] == '\\') {
674 state = DESCRIPTION;
675 t[k-1] = 0;
676 }
677
678 if ((j = strstrip(t+12)) && *j) {
679 if (!(d = strdup(j))) {
680 r = -ENOMEM;
681 goto finish;
682 }
683 } else
684 d = NULL;
685
686 free(chkconfig_description);
687 chkconfig_description = d;
688
689 } else if (startswith_no_case(t, "pidfile:")) {
690
691 char *fn;
692
693 state = NORMAL;
694
695 fn = strstrip(t+8);
696 if (!path_is_absolute(fn)) {
697 log_warning_unit(u->id,
698 "[%s:%u] PID file not absolute. Ignoring.",
699 path, line);
700 continue;
701 }
702
703 if (!(fn = strdup(fn))) {
704 r = -ENOMEM;
705 goto finish;
706 }
707
708 free(s->pid_file);
709 s->pid_file = fn;
710 }
711
712 } else if (state == DESCRIPTION) {
713
714 /* Try to parse Red Hat style description
715 * continuation */
716
717 size_t k = strlen(t);
718 char *j;
719
720 if (t[k-1] == '\\')
721 t[k-1] = 0;
722 else
723 state = NORMAL;
724
725 if ((j = strstrip(t)) && *j) {
726 char *d = NULL;
727
728 if (chkconfig_description)
729 d = strjoin(chkconfig_description, " ", j, NULL);
730 else
731 d = strdup(j);
732
733 if (!d) {
734 r = -ENOMEM;
735 goto finish;
736 }
737
738 free(chkconfig_description);
739 chkconfig_description = d;
740 }
741
742 } else if (state == LSB || state == LSB_DESCRIPTION) {
743
744 if (startswith_no_case(t, "Provides:")) {
745 char *i, *w;
746 size_t z;
747
748 state = LSB;
749
750 FOREACH_WORD_QUOTED(w, z, t+9, i) {
751 char *n, *m;
752
753 if (!(n = strndup(w, z))) {
754 r = -ENOMEM;
755 goto finish;
756 }
757
758 r = sysv_translate_facility(n, path_get_file_name(path), &m);
759 free(n);
760
761 if (r < 0)
762 goto finish;
763
764 if (r == 0)
765 continue;
766
767 if (unit_name_to_type(m) == UNIT_SERVICE)
768 r = unit_add_name(u, m);
769 else
770 /* NB: SysV targets
771 * which are provided
772 * by a service are
773 * pulled in by the
774 * services, as an
775 * indication that the
776 * generic service is
777 * now available. This
778 * is strictly
779 * one-way. The
780 * targets do NOT pull
781 * in the SysV
782 * services! */
783 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
784
785 if (r < 0)
786 log_error_unit(u->id,
787 "[%s:%u] Failed to add LSB Provides name %s, ignoring: %s",
788 path, line, m, strerror(-r));
789
790 free(m);
791 }
792
793 } else if (startswith_no_case(t, "Required-Start:") ||
794 startswith_no_case(t, "Should-Start:") ||
795 startswith_no_case(t, "X-Start-Before:") ||
796 startswith_no_case(t, "X-Start-After:")) {
797 char *i, *w;
798 size_t z;
799
800 state = LSB;
801
802 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
803 char *n, *m;
804
805 if (!(n = strndup(w, z))) {
806 r = -ENOMEM;
807 goto finish;
808 }
809
810 r = sysv_translate_facility(n, path_get_file_name(path), &m);
811 if (r < 0) {
812 log_error_unit(u->id,
813 "[%s:%u] Failed to translate LSB dependency %s, ignoring: %s",
814 path, line, n, strerror(-r));
815 free(n);
816 continue;
817 }
818
819 free(n);
820
821 if (r == 0)
822 continue;
823
824 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
825
826 if (r < 0)
827 log_error_unit(u->id, "[%s:%u] Failed to add dependency on %s, ignoring: %s",
828 path, line, m, strerror(-r));
829
830 free(m);
831 }
832 } else if (startswith_no_case(t, "Default-Start:")) {
833 char *k, *d;
834
835 state = LSB;
836
837 k = delete_chars(t+14, WHITESPACE "-");
838
839 if (k[0] != 0) {
840 if (!(d = strdup(k))) {
841 r = -ENOMEM;
842 goto finish;
843 }
844
845 free(s->sysv_runlevels);
846 s->sysv_runlevels = d;
847 }
848
849 } else if (startswith_no_case(t, "Description:")) {
850 char *d, *j;
851
852 state = LSB_DESCRIPTION;
853
854 if ((j = strstrip(t+12)) && *j) {
855 if (!(d = strdup(j))) {
856 r = -ENOMEM;
857 goto finish;
858 }
859 } else
860 d = NULL;
861
862 free(long_description);
863 long_description = d;
864
865 } else if (startswith_no_case(t, "Short-Description:")) {
866 char *d, *j;
867
868 state = LSB;
869
870 if ((j = strstrip(t+18)) && *j) {
871 if (!(d = strdup(j))) {
872 r = -ENOMEM;
873 goto finish;
874 }
875 } else
876 d = NULL;
877
878 free(short_description);
879 short_description = d;
880
881 } else if (state == LSB_DESCRIPTION) {
882
883 if (startswith(l, "#\t") || startswith(l, "# ")) {
884 char *j;
885
886 if ((j = strstrip(t)) && *j) {
887 char *d = NULL;
888
889 if (long_description)
890 d = strjoin(long_description, " ", t, NULL);
891 else
892 d = strdup(j);
893
894 if (!d) {
895 r = -ENOMEM;
896 goto finish;
897 }
898
899 free(long_description);
900 long_description = d;
901 }
902
903 } else
904 state = LSB;
905 }
906 }
907 }
908
909 if ((r = sysv_exec_commands(s, supports_reload)) < 0)
910 goto finish;
911
912 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
913 /* If there a runlevels configured for this service
914 * but none of the standard ones, then we assume this
915 * is some special kind of service (which might be
916 * needed for early boot) and don't create any links
917 * to it. */
918
919 UNIT(s)->default_dependencies = false;
920
921 /* Don't timeout special services during boot (like fsck) */
922 s->timeout_start_usec = 0;
923 s->timeout_stop_usec = 0;
924 } else {
925 s->timeout_start_usec = DEFAULT_SYSV_TIMEOUT_USEC;
926 s->timeout_stop_usec = DEFAULT_SYSV_TIMEOUT_USEC;
927 }
928
929 /* Special setting for all SysV services */
930 s->type = SERVICE_FORKING;
931 s->remain_after_exit = !s->pid_file;
932 s->guess_main_pid = false;
933 s->restart = SERVICE_RESTART_NO;
934 s->exec_context.ignore_sigpipe = false;
935 s->kill_context.kill_mode = KILL_PROCESS;
936
937 /* We use the long description only if
938 * no short description is set. */
939
940 if (short_description)
941 description = short_description;
942 else if (chkconfig_description)
943 description = chkconfig_description;
944 else if (long_description)
945 description = long_description;
946 else
947 description = NULL;
948
949 if (description) {
950 char *d;
951
952 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
953 r = -ENOMEM;
954 goto finish;
955 }
956
957 u->description = d;
958 }
959
960 /* The priority that has been set in /etc/rcN.d/ hierarchies
961 * takes precedence over what is stored as default in the LSB
962 * header */
963 if (s->sysv_start_priority_from_rcnd >= 0)
964 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
965
966 u->load_state = UNIT_LOADED;
967 r = 0;
968
969 finish:
970
971 if (f)
972 fclose(f);
973
974 free(short_description);
975 free(long_description);
976 free(chkconfig_description);
977
978 return r;
979 }
980
981 static int service_load_sysv_name(Service *s, const char *name) {
982 char **p;
983
984 assert(s);
985 assert(name);
986
987 /* For SysV services we strip the rc.* and *.sh
988 * prefixes/suffixes. */
989 if (startswith(name, "rc.") ||
990 endswith(name, ".sh.service"))
991 return -ENOENT;
992
993 STRV_FOREACH(p, UNIT(s)->manager->lookup_paths.sysvinit_path) {
994 char *path;
995 int r;
996
997 path = strjoin(*p, "/", name, NULL);
998 if (!path)
999 return -ENOMEM;
1000
1001 assert(endswith(path, ".service"));
1002 path[strlen(path)-8] = 0;
1003
1004 r = service_load_sysv_path(s, path);
1005
1006 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
1007 /* Try *.sh source'able init scripts */
1008 strcat(path, ".sh");
1009 r = service_load_sysv_path(s, path);
1010 }
1011 free(path);
1012
1013 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
1014 /* Try rc.* init scripts */
1015
1016 path = strjoin(*p, "/rc.", name, NULL);
1017 if (!path)
1018 return -ENOMEM;
1019
1020 /* Drop .service suffix */
1021 path[strlen(path)-8] = 0;
1022 r = service_load_sysv_path(s, path);
1023 free(path);
1024 }
1025
1026 if (r < 0)
1027 return r;
1028
1029 if (UNIT(s)->load_state != UNIT_STUB)
1030 break;
1031 }
1032
1033 return 0;
1034 }
1035
1036 static int service_load_sysv(Service *s) {
1037 const char *t;
1038 Iterator i;
1039 int r;
1040
1041 assert(s);
1042
1043 /* Load service data from SysV init scripts, preferably with
1044 * LSB headers ... */
1045
1046 if (strv_isempty(UNIT(s)->manager->lookup_paths.sysvinit_path))
1047 return 0;
1048
1049 if ((t = UNIT(s)->id))
1050 if ((r = service_load_sysv_name(s, t)) < 0)
1051 return r;
1052
1053 if (UNIT(s)->load_state == UNIT_STUB)
1054 SET_FOREACH(t, UNIT(s)->names, i) {
1055 if (t == UNIT(s)->id)
1056 continue;
1057
1058 if ((r = service_load_sysv_name(s, t)) < 0)
1059 return r;
1060
1061 if (UNIT(s)->load_state != UNIT_STUB)
1062 break;
1063 }
1064
1065 return 0;
1066 }
1067 #endif
1068
1069 static int fsck_fix_order(Service *s) {
1070 Unit *other;
1071 int r;
1072
1073 assert(s);
1074
1075 if (s->fsck_passno <= 0)
1076 return 0;
1077
1078 /* For each pair of services where both have an fsck priority
1079 * we order things based on it. */
1080
1081 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
1082 Service *t;
1083 UnitDependency d;
1084
1085 t = SERVICE(other);
1086
1087 if (s == t)
1088 continue;
1089
1090 if (UNIT(t)->load_state != UNIT_LOADED)
1091 continue;
1092
1093 if (t->fsck_passno <= 0)
1094 continue;
1095
1096 if (t->fsck_passno < s->fsck_passno)
1097 d = UNIT_AFTER;
1098 else if (t->fsck_passno > s->fsck_passno)
1099 d = UNIT_BEFORE;
1100 else
1101 continue;
1102
1103 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
1104 return r;
1105 }
1106
1107 return 0;
1108 }
1109
1110 static int service_verify(Service *s) {
1111 assert(s);
1112
1113 if (UNIT(s)->load_state != UNIT_LOADED)
1114 return 0;
1115
1116 if (!s->exec_command[SERVICE_EXEC_START]) {
1117 log_error_unit(UNIT(s)->id,
1118 "%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
1119 return -EINVAL;
1120 }
1121
1122 if (s->type != SERVICE_ONESHOT &&
1123 s->exec_command[SERVICE_EXEC_START]->command_next) {
1124 log_error_unit(UNIT(s)->id,
1125 "%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1126 return -EINVAL;
1127 }
1128
1129 if (s->type == SERVICE_DBUS && !s->bus_name) {
1130 log_error_unit(UNIT(s)->id,
1131 "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
1132 return -EINVAL;
1133 }
1134
1135 if (s->bus_name && s->type != SERVICE_DBUS)
1136 log_warning_unit(UNIT(s)->id,
1137 "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
1138
1139 if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
1140 log_error_unit(UNIT(s)->id,
1141 "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
1142 return -EINVAL;
1143 }
1144
1145 return 0;
1146 }
1147
1148 static int service_add_default_dependencies(Service *s) {
1149 int r;
1150
1151 assert(s);
1152
1153 /* Add a number of automatic dependencies useful for the
1154 * majority of services. */
1155
1156 /* First, pull in base system */
1157 if (UNIT(s)->manager->running_as == SYSTEMD_SYSTEM) {
1158
1159 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
1160 return r;
1161
1162 } else if (UNIT(s)->manager->running_as == SYSTEMD_USER) {
1163
1164 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
1165 return r;
1166 }
1167
1168 /* Second, activate normal shutdown */
1169 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
1170 }
1171
1172 static void service_fix_output(Service *s) {
1173 assert(s);
1174
1175 /* If nothing has been explicitly configured, patch default
1176 * output in. If input is socket/tty we avoid this however,
1177 * since in that case we want output to default to the same
1178 * place as we read input from. */
1179
1180 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1181 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1182 s->exec_context.std_input == EXEC_INPUT_NULL)
1183 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
1184
1185 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1186 s->exec_context.std_input == EXEC_INPUT_NULL)
1187 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
1188 }
1189
1190 static int service_load(Unit *u) {
1191 int r;
1192 Service *s = SERVICE(u);
1193
1194 assert(s);
1195
1196 /* Load a .service file */
1197 if ((r = unit_load_fragment(u)) < 0)
1198 return r;
1199
1200 #ifdef HAVE_SYSV_COMPAT
1201 /* Load a classic init script as a fallback, if we couldn't find anything */
1202 if (u->load_state == UNIT_STUB)
1203 if ((r = service_load_sysv(s)) < 0)
1204 return r;
1205 #endif
1206
1207 /* Still nothing found? Then let's give up */
1208 if (u->load_state == UNIT_STUB)
1209 return -ENOENT;
1210
1211 /* We were able to load something, then let's add in the
1212 * dropin directories. */
1213 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
1214 return r;
1215
1216 /* This is a new unit? Then let's add in some extras */
1217 if (u->load_state == UNIT_LOADED) {
1218 if (s->type == _SERVICE_TYPE_INVALID)
1219 s->type = s->bus_name ? SERVICE_DBUS : SERVICE_SIMPLE;
1220
1221 /* Oneshot services have disabled start timeout by default */
1222 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
1223 s->timeout_start_usec = 0;
1224
1225 service_fix_output(s);
1226
1227 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
1228 return r;
1229
1230 if ((r = unit_add_default_cgroups(u)) < 0)
1231 return r;
1232
1233 #ifdef HAVE_SYSV_COMPAT
1234 if ((r = sysv_fix_order(s)) < 0)
1235 return r;
1236 #endif
1237
1238 if ((r = fsck_fix_order(s)) < 0)
1239 return r;
1240
1241 if (s->bus_name)
1242 if ((r = unit_watch_bus_name(u, s->bus_name)) < 0)
1243 return r;
1244
1245 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1246 s->notify_access = NOTIFY_MAIN;
1247
1248 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
1249 s->notify_access = NOTIFY_MAIN;
1250
1251 if (s->type == SERVICE_DBUS || s->bus_name)
1252 if ((r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true)) < 0)
1253 return r;
1254
1255 if (UNIT(s)->default_dependencies)
1256 if ((r = service_add_default_dependencies(s)) < 0)
1257 return r;
1258
1259 r = unit_exec_context_defaults(u, &s->exec_context);
1260 if (r < 0)
1261 return r;
1262 }
1263
1264 return service_verify(s);
1265 }
1266
1267 static void service_dump(Unit *u, FILE *f, const char *prefix) {
1268
1269 ServiceExecCommand c;
1270 Service *s = SERVICE(u);
1271 const char *prefix2;
1272 char *p2;
1273
1274 assert(s);
1275
1276 p2 = strappend(prefix, "\t");
1277 prefix2 = p2 ? p2 : prefix;
1278
1279 fprintf(f,
1280 "%sService State: %s\n"
1281 "%sResult: %s\n"
1282 "%sReload Result: %s\n"
1283 "%sPermissionsStartOnly: %s\n"
1284 "%sRootDirectoryStartOnly: %s\n"
1285 "%sRemainAfterExit: %s\n"
1286 "%sGuessMainPID: %s\n"
1287 "%sType: %s\n"
1288 "%sRestart: %s\n"
1289 "%sNotifyAccess: %s\n",
1290 prefix, service_state_to_string(s->state),
1291 prefix, service_result_to_string(s->result),
1292 prefix, service_result_to_string(s->reload_result),
1293 prefix, yes_no(s->permissions_start_only),
1294 prefix, yes_no(s->root_directory_start_only),
1295 prefix, yes_no(s->remain_after_exit),
1296 prefix, yes_no(s->guess_main_pid),
1297 prefix, service_type_to_string(s->type),
1298 prefix, service_restart_to_string(s->restart),
1299 prefix, notify_access_to_string(s->notify_access));
1300
1301 if (s->control_pid > 0)
1302 fprintf(f,
1303 "%sControl PID: %lu\n",
1304 prefix, (unsigned long) s->control_pid);
1305
1306 if (s->main_pid > 0)
1307 fprintf(f,
1308 "%sMain PID: %lu\n"
1309 "%sMain PID Known: %s\n"
1310 "%sMain PID Alien: %s\n",
1311 prefix, (unsigned long) s->main_pid,
1312 prefix, yes_no(s->main_pid_known),
1313 prefix, yes_no(s->main_pid_alien));
1314
1315 if (s->pid_file)
1316 fprintf(f,
1317 "%sPIDFile: %s\n",
1318 prefix, s->pid_file);
1319
1320 if (s->bus_name)
1321 fprintf(f,
1322 "%sBusName: %s\n"
1323 "%sBus Name Good: %s\n",
1324 prefix, s->bus_name,
1325 prefix, yes_no(s->bus_name_good));
1326
1327 kill_context_dump(&s->kill_context, f, prefix);
1328 exec_context_dump(&s->exec_context, f, prefix);
1329
1330 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
1331
1332 if (!s->exec_command[c])
1333 continue;
1334
1335 fprintf(f, "%s-> %s:\n",
1336 prefix, service_exec_command_to_string(c));
1337
1338 exec_command_dump_list(s->exec_command[c], f, prefix2);
1339 }
1340
1341 #ifdef HAVE_SYSV_COMPAT
1342 if (s->is_sysv)
1343 fprintf(f,
1344 "%sSysV Init Script has LSB Header: %s\n"
1345 "%sSysVEnabled: %s\n",
1346 prefix, yes_no(s->sysv_has_lsb),
1347 prefix, yes_no(s->sysv_enabled));
1348
1349 if (s->sysv_start_priority >= 0)
1350 fprintf(f,
1351 "%sSysVStartPriority: %i\n",
1352 prefix, s->sysv_start_priority);
1353
1354 if (s->sysv_runlevels)
1355 fprintf(f, "%sSysVRunLevels: %s\n",
1356 prefix, s->sysv_runlevels);
1357 #endif
1358
1359 if (s->fsck_passno > 0)
1360 fprintf(f,
1361 "%sFsckPassNo: %i\n",
1362 prefix, s->fsck_passno);
1363
1364 if (s->status_text)
1365 fprintf(f, "%sStatus Text: %s\n",
1366 prefix, s->status_text);
1367
1368 free(p2);
1369 }
1370
1371 static int service_load_pid_file(Service *s, bool may_warn) {
1372 char *k;
1373 int r;
1374 pid_t pid;
1375
1376 assert(s);
1377
1378 if (!s->pid_file)
1379 return -ENOENT;
1380
1381 if ((r = read_one_line_file(s->pid_file, &k)) < 0) {
1382 if (may_warn)
1383 log_info_unit(UNIT(s)->id,
1384 "PID file %s not readable (yet?) after %s.",
1385 s->pid_file, service_state_to_string(s->state));
1386 return r;
1387 }
1388
1389 r = parse_pid(k, &pid);
1390 free(k);
1391
1392 if (r < 0)
1393 return r;
1394
1395 if (kill(pid, 0) < 0 && errno != EPERM) {
1396 if (may_warn)
1397 log_info_unit(UNIT(s)->id,
1398 "PID %lu read from file %s does not exist.",
1399 (unsigned long) pid, s->pid_file);
1400 return -ESRCH;
1401 }
1402
1403 if (s->main_pid_known) {
1404 if (pid == s->main_pid)
1405 return 0;
1406
1407 log_debug_unit(UNIT(s)->id,
1408 "Main PID changing: %lu -> %lu",
1409 (unsigned long) s->main_pid, (unsigned long) pid);
1410 service_unwatch_main_pid(s);
1411 s->main_pid_known = false;
1412 } else
1413 log_debug_unit(UNIT(s)->id,
1414 "Main PID loaded: %lu", (unsigned long) pid);
1415
1416 if ((r = service_set_main_pid(s, pid)) < 0)
1417 return r;
1418
1419 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1420 /* FIXME: we need to do something here */
1421 return r;
1422
1423 return 0;
1424 }
1425
1426 static int service_search_main_pid(Service *s) {
1427 pid_t pid;
1428 int r;
1429
1430 assert(s);
1431
1432 /* If we know it anyway, don't ever fallback to unreliable
1433 * heuristics */
1434 if (s->main_pid_known)
1435 return 0;
1436
1437 if (!s->guess_main_pid)
1438 return 0;
1439
1440 assert(s->main_pid <= 0);
1441
1442 if ((pid = cgroup_bonding_search_main_pid_list(UNIT(s)->cgroup_bondings)) <= 0)
1443 return -ENOENT;
1444
1445 log_debug_unit(UNIT(s)->id,
1446 "Main PID guessed: %lu", (unsigned long) pid);
1447 if ((r = service_set_main_pid(s, pid)) < 0)
1448 return r;
1449
1450 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1451 /* FIXME: we need to do something here */
1452 return r;
1453
1454 return 0;
1455 }
1456
1457 static void service_notify_sockets_dead(Service *s, bool failed_permanent) {
1458 Iterator i;
1459 Unit *u;
1460
1461 assert(s);
1462
1463 /* Notifies all our sockets when we die */
1464
1465 if (s->socket_fd >= 0)
1466 return;
1467
1468 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i)
1469 if (u->type == UNIT_SOCKET)
1470 socket_notify_service_dead(SOCKET(u), failed_permanent);
1471
1472 return;
1473 }
1474
1475 static void service_set_state(Service *s, ServiceState state) {
1476 ServiceState old_state;
1477 const UnitActiveState *table;
1478 assert(s);
1479
1480 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1481
1482 old_state = s->state;
1483 s->state = state;
1484
1485 service_unwatch_pid_file(s);
1486
1487 if (state != SERVICE_START_PRE &&
1488 state != SERVICE_START &&
1489 state != SERVICE_START_POST &&
1490 state != SERVICE_RELOAD &&
1491 state != SERVICE_STOP &&
1492 state != SERVICE_STOP_SIGTERM &&
1493 state != SERVICE_STOP_SIGKILL &&
1494 state != SERVICE_STOP_POST &&
1495 state != SERVICE_FINAL_SIGTERM &&
1496 state != SERVICE_FINAL_SIGKILL &&
1497 state != SERVICE_AUTO_RESTART)
1498 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1499
1500 if (state != SERVICE_START &&
1501 state != SERVICE_START_POST &&
1502 state != SERVICE_RUNNING &&
1503 state != SERVICE_RELOAD &&
1504 state != SERVICE_STOP &&
1505 state != SERVICE_STOP_SIGTERM &&
1506 state != SERVICE_STOP_SIGKILL) {
1507 service_unwatch_main_pid(s);
1508 s->main_command = NULL;
1509 }
1510
1511 if (state != SERVICE_START_PRE &&
1512 state != SERVICE_START &&
1513 state != SERVICE_START_POST &&
1514 state != SERVICE_RELOAD &&
1515 state != SERVICE_STOP &&
1516 state != SERVICE_STOP_SIGTERM &&
1517 state != SERVICE_STOP_SIGKILL &&
1518 state != SERVICE_STOP_POST &&
1519 state != SERVICE_FINAL_SIGTERM &&
1520 state != SERVICE_FINAL_SIGKILL) {
1521 service_unwatch_control_pid(s);
1522 s->control_command = NULL;
1523 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1524 }
1525
1526 if (state == SERVICE_FAILED)
1527 service_notify_sockets_dead(s, s->result == SERVICE_FAILURE_START_LIMIT);
1528
1529 if (state == SERVICE_DEAD ||
1530 state == SERVICE_STOP ||
1531 state == SERVICE_STOP_SIGTERM ||
1532 state == SERVICE_STOP_SIGKILL ||
1533 state == SERVICE_STOP_POST ||
1534 state == SERVICE_FINAL_SIGTERM ||
1535 state == SERVICE_FINAL_SIGKILL ||
1536 state == SERVICE_AUTO_RESTART)
1537 service_notify_sockets_dead(s, false);
1538
1539 if (state != SERVICE_START_PRE &&
1540 state != SERVICE_START &&
1541 state != SERVICE_START_POST &&
1542 state != SERVICE_RUNNING &&
1543 state != SERVICE_RELOAD &&
1544 state != SERVICE_STOP &&
1545 state != SERVICE_STOP_SIGTERM &&
1546 state != SERVICE_STOP_SIGKILL &&
1547 state != SERVICE_STOP_POST &&
1548 state != SERVICE_FINAL_SIGTERM &&
1549 state != SERVICE_FINAL_SIGKILL &&
1550 !(state == SERVICE_DEAD && UNIT(s)->job)) {
1551 service_close_socket_fd(s);
1552 service_connection_unref(s);
1553 }
1554
1555 if (state == SERVICE_STOP || state == SERVICE_STOP_SIGTERM)
1556 service_stop_watchdog(s);
1557
1558 /* For the inactive states unit_notify() will trim the cgroup,
1559 * but for exit we have to do that ourselves... */
1560 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
1561 cgroup_bonding_trim_list(UNIT(s)->cgroup_bondings, true);
1562
1563 if (old_state != state)
1564 log_debug_unit(UNIT(s)->id,
1565 "%s changed %s -> %s", UNIT(s)->id,
1566 service_state_to_string(old_state),
1567 service_state_to_string(state));
1568
1569 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
1570 s->reload_result = SERVICE_SUCCESS;
1571 }
1572
1573 static int service_coldplug(Unit *u) {
1574 Service *s = SERVICE(u);
1575 int r;
1576
1577 assert(s);
1578 assert(s->state == SERVICE_DEAD);
1579
1580 if (s->deserialized_state != s->state) {
1581
1582 if (s->deserialized_state == SERVICE_START_PRE ||
1583 s->deserialized_state == SERVICE_START ||
1584 s->deserialized_state == SERVICE_START_POST ||
1585 s->deserialized_state == SERVICE_RELOAD ||
1586 s->deserialized_state == SERVICE_STOP ||
1587 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1588 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1589 s->deserialized_state == SERVICE_STOP_POST ||
1590 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1591 s->deserialized_state == SERVICE_FINAL_SIGKILL ||
1592 s->deserialized_state == SERVICE_AUTO_RESTART) {
1593 if (s->deserialized_state == SERVICE_AUTO_RESTART || s->timeout_start_usec > 0) {
1594 usec_t k;
1595
1596 k = s->deserialized_state == SERVICE_AUTO_RESTART ? s->restart_usec : s->timeout_start_usec;
1597
1598 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, k, &s->timer_watch);
1599 if (r < 0)
1600 return r;
1601 }
1602 }
1603
1604 if ((s->deserialized_state == SERVICE_START &&
1605 (s->type == SERVICE_FORKING ||
1606 s->type == SERVICE_DBUS ||
1607 s->type == SERVICE_ONESHOT ||
1608 s->type == SERVICE_NOTIFY)) ||
1609 s->deserialized_state == SERVICE_START_POST ||
1610 s->deserialized_state == SERVICE_RUNNING ||
1611 s->deserialized_state == SERVICE_RELOAD ||
1612 s->deserialized_state == SERVICE_STOP ||
1613 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1614 s->deserialized_state == SERVICE_STOP_SIGKILL)
1615 if (s->main_pid > 0)
1616 if ((r = unit_watch_pid(UNIT(s), s->main_pid)) < 0)
1617 return r;
1618
1619 if (s->deserialized_state == SERVICE_START_PRE ||
1620 s->deserialized_state == SERVICE_START ||
1621 s->deserialized_state == SERVICE_START_POST ||
1622 s->deserialized_state == SERVICE_RELOAD ||
1623 s->deserialized_state == SERVICE_STOP ||
1624 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1625 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1626 s->deserialized_state == SERVICE_STOP_POST ||
1627 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1628 s->deserialized_state == SERVICE_FINAL_SIGKILL)
1629 if (s->control_pid > 0)
1630 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
1631 return r;
1632
1633 if (s->deserialized_state == SERVICE_START_POST ||
1634 s->deserialized_state == SERVICE_RUNNING)
1635 service_handle_watchdog(s);
1636
1637 service_set_state(s, s->deserialized_state);
1638 }
1639 return 0;
1640 }
1641
1642 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1643 Iterator i;
1644 int r;
1645 int *rfds = NULL;
1646 unsigned rn_fds = 0;
1647 Unit *u;
1648
1649 assert(s);
1650 assert(fds);
1651 assert(n_fds);
1652
1653 if (s->socket_fd >= 0)
1654 return 0;
1655
1656 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1657 int *cfds;
1658 unsigned cn_fds;
1659 Socket *sock;
1660
1661 if (u->type != UNIT_SOCKET)
1662 continue;
1663
1664 sock = SOCKET(u);
1665
1666 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
1667 goto fail;
1668
1669 if (!cfds)
1670 continue;
1671
1672 if (!rfds) {
1673 rfds = cfds;
1674 rn_fds = cn_fds;
1675 } else {
1676 int *t;
1677
1678 if (!(t = new(int, rn_fds+cn_fds))) {
1679 free(cfds);
1680 r = -ENOMEM;
1681 goto fail;
1682 }
1683
1684 memcpy(t, rfds, rn_fds * sizeof(int));
1685 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
1686 free(rfds);
1687 free(cfds);
1688
1689 rfds = t;
1690 rn_fds = rn_fds+cn_fds;
1691 }
1692 }
1693
1694 *fds = rfds;
1695 *n_fds = rn_fds;
1696
1697 return 0;
1698
1699 fail:
1700 free(rfds);
1701
1702 return r;
1703 }
1704
1705 static int service_spawn(
1706 Service *s,
1707 ExecCommand *c,
1708 bool timeout,
1709 bool pass_fds,
1710 bool apply_permissions,
1711 bool apply_chroot,
1712 bool apply_tty_stdin,
1713 bool set_notify_socket,
1714 bool is_control,
1715 pid_t *_pid) {
1716
1717 pid_t pid;
1718 int r;
1719 int *fds = NULL, *fdsbuf = NULL;
1720 unsigned n_fds = 0, n_env = 0;
1721 char **argv = NULL, **final_env = NULL, **our_env = NULL;
1722
1723 assert(s);
1724 assert(c);
1725 assert(_pid);
1726
1727 if (pass_fds ||
1728 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1729 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1730 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1731
1732 if (s->socket_fd >= 0) {
1733 fds = &s->socket_fd;
1734 n_fds = 1;
1735 } else {
1736 if ((r = service_collect_fds(s, &fdsbuf, &n_fds)) < 0)
1737 goto fail;
1738
1739 fds = fdsbuf;
1740 }
1741 }
1742
1743 if (timeout && s->timeout_start_usec) {
1744 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->timeout_start_usec, &s->timer_watch);
1745 if (r < 0)
1746 goto fail;
1747 } else
1748 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1749
1750 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
1751 r = -ENOMEM;
1752 goto fail;
1753 }
1754
1755 our_env = new0(char*, 5);
1756 if (!our_env) {
1757 r = -ENOMEM;
1758 goto fail;
1759 }
1760
1761 if (set_notify_socket)
1762 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1763 r = -ENOMEM;
1764 goto fail;
1765 }
1766
1767 if (s->main_pid > 0)
1768 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
1769 r = -ENOMEM;
1770 goto fail;
1771 }
1772
1773 if (s->watchdog_usec > 0)
1774 if (asprintf(our_env + n_env++, "WATCHDOG_USEC=%llu", (unsigned long long) s->watchdog_usec) < 0) {
1775 r = -ENOMEM;
1776 goto fail;
1777 }
1778
1779 if (s->meta.manager->running_as != SYSTEMD_SYSTEM)
1780 if (asprintf(our_env + n_env++, "MANAGERPID=%lu", (unsigned long) getpid()) < 0) {
1781 r = -ENOMEM;
1782 goto fail;
1783 }
1784
1785 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1786 if (!final_env) {
1787 r = -ENOMEM;
1788 goto fail;
1789 }
1790
1791 r = exec_spawn(c,
1792 argv,
1793 &s->exec_context,
1794 fds, n_fds,
1795 final_env,
1796 apply_permissions,
1797 apply_chroot,
1798 apply_tty_stdin,
1799 UNIT(s)->manager->confirm_spawn,
1800 UNIT(s)->cgroup_bondings,
1801 UNIT(s)->cgroup_attributes,
1802 is_control ? "control" : NULL,
1803 UNIT(s)->id,
1804 s->type == SERVICE_IDLE ? UNIT(s)->manager->idle_pipe : NULL,
1805 &pid);
1806
1807 if (r < 0)
1808 goto fail;
1809
1810 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1811 /* FIXME: we need to do something here */
1812 goto fail;
1813
1814 free(fdsbuf);
1815 strv_free(argv);
1816 strv_free(our_env);
1817 strv_free(final_env);
1818
1819 *_pid = pid;
1820
1821 return 0;
1822
1823 fail:
1824 free(fdsbuf);
1825 strv_free(argv);
1826 strv_free(our_env);
1827 strv_free(final_env);
1828
1829 if (timeout)
1830 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1831
1832 return r;
1833 }
1834
1835 static int main_pid_good(Service *s) {
1836 assert(s);
1837
1838 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1839 * don't know */
1840
1841 /* If we know the pid file, then lets just check if it is
1842 * still valid */
1843 if (s->main_pid_known) {
1844
1845 /* If it's an alien child let's check if it is still
1846 * alive ... */
1847 if (s->main_pid_alien)
1848 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1849
1850 /* .. otherwise assume we'll get a SIGCHLD for it,
1851 * which we really should wait for to collect exit
1852 * status and code */
1853 return s->main_pid > 0;
1854 }
1855
1856 /* We don't know the pid */
1857 return -EAGAIN;
1858 }
1859
1860 static int control_pid_good(Service *s) {
1861 assert(s);
1862
1863 return s->control_pid > 0;
1864 }
1865
1866 static int cgroup_good(Service *s) {
1867 int r;
1868
1869 assert(s);
1870
1871 if ((r = cgroup_bonding_is_empty_list(UNIT(s)->cgroup_bondings)) < 0)
1872 return r;
1873
1874 return !r;
1875 }
1876
1877 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1878 int r;
1879 assert(s);
1880
1881 if (f != SERVICE_SUCCESS)
1882 s->result = f;
1883
1884 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1885
1886 if (allow_restart &&
1887 !s->forbid_restart &&
1888 (s->restart == SERVICE_RESTART_ALWAYS ||
1889 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1890 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1891 (s->restart == SERVICE_RESTART_ON_ABORT && (s->result == SERVICE_FAILURE_SIGNAL ||
1892 s->result == SERVICE_FAILURE_CORE_DUMP))) &&
1893 (s->result != SERVICE_FAILURE_EXIT_CODE ||
1894 !set_contains(s->restart_ignore_status.code, INT_TO_PTR(s->main_exec_status.status))) &&
1895 (s->result != SERVICE_FAILURE_SIGNAL ||
1896 !set_contains(s->restart_ignore_status.signal, INT_TO_PTR(s->main_exec_status.status)))
1897 ) {
1898
1899 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->restart_usec, &s->timer_watch);
1900 if (r < 0)
1901 goto fail;
1902
1903 service_set_state(s, SERVICE_AUTO_RESTART);
1904 }
1905
1906 s->forbid_restart = false;
1907
1908 return;
1909
1910 fail:
1911 log_warning_unit(UNIT(s)->id,
1912 "%s failed to run install restart timer: %s",
1913 UNIT(s)->id, strerror(-r));
1914 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1915 }
1916
1917 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
1918
1919 static void service_enter_stop_post(Service *s, ServiceResult f) {
1920 int r;
1921 assert(s);
1922
1923 if (f != SERVICE_SUCCESS)
1924 s->result = f;
1925
1926 service_unwatch_control_pid(s);
1927
1928 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST])) {
1929 s->control_command_id = SERVICE_EXEC_STOP_POST;
1930
1931 r = service_spawn(s,
1932 s->control_command,
1933 true,
1934 false,
1935 !s->permissions_start_only,
1936 !s->root_directory_start_only,
1937 true,
1938 false,
1939 true,
1940 &s->control_pid);
1941 if (r < 0)
1942 goto fail;
1943
1944
1945 service_set_state(s, SERVICE_STOP_POST);
1946 } else
1947 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1948
1949 return;
1950
1951 fail:
1952 log_warning_unit(UNIT(s)->id,
1953 "%s failed to run 'stop-post' task: %s",
1954 UNIT(s)->id, strerror(-r));
1955 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1956 }
1957
1958 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1959 int r;
1960
1961 assert(s);
1962
1963 if (f != SERVICE_SUCCESS)
1964 s->result = f;
1965
1966 r = unit_kill_context(
1967 UNIT(s),
1968 &s->kill_context,
1969 state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM,
1970 s->main_pid,
1971 s->control_pid,
1972 s->main_pid_alien);
1973 if (r < 0)
1974 goto fail;
1975
1976 if (r > 0) {
1977 if (s->timeout_stop_usec > 0) {
1978 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->timeout_stop_usec, &s->timer_watch);
1979 if (r < 0)
1980 goto fail;
1981 }
1982
1983 service_set_state(s, state);
1984 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1985 service_enter_stop_post(s, SERVICE_SUCCESS);
1986 else
1987 service_enter_dead(s, SERVICE_SUCCESS, true);
1988
1989 return;
1990
1991 fail:
1992 log_warning_unit(UNIT(s)->id,
1993 "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1994
1995 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1996 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1997 else
1998 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1999 }
2000
2001 static void service_enter_stop(Service *s, ServiceResult f) {
2002 int r;
2003
2004 assert(s);
2005
2006 if (f != SERVICE_SUCCESS)
2007 s->result = f;
2008
2009 service_unwatch_control_pid(s);
2010
2011 if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP])) {
2012 s->control_command_id = SERVICE_EXEC_STOP;
2013
2014 r = service_spawn(s,
2015 s->control_command,
2016 true,
2017 false,
2018 !s->permissions_start_only,
2019 !s->root_directory_start_only,
2020 false,
2021 false,
2022 true,
2023 &s->control_pid);
2024 if (r < 0)
2025 goto fail;
2026
2027 service_set_state(s, SERVICE_STOP);
2028 } else
2029 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2030
2031 return;
2032
2033 fail:
2034 log_warning_unit(UNIT(s)->id,
2035 "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
2036 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2037 }
2038
2039 static void service_enter_running(Service *s, ServiceResult f) {
2040 int main_pid_ok, cgroup_ok;
2041 assert(s);
2042
2043 if (f != SERVICE_SUCCESS)
2044 s->result = f;
2045
2046 main_pid_ok = main_pid_good(s);
2047 cgroup_ok = cgroup_good(s);
2048
2049 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
2050 (s->bus_name_good || s->type != SERVICE_DBUS))
2051 service_set_state(s, SERVICE_RUNNING);
2052 else if (s->remain_after_exit)
2053 service_set_state(s, SERVICE_EXITED);
2054 else
2055 service_enter_stop(s, SERVICE_SUCCESS);
2056 }
2057
2058 static void service_enter_start_post(Service *s) {
2059 int r;
2060 assert(s);
2061
2062 service_unwatch_control_pid(s);
2063
2064 if (s->watchdog_usec > 0)
2065 service_reset_watchdog(s);
2066
2067 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST])) {
2068 s->control_command_id = SERVICE_EXEC_START_POST;
2069
2070 r = service_spawn(s,
2071 s->control_command,
2072 true,
2073 false,
2074 !s->permissions_start_only,
2075 !s->root_directory_start_only,
2076 false,
2077 false,
2078 true,
2079 &s->control_pid);
2080 if (r < 0)
2081 goto fail;
2082
2083 service_set_state(s, SERVICE_START_POST);
2084 } else
2085 service_enter_running(s, SERVICE_SUCCESS);
2086
2087 return;
2088
2089 fail:
2090 log_warning_unit(UNIT(s)->id,
2091 "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
2092 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2093 }
2094
2095 static void service_enter_start(Service *s) {
2096 pid_t pid;
2097 int r;
2098 ExecCommand *c;
2099
2100 assert(s);
2101
2102 assert(s->exec_command[SERVICE_EXEC_START]);
2103 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
2104
2105 if (s->type == SERVICE_FORKING)
2106 service_unwatch_control_pid(s);
2107 else
2108 service_unwatch_main_pid(s);
2109
2110 /* We want to ensure that nobody leaks processes from
2111 * START_PRE here, so let's go on a killing spree, People
2112 * should not spawn long running processes from START_PRE. */
2113 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, true, NULL, "control");
2114
2115 if (s->type == SERVICE_FORKING) {
2116 s->control_command_id = SERVICE_EXEC_START;
2117 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2118
2119 s->main_command = NULL;
2120 } else {
2121 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2122 s->control_command = NULL;
2123
2124 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2125 }
2126
2127 r = service_spawn(s,
2128 c,
2129 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS || s->type == SERVICE_NOTIFY || s->type == SERVICE_ONESHOT,
2130 true,
2131 true,
2132 true,
2133 true,
2134 s->notify_access != NOTIFY_NONE,
2135 false,
2136 &pid);
2137 if (r < 0)
2138 goto fail;
2139
2140 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
2141 /* For simple services we immediately start
2142 * the START_POST binaries. */
2143
2144 service_set_main_pid(s, pid);
2145 service_enter_start_post(s);
2146
2147 } else if (s->type == SERVICE_FORKING) {
2148
2149 /* For forking services we wait until the start
2150 * process exited. */
2151
2152 s->control_pid = pid;
2153 service_set_state(s, SERVICE_START);
2154
2155 } else if (s->type == SERVICE_ONESHOT ||
2156 s->type == SERVICE_DBUS ||
2157 s->type == SERVICE_NOTIFY) {
2158
2159 /* For oneshot services we wait until the start
2160 * process exited, too, but it is our main process. */
2161
2162 /* For D-Bus services we know the main pid right away,
2163 * but wait for the bus name to appear on the
2164 * bus. Notify services are similar. */
2165
2166 service_set_main_pid(s, pid);
2167 service_set_state(s, SERVICE_START);
2168 } else
2169 assert_not_reached("Unknown service type");
2170
2171 return;
2172
2173 fail:
2174 log_warning_unit(UNIT(s)->id,
2175 "%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
2176 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2177 }
2178
2179 static void service_enter_start_pre(Service *s) {
2180 int r;
2181
2182 assert(s);
2183
2184 service_unwatch_control_pid(s);
2185
2186 if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE])) {
2187
2188 /* Before we start anything, let's clear up what might
2189 * be left from previous runs. */
2190 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, true, NULL, "control");
2191
2192 s->control_command_id = SERVICE_EXEC_START_PRE;
2193
2194 r = service_spawn(s,
2195 s->control_command,
2196 true,
2197 false,
2198 !s->permissions_start_only,
2199 !s->root_directory_start_only,
2200 true,
2201 false,
2202 true,
2203 &s->control_pid);
2204 if (r < 0)
2205 goto fail;
2206
2207 service_set_state(s, SERVICE_START_PRE);
2208 } else
2209 service_enter_start(s);
2210
2211 return;
2212
2213 fail:
2214 log_warning_unit(UNIT(s)->id,
2215 "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
2216 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2217 }
2218
2219 static void service_enter_restart(Service *s) {
2220 int r;
2221 DBusError error;
2222
2223 assert(s);
2224 dbus_error_init(&error);
2225
2226 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
2227 /* Don't restart things if we are going down anyway */
2228 log_info_unit(UNIT(s)->id,
2229 "Stop job pending for unit, delaying automatic restart.");
2230
2231 r = unit_watch_timer(UNIT(s), CLOCK_MONOTONIC, true, s->restart_usec, &s->timer_watch);
2232 if (r < 0)
2233 goto fail;
2234
2235 return;
2236 }
2237
2238 /* Any units that are bound to this service must also be
2239 * restarted. We use JOB_RESTART (instead of the more obvious
2240 * JOB_START) here so that those dependency jobs will be added
2241 * as well. */
2242 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
2243 if (r < 0)
2244 goto fail;
2245
2246 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
2247 * it will be canceled as part of the service_stop() call that
2248 * is executed as part of JOB_RESTART. */
2249
2250 log_debug_unit(UNIT(s)->id,
2251 "%s scheduled restart job.", UNIT(s)->id);
2252 return;
2253
2254 fail:
2255 log_warning_unit(UNIT(s)->id,
2256 "%s failed to schedule restart job: %s",
2257 UNIT(s)->id, bus_error(&error, -r));
2258 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
2259
2260 dbus_error_free(&error);
2261 }
2262
2263 static void service_enter_reload(Service *s) {
2264 int r;
2265
2266 assert(s);
2267
2268 service_unwatch_control_pid(s);
2269
2270 if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD])) {
2271 s->control_command_id = SERVICE_EXEC_RELOAD;
2272
2273 r = service_spawn(s,
2274 s->control_command,
2275 true,
2276 false,
2277 !s->permissions_start_only,
2278 !s->root_directory_start_only,
2279 false,
2280 false,
2281 true,
2282 &s->control_pid);
2283 if (r < 0)
2284 goto fail;
2285
2286 service_set_state(s, SERVICE_RELOAD);
2287 } else
2288 service_enter_running(s, SERVICE_SUCCESS);
2289
2290 return;
2291
2292 fail:
2293 log_warning_unit(UNIT(s)->id,
2294 "%s failed to run 'reload' task: %s",
2295 UNIT(s)->id, strerror(-r));
2296 s->reload_result = SERVICE_FAILURE_RESOURCES;
2297 service_enter_running(s, SERVICE_SUCCESS);
2298 }
2299
2300 static void service_run_next_control(Service *s) {
2301 int r;
2302
2303 assert(s);
2304 assert(s->control_command);
2305 assert(s->control_command->command_next);
2306
2307 assert(s->control_command_id != SERVICE_EXEC_START);
2308
2309 s->control_command = s->control_command->command_next;
2310 service_unwatch_control_pid(s);
2311
2312 r = service_spawn(s,
2313 s->control_command,
2314 true,
2315 false,
2316 !s->permissions_start_only,
2317 !s->root_directory_start_only,
2318 s->control_command_id == SERVICE_EXEC_START_PRE ||
2319 s->control_command_id == SERVICE_EXEC_STOP_POST,
2320 false,
2321 true,
2322 &s->control_pid);
2323 if (r < 0)
2324 goto fail;
2325
2326 return;
2327
2328 fail:
2329 log_warning_unit(UNIT(s)->id,
2330 "%s failed to run next control task: %s",
2331 UNIT(s)->id, strerror(-r));
2332
2333 if (s->state == SERVICE_START_PRE)
2334 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2335 else if (s->state == SERVICE_STOP)
2336 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2337 else if (s->state == SERVICE_STOP_POST)
2338 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2339 else if (s->state == SERVICE_RELOAD) {
2340 s->reload_result = SERVICE_FAILURE_RESOURCES;
2341 service_enter_running(s, SERVICE_SUCCESS);
2342 } else
2343 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2344 }
2345
2346 static void service_run_next_main(Service *s) {
2347 pid_t pid;
2348 int r;
2349
2350 assert(s);
2351 assert(s->main_command);
2352 assert(s->main_command->command_next);
2353 assert(s->type == SERVICE_ONESHOT);
2354
2355 s->main_command = s->main_command->command_next;
2356 service_unwatch_main_pid(s);
2357
2358 r = service_spawn(s,
2359 s->main_command,
2360 true,
2361 true,
2362 true,
2363 true,
2364 true,
2365 s->notify_access != NOTIFY_NONE,
2366 false,
2367 &pid);
2368 if (r < 0)
2369 goto fail;
2370
2371 service_set_main_pid(s, pid);
2372
2373 return;
2374
2375 fail:
2376 log_warning_unit(UNIT(s)->id,
2377 "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
2378 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2379 }
2380
2381 static int service_start_limit_test(Service *s) {
2382 assert(s);
2383
2384 if (ratelimit_test(&s->start_limit))
2385 return 0;
2386
2387 switch (s->start_limit_action) {
2388
2389 case SERVICE_START_LIMIT_NONE:
2390 log_warning_unit(UNIT(s)->id,
2391 "%s start request repeated too quickly, refusing to start.",
2392 UNIT(s)->id);
2393 break;
2394
2395 case SERVICE_START_LIMIT_REBOOT: {
2396 DBusError error;
2397 int r;
2398
2399 dbus_error_init(&error);
2400
2401 log_warning_unit(UNIT(s)->id,
2402 "%s start request repeated too quickly, rebooting.", UNIT(s)->id);
2403
2404 r = manager_add_job_by_name(UNIT(s)->manager, JOB_START, SPECIAL_REBOOT_TARGET, JOB_REPLACE, true, &error, NULL);
2405 if (r < 0) {
2406 log_error_unit(UNIT(s)->id,
2407 "Failed to reboot: %s.", bus_error(&error, r));
2408 dbus_error_free(&error);
2409 }
2410
2411 break;
2412 }
2413
2414 case SERVICE_START_LIMIT_REBOOT_FORCE:
2415 log_warning_unit(UNIT(s)->id,
2416 "%s start request repeated too quickly, forcibly rebooting.", UNIT(s)->id);
2417 UNIT(s)->manager->exit_code = MANAGER_REBOOT;
2418 break;
2419
2420 case SERVICE_START_LIMIT_REBOOT_IMMEDIATE:
2421 log_warning_unit(UNIT(s)->id,
2422 "%s start request repeated too quickly, rebooting immediately.", UNIT(s)->id);
2423 sync();
2424 reboot(RB_AUTOBOOT);
2425 break;
2426
2427 default:
2428 log_error_unit(UNIT(s)->id,
2429 "start limit action=%i", s->start_limit_action);
2430 assert_not_reached("Unknown StartLimitAction.");
2431 }
2432
2433 return -ECANCELED;
2434 }
2435
2436 static int service_start(Unit *u) {
2437 Service *s = SERVICE(u);
2438 int r;
2439
2440 assert(s);
2441
2442 /* We cannot fulfill this request right now, try again later
2443 * please! */
2444 if (s->state == SERVICE_STOP ||
2445 s->state == SERVICE_STOP_SIGTERM ||
2446 s->state == SERVICE_STOP_SIGKILL ||
2447 s->state == SERVICE_STOP_POST ||
2448 s->state == SERVICE_FINAL_SIGTERM ||
2449 s->state == SERVICE_FINAL_SIGKILL)
2450 return -EAGAIN;
2451
2452 /* Already on it! */
2453 if (s->state == SERVICE_START_PRE ||
2454 s->state == SERVICE_START ||
2455 s->state == SERVICE_START_POST)
2456 return 0;
2457
2458 /* A service that will be restarted must be stopped first to
2459 * trigger BindsTo and/or OnFailure dependencies. If a user
2460 * does not want to wait for the holdoff time to elapse, the
2461 * service should be manually restarted, not started. We
2462 * simply return EAGAIN here, so that any start jobs stay
2463 * queued, and assume that the auto restart timer will
2464 * eventually trigger the restart. */
2465 if (s->state == SERVICE_AUTO_RESTART)
2466 return -EAGAIN;
2467
2468 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
2469
2470 /* Make sure we don't enter a busy loop of some kind. */
2471 r = service_start_limit_test(s);
2472 if (r < 0) {
2473 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
2474 return r;
2475 }
2476
2477 s->result = SERVICE_SUCCESS;
2478 s->reload_result = SERVICE_SUCCESS;
2479 s->main_pid_known = false;
2480 s->main_pid_alien = false;
2481 s->forbid_restart = false;
2482
2483 service_enter_start_pre(s);
2484 return 0;
2485 }
2486
2487 static int service_stop(Unit *u) {
2488 Service *s = SERVICE(u);
2489
2490 assert(s);
2491
2492 /* Don't create restart jobs from here. */
2493 s->forbid_restart = true;
2494
2495 /* Already on it */
2496 if (s->state == SERVICE_STOP ||
2497 s->state == SERVICE_STOP_SIGTERM ||
2498 s->state == SERVICE_STOP_SIGKILL ||
2499 s->state == SERVICE_STOP_POST ||
2500 s->state == SERVICE_FINAL_SIGTERM ||
2501 s->state == SERVICE_FINAL_SIGKILL)
2502 return 0;
2503
2504 /* A restart will be scheduled or is in progress. */
2505 if (s->state == SERVICE_AUTO_RESTART) {
2506 service_set_state(s, SERVICE_DEAD);
2507 return 0;
2508 }
2509
2510 /* If there's already something running we go directly into
2511 * kill mode. */
2512 if (s->state == SERVICE_START_PRE ||
2513 s->state == SERVICE_START ||
2514 s->state == SERVICE_START_POST ||
2515 s->state == SERVICE_RELOAD) {
2516 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2517 return 0;
2518 }
2519
2520 assert(s->state == SERVICE_RUNNING ||
2521 s->state == SERVICE_EXITED);
2522
2523 service_enter_stop(s, SERVICE_SUCCESS);
2524 return 0;
2525 }
2526
2527 static int service_reload(Unit *u) {
2528 Service *s = SERVICE(u);
2529
2530 assert(s);
2531
2532 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2533
2534 service_enter_reload(s);
2535 return 0;
2536 }
2537
2538 static bool service_can_reload(Unit *u) {
2539 Service *s = SERVICE(u);
2540
2541 assert(s);
2542
2543 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2544 }
2545
2546 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2547 Service *s = SERVICE(u);
2548
2549 assert(u);
2550 assert(f);
2551 assert(fds);
2552
2553 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2554 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2555 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2556
2557 if (s->control_pid > 0)
2558 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
2559
2560 if (s->main_pid_known && s->main_pid > 0)
2561 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
2562
2563 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2564
2565 if (s->status_text)
2566 unit_serialize_item(u, f, "status-text", s->status_text);
2567
2568 /* FIXME: There's a minor uncleanliness here: if there are
2569 * multiple commands attached here, we will start from the
2570 * first one again */
2571 if (s->control_command_id >= 0)
2572 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2573
2574 if (s->socket_fd >= 0) {
2575 int copy;
2576
2577 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2578 return copy;
2579
2580 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2581 }
2582
2583 if (s->main_exec_status.pid > 0) {
2584 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu", (unsigned long) s->main_exec_status.pid);
2585 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2586 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2587
2588 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2589 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2590 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2591 }
2592 }
2593 if (dual_timestamp_is_set(&s->watchdog_timestamp))
2594 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2595
2596 return 0;
2597 }
2598
2599 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2600 Service *s = SERVICE(u);
2601
2602 assert(u);
2603 assert(key);
2604 assert(value);
2605 assert(fds);
2606
2607 if (streq(key, "state")) {
2608 ServiceState state;
2609
2610 if ((state = service_state_from_string(value)) < 0)
2611 log_debug_unit(u->id, "Failed to parse state value %s", value);
2612 else
2613 s->deserialized_state = state;
2614 } else if (streq(key, "result")) {
2615 ServiceResult f;
2616
2617 f = service_result_from_string(value);
2618 if (f < 0)
2619 log_debug_unit(u->id, "Failed to parse result value %s", value);
2620 else if (f != SERVICE_SUCCESS)
2621 s->result = f;
2622
2623 } else if (streq(key, "reload-result")) {
2624 ServiceResult f;
2625
2626 f = service_result_from_string(value);
2627 if (f < 0)
2628 log_debug_unit(u->id, "Failed to parse reload result value %s", value);
2629 else if (f != SERVICE_SUCCESS)
2630 s->reload_result = f;
2631
2632 } else if (streq(key, "control-pid")) {
2633 pid_t pid;
2634
2635 if (parse_pid(value, &pid) < 0)
2636 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
2637 else
2638 s->control_pid = pid;
2639 } else if (streq(key, "main-pid")) {
2640 pid_t pid;
2641
2642 if (parse_pid(value, &pid) < 0)
2643 log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
2644 else
2645 service_set_main_pid(s, (pid_t) pid);
2646 } else if (streq(key, "main-pid-known")) {
2647 int b;
2648
2649 if ((b = parse_boolean(value)) < 0)
2650 log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
2651 else
2652 s->main_pid_known = b;
2653 } else if (streq(key, "status-text")) {
2654 char *t;
2655
2656 if ((t = strdup(value))) {
2657 free(s->status_text);
2658 s->status_text = t;
2659 }
2660
2661 } else if (streq(key, "control-command")) {
2662 ServiceExecCommand id;
2663
2664 if ((id = service_exec_command_from_string(value)) < 0)
2665 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
2666 else {
2667 s->control_command_id = id;
2668 s->control_command = s->exec_command[id];
2669 }
2670 } else if (streq(key, "socket-fd")) {
2671 int fd;
2672
2673 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2674 log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
2675 else {
2676
2677 if (s->socket_fd >= 0)
2678 close_nointr_nofail(s->socket_fd);
2679 s->socket_fd = fdset_remove(fds, fd);
2680 }
2681 } else if (streq(key, "main-exec-status-pid")) {
2682 pid_t pid;
2683
2684 if (parse_pid(value, &pid) < 0)
2685 log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
2686 else
2687 s->main_exec_status.pid = pid;
2688 } else if (streq(key, "main-exec-status-code")) {
2689 int i;
2690
2691 if (safe_atoi(value, &i) < 0)
2692 log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
2693 else
2694 s->main_exec_status.code = i;
2695 } else if (streq(key, "main-exec-status-status")) {
2696 int i;
2697
2698 if (safe_atoi(value, &i) < 0)
2699 log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
2700 else
2701 s->main_exec_status.status = i;
2702 } else if (streq(key, "main-exec-status-start"))
2703 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2704 else if (streq(key, "main-exec-status-exit"))
2705 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2706 else if (streq(key, "watchdog-timestamp"))
2707 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2708 else
2709 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
2710
2711 return 0;
2712 }
2713
2714 static UnitActiveState service_active_state(Unit *u) {
2715 const UnitActiveState *table;
2716
2717 assert(u);
2718
2719 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2720
2721 return table[SERVICE(u)->state];
2722 }
2723
2724 static const char *service_sub_state_to_string(Unit *u) {
2725 assert(u);
2726
2727 return service_state_to_string(SERVICE(u)->state);
2728 }
2729
2730 static bool service_check_gc(Unit *u) {
2731 Service *s = SERVICE(u);
2732
2733 assert(s);
2734
2735 /* Never clean up services that still have a process around,
2736 * even if the service is formally dead. */
2737 if (cgroup_good(s) > 0 ||
2738 main_pid_good(s) > 0 ||
2739 control_pid_good(s) > 0)
2740 return true;
2741
2742 #ifdef HAVE_SYSV_COMPAT
2743 if (s->is_sysv)
2744 return true;
2745 #endif
2746
2747 return false;
2748 }
2749
2750 static bool service_check_snapshot(Unit *u) {
2751 Service *s = SERVICE(u);
2752
2753 assert(s);
2754
2755 return !s->got_socket_fd;
2756 }
2757
2758 static int service_retry_pid_file(Service *s) {
2759 int r;
2760
2761 assert(s->pid_file);
2762 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2763
2764 r = service_load_pid_file(s, false);
2765 if (r < 0)
2766 return r;
2767
2768 service_unwatch_pid_file(s);
2769
2770 service_enter_running(s, SERVICE_SUCCESS);
2771 return 0;
2772 }
2773
2774 static int service_watch_pid_file(Service *s) {
2775 int r;
2776
2777 log_debug_unit(UNIT(s)->id,
2778 "Setting watch for %s's PID file %s",
2779 UNIT(s)->id, s->pid_file_pathspec->path);
2780 r = path_spec_watch(s->pid_file_pathspec, UNIT(s));
2781 if (r < 0)
2782 goto fail;
2783
2784 /* the pidfile might have appeared just before we set the watch */
2785 service_retry_pid_file(s);
2786
2787 return 0;
2788 fail:
2789 log_error_unit(UNIT(s)->id,
2790 "Failed to set a watch for %s's PID file %s: %s",
2791 UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2792 service_unwatch_pid_file(s);
2793 return r;
2794 }
2795
2796 static int service_demand_pid_file(Service *s) {
2797 PathSpec *ps;
2798
2799 assert(s->pid_file);
2800 assert(!s->pid_file_pathspec);
2801
2802 ps = new0(PathSpec, 1);
2803 if (!ps)
2804 return -ENOMEM;
2805
2806 ps->path = strdup(s->pid_file);
2807 if (!ps->path) {
2808 free(ps);
2809 return -ENOMEM;
2810 }
2811
2812 path_kill_slashes(ps->path);
2813
2814 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2815 * keep their PID file open all the time. */
2816 ps->type = PATH_MODIFIED;
2817 ps->inotify_fd = -1;
2818
2819 s->pid_file_pathspec = ps;
2820
2821 return service_watch_pid_file(s);
2822 }
2823
2824 static void service_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
2825 Service *s = SERVICE(u);
2826
2827 assert(s);
2828 assert(fd >= 0);
2829 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2830 assert(s->pid_file_pathspec);
2831 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2832
2833 log_debug_unit(u->id, "inotify event for %s", u->id);
2834
2835 if (path_spec_fd_event(s->pid_file_pathspec, events) < 0)
2836 goto fail;
2837
2838 if (service_retry_pid_file(s) == 0)
2839 return;
2840
2841 if (service_watch_pid_file(s) < 0)
2842 goto fail;
2843
2844 return;
2845 fail:
2846 service_unwatch_pid_file(s);
2847 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2848 }
2849
2850 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2851 Service *s = SERVICE(u);
2852 ServiceResult f;
2853
2854 assert(s);
2855 assert(pid >= 0);
2856
2857 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2858 is_clean_exit_lsb(code, status, &s->success_status))
2859 f = SERVICE_SUCCESS;
2860 else if (code == CLD_EXITED)
2861 f = SERVICE_FAILURE_EXIT_CODE;
2862 else if (code == CLD_KILLED)
2863 f = SERVICE_FAILURE_SIGNAL;
2864 else if (code == CLD_DUMPED)
2865 f = SERVICE_FAILURE_CORE_DUMP;
2866 else
2867 assert_not_reached("Unknown code");
2868
2869 if (s->main_pid == pid) {
2870 /* Forking services may occasionally move to a new PID.
2871 * As long as they update the PID file before exiting the old
2872 * PID, they're fine. */
2873 if (service_load_pid_file(s, false) == 0)
2874 return;
2875
2876 s->main_pid = 0;
2877 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2878
2879 if (s->main_command) {
2880 /* If this is not a forking service than the
2881 * main process got started and hence we copy
2882 * the exit status so that it is recorded both
2883 * as main and as control process exit
2884 * status */
2885
2886 s->main_command->exec_status = s->main_exec_status;
2887
2888 if (s->main_command->ignore)
2889 f = SERVICE_SUCCESS;
2890 } else if (s->exec_command[SERVICE_EXEC_START]) {
2891
2892 /* If this is a forked process, then we should
2893 * ignore the return value if this was
2894 * configured for the starter process */
2895
2896 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2897 f = SERVICE_SUCCESS;
2898 }
2899
2900 log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2901 u->id,
2902 "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
2903 u->id, sigchld_code_to_string(code), status,
2904 strna(code == CLD_EXITED
2905 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2906 : signal_to_string(status)),
2907 "EXIT_CODE=%s", sigchld_code_to_string(code),
2908 "EXIT_STATUS=%i", status,
2909 NULL);
2910
2911 if (f != SERVICE_SUCCESS)
2912 s->result = f;
2913
2914 if (s->main_command &&
2915 s->main_command->command_next &&
2916 f == SERVICE_SUCCESS) {
2917
2918 /* There is another command to *
2919 * execute, so let's do that. */
2920
2921 log_debug_unit(u->id,
2922 "%s running next main command for state %s",
2923 u->id, service_state_to_string(s->state));
2924 service_run_next_main(s);
2925
2926 } else {
2927
2928 /* The service exited, so the service is officially
2929 * gone. */
2930 s->main_command = NULL;
2931
2932 switch (s->state) {
2933
2934 case SERVICE_START_POST:
2935 case SERVICE_RELOAD:
2936 case SERVICE_STOP:
2937 /* Need to wait until the operation is
2938 * done */
2939 break;
2940
2941 case SERVICE_START:
2942 if (s->type == SERVICE_ONESHOT) {
2943 /* This was our main goal, so let's go on */
2944 if (f == SERVICE_SUCCESS)
2945 service_enter_start_post(s);
2946 else
2947 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2948 break;
2949 }
2950
2951 /* Fall through */
2952
2953 case SERVICE_RUNNING:
2954 service_enter_running(s, f);
2955 break;
2956
2957 case SERVICE_STOP_SIGTERM:
2958 case SERVICE_STOP_SIGKILL:
2959
2960 if (!control_pid_good(s))
2961 service_enter_stop_post(s, f);
2962
2963 /* If there is still a control process, wait for that first */
2964 break;
2965
2966 default:
2967 assert_not_reached("Uh, main process died at wrong time.");
2968 }
2969 }
2970
2971 } else if (s->control_pid == pid) {
2972
2973 s->control_pid = 0;
2974
2975 if (s->control_command) {
2976 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2977
2978 if (s->control_command->ignore)
2979 f = SERVICE_SUCCESS;
2980 }
2981
2982 log_full_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
2983 "%s: control process exited, code=%s status=%i",
2984 u->id, sigchld_code_to_string(code), status);
2985
2986 if (f != SERVICE_SUCCESS)
2987 s->result = f;
2988
2989 /* Immediately get rid of the cgroup, so that the
2990 * kernel doesn't delay the cgroup empty messages for
2991 * the service cgroup any longer than necessary */
2992 cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, SIGKILL, true, true, NULL, "control");
2993
2994 if (s->control_command &&
2995 s->control_command->command_next &&
2996 f == SERVICE_SUCCESS) {
2997
2998 /* There is another command to *
2999 * execute, so let's do that. */
3000
3001 log_debug_unit(u->id,
3002 "%s running next control command for state %s",
3003 u->id, service_state_to_string(s->state));
3004 service_run_next_control(s);
3005
3006 } else {
3007 /* No further commands for this step, so let's
3008 * figure out what to do next */
3009
3010 s->control_command = NULL;
3011 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
3012
3013 log_debug_unit(u->id,
3014 "%s got final SIGCHLD for state %s",
3015 u->id, service_state_to_string(s->state));
3016
3017 switch (s->state) {
3018
3019 case SERVICE_START_PRE:
3020 if (f == SERVICE_SUCCESS)
3021 service_enter_start(s);
3022 else
3023 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3024 break;
3025
3026 case SERVICE_START:
3027 if (s->type != SERVICE_FORKING)
3028 /* Maybe spurious event due to a reload that changed the type? */
3029 break;
3030
3031 if (f != SERVICE_SUCCESS) {
3032 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3033 break;
3034 }
3035
3036 if (s->pid_file) {
3037 bool has_start_post;
3038 int r;
3039
3040 /* Let's try to load the pid file here if we can.
3041 * The PID file might actually be created by a START_POST
3042 * script. In that case don't worry if the loading fails. */
3043
3044 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
3045 r = service_load_pid_file(s, !has_start_post);
3046 if (!has_start_post && r < 0) {
3047 r = service_demand_pid_file(s);
3048 if (r < 0 || !cgroup_good(s))
3049 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3050 break;
3051 }
3052 } else
3053 service_search_main_pid(s);
3054
3055 service_enter_start_post(s);
3056 break;
3057
3058 case SERVICE_START_POST:
3059 if (f != SERVICE_SUCCESS) {
3060 service_enter_stop(s, f);
3061 break;
3062 }
3063
3064 if (s->pid_file) {
3065 int r;
3066
3067 r = service_load_pid_file(s, true);
3068 if (r < 0) {
3069 r = service_demand_pid_file(s);
3070 if (r < 0 || !cgroup_good(s))
3071 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3072 break;
3073 }
3074 } else
3075 service_search_main_pid(s);
3076
3077 service_enter_running(s, SERVICE_SUCCESS);
3078 break;
3079
3080 case SERVICE_RELOAD:
3081 if (f == SERVICE_SUCCESS) {
3082 service_load_pid_file(s, true);
3083 service_search_main_pid(s);
3084 }
3085
3086 s->reload_result = f;
3087 service_enter_running(s, SERVICE_SUCCESS);
3088 break;
3089
3090 case SERVICE_STOP:
3091 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3092 break;
3093
3094 case SERVICE_STOP_SIGTERM:
3095 case SERVICE_STOP_SIGKILL:
3096 if (main_pid_good(s) <= 0)
3097 service_enter_stop_post(s, f);
3098
3099 /* If there is still a service
3100 * process around, wait until
3101 * that one quit, too */
3102 break;
3103
3104 case SERVICE_STOP_POST:
3105 case SERVICE_FINAL_SIGTERM:
3106 case SERVICE_FINAL_SIGKILL:
3107 service_enter_dead(s, f, true);
3108 break;
3109
3110 default:
3111 assert_not_reached("Uh, control process died at wrong time.");
3112 }
3113 }
3114 }
3115
3116 /* Notify clients about changed exit status */
3117 unit_add_to_dbus_queue(u);
3118 }
3119
3120 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
3121 Service *s = SERVICE(u);
3122
3123 assert(s);
3124 assert(elapsed == 1);
3125
3126 if (w == &s->watchdog_watch) {
3127 service_handle_watchdog(s);
3128 return;
3129 }
3130
3131 assert(w == &s->timer_watch);
3132
3133 switch (s->state) {
3134
3135 case SERVICE_START_PRE:
3136 case SERVICE_START:
3137 log_warning_unit(u->id,
3138 "%s operation timed out. Terminating.", u->id);
3139 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3140 break;
3141
3142 case SERVICE_START_POST:
3143 log_warning_unit(u->id,
3144 "%s operation timed out. Stopping.", u->id);
3145 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
3146 break;
3147
3148 case SERVICE_RELOAD:
3149 log_warning_unit(u->id,
3150 "%s operation timed out. Stopping.", u->id);
3151 s->reload_result = SERVICE_FAILURE_TIMEOUT;
3152 service_enter_running(s, SERVICE_SUCCESS);
3153 break;
3154
3155 case SERVICE_STOP:
3156 log_warning_unit(u->id,
3157 "%s stopping timed out. Terminating.", u->id);
3158 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3159 break;
3160
3161 case SERVICE_STOP_SIGTERM:
3162 if (s->kill_context.send_sigkill) {
3163 log_warning_unit(u->id,
3164 "%s stopping timed out. Killing.", u->id);
3165 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3166 } else {
3167 log_warning_unit(u->id,
3168 "%s stopping timed out. Skipping SIGKILL.", u->id);
3169 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3170 }
3171
3172 break;
3173
3174 case SERVICE_STOP_SIGKILL:
3175 /* Uh, we sent a SIGKILL and it is still not gone?
3176 * Must be something we cannot kill, so let's just be
3177 * weirded out and continue */
3178
3179 log_warning_unit(u->id,
3180 "%s still around after SIGKILL. Ignoring.", u->id);
3181 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3182 break;
3183
3184 case SERVICE_STOP_POST:
3185 log_warning_unit(u->id,
3186 "%s stopping timed out (2). Terminating.", u->id);
3187 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3188 break;
3189
3190 case SERVICE_FINAL_SIGTERM:
3191 if (s->kill_context.send_sigkill) {
3192 log_warning_unit(u->id,
3193 "%s stopping timed out (2). Killing.", u->id);
3194 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3195 } else {
3196 log_warning_unit(u->id,
3197 "%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.",
3198 u->id);
3199 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3200 }
3201
3202 break;
3203
3204 case SERVICE_FINAL_SIGKILL:
3205 log_warning_unit(u->id,
3206 "%s still around after SIGKILL (2). Entering failed mode.", u->id);
3207 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
3208 break;
3209
3210 case SERVICE_AUTO_RESTART:
3211 log_info_unit(u->id,
3212 "%s holdoff time over, scheduling restart.", u->id);
3213 service_enter_restart(s);
3214 break;
3215
3216 default:
3217 assert_not_reached("Timeout at wrong time.");
3218 }
3219 }
3220
3221 static void service_cgroup_notify_event(Unit *u) {
3222 Service *s = SERVICE(u);
3223
3224 assert(u);
3225
3226 log_debug_unit(u->id,
3227 "%s: cgroup is empty", u->id);
3228
3229 switch (s->state) {
3230
3231 /* Waiting for SIGCHLD is usually more interesting,
3232 * because it includes return codes/signals. Which is
3233 * why we ignore the cgroup events for most cases,
3234 * except when we don't know pid which to expect the
3235 * SIGCHLD for. */
3236
3237 case SERVICE_START:
3238 case SERVICE_START_POST:
3239 /* If we were hoping for the daemon to write its PID file,
3240 * we can give up now. */
3241 if (s->pid_file_pathspec) {
3242 log_warning_unit(u->id,
3243 "%s never wrote its PID file. Failing.", UNIT(s)->id);
3244 service_unwatch_pid_file(s);
3245 if (s->state == SERVICE_START)
3246 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3247 else
3248 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3249 }
3250 break;
3251
3252 case SERVICE_RUNNING:
3253 /* service_enter_running() will figure out what to do */
3254 service_enter_running(s, SERVICE_SUCCESS);
3255 break;
3256
3257 case SERVICE_STOP_SIGTERM:
3258 case SERVICE_STOP_SIGKILL:
3259
3260 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3261 service_enter_stop_post(s, SERVICE_SUCCESS);
3262
3263 break;
3264
3265 case SERVICE_FINAL_SIGTERM:
3266 case SERVICE_FINAL_SIGKILL:
3267 if (main_pid_good(s) <= 0 && !control_pid_good(s))
3268 service_enter_dead(s, SERVICE_SUCCESS, true);
3269
3270 break;
3271
3272 default:
3273 ;
3274 }
3275 }
3276
3277 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
3278 Service *s = SERVICE(u);
3279 const char *e;
3280
3281 assert(u);
3282
3283 if (s->notify_access == NOTIFY_NONE) {
3284 log_warning_unit(u->id,
3285 "%s: Got notification message from PID %lu, but reception is disabled.",
3286 u->id, (unsigned long) pid);
3287 return;
3288 }
3289
3290 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3291 log_warning_unit(u->id,
3292 "%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
3293 u->id, (unsigned long) pid, (unsigned long) s->main_pid);
3294 return;
3295 }
3296
3297 log_debug_unit(u->id,
3298 "%s: Got message", u->id);
3299
3300 /* Interpret MAINPID= */
3301 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3302 (s->state == SERVICE_START ||
3303 s->state == SERVICE_START_POST ||
3304 s->state == SERVICE_RUNNING ||
3305 s->state == SERVICE_RELOAD)) {
3306
3307 if (parse_pid(e + 8, &pid) < 0)
3308 log_warning_unit(u->id,
3309 "Failed to parse notification message %s", e);
3310 else {
3311 log_debug_unit(u->id,
3312 "%s: got %s", u->id, e);
3313 service_set_main_pid(s, pid);
3314 }
3315 }
3316
3317 /* Interpret READY= */
3318 if (s->type == SERVICE_NOTIFY &&
3319 s->state == SERVICE_START &&
3320 strv_find(tags, "READY=1")) {
3321 log_debug_unit(u->id,
3322 "%s: got READY=1", u->id);
3323
3324 service_enter_start_post(s);
3325 }
3326
3327 /* Interpret STATUS= */
3328 e = strv_find_prefix(tags, "STATUS=");
3329 if (e) {
3330 char *t;
3331
3332 if (e[7]) {
3333
3334 if (!utf8_is_valid(e+7)) {
3335 log_warning_unit(u->id,
3336 "Status message in notification is not UTF-8 clean.");
3337 return;
3338 }
3339
3340 t = strdup(e+7);
3341 if (!t) {
3342 log_error_unit(u->id,
3343 "Failed to allocate string.");
3344 return;
3345 }
3346
3347 log_debug_unit(u->id,
3348 "%s: got %s", u->id, e);
3349
3350 free(s->status_text);
3351 s->status_text = t;
3352 } else {
3353 free(s->status_text);
3354 s->status_text = NULL;
3355 }
3356
3357 }
3358 if (strv_find(tags, "WATCHDOG=1")) {
3359 log_debug_unit(u->id,
3360 "%s: got WATCHDOG=1", u->id);
3361 if (dual_timestamp_is_set(&s->watchdog_timestamp))
3362 service_reset_watchdog(s);
3363 }
3364
3365 /* Notify clients about changed status or main pid */
3366 unit_add_to_dbus_queue(u);
3367 }
3368
3369 #ifdef HAVE_SYSV_COMPAT
3370
3371 static int service_enumerate(Manager *m) {
3372 char **p;
3373 unsigned i;
3374 DIR *d = NULL;
3375 char *path = NULL, *fpath = NULL, *name = NULL;
3376 Set *runlevel_services[ELEMENTSOF(rcnd_table)], *shutdown_services = NULL;
3377 Unit *service;
3378 Iterator j;
3379 int r;
3380
3381 assert(m);
3382
3383 if (m->running_as != SYSTEMD_SYSTEM)
3384 return 0;
3385
3386 zero(runlevel_services);
3387
3388 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
3389 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
3390 struct dirent *de;
3391
3392 free(path);
3393 path = strjoin(*p, "/", rcnd_table[i].path, NULL);
3394 if (!path) {
3395 r = -ENOMEM;
3396 goto finish;
3397 }
3398
3399 if (d)
3400 closedir(d);
3401
3402 if (!(d = opendir(path))) {
3403 if (errno != ENOENT)
3404 log_warning("opendir() failed on %s: %s", path, strerror(errno));
3405
3406 continue;
3407 }
3408
3409 while ((de = readdir(d))) {
3410 int a, b;
3411
3412 if (ignore_file(de->d_name))
3413 continue;
3414
3415 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3416 continue;
3417
3418 if (strlen(de->d_name) < 4)
3419 continue;
3420
3421 a = undecchar(de->d_name[1]);
3422 b = undecchar(de->d_name[2]);
3423
3424 if (a < 0 || b < 0)
3425 continue;
3426
3427 free(fpath);
3428 fpath = strjoin(path, "/", de->d_name, NULL);
3429 if (!fpath) {
3430 r = -ENOMEM;
3431 goto finish;
3432 }
3433
3434 if (access(fpath, X_OK) < 0) {
3435
3436 if (errno != ENOENT)
3437 log_warning("access() failed on %s: %s", fpath, strerror(errno));
3438
3439 continue;
3440 }
3441
3442 free(name);
3443 if (!(name = sysv_translate_name(de->d_name + 3))) {
3444 r = -ENOMEM;
3445 goto finish;
3446 }
3447
3448 r = manager_load_unit_prepare(m, name, NULL, NULL, &service);
3449 if (r < 0) {
3450 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3451 continue;
3452 }
3453
3454 if (de->d_name[0] == 'S') {
3455
3456 if (rcnd_table[i].type == RUNLEVEL_UP) {
3457 SERVICE(service)->sysv_start_priority_from_rcnd =
3458 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
3459
3460 SERVICE(service)->sysv_enabled = true;
3461 }
3462
3463 if ((r = set_ensure_allocated(&runlevel_services[i], trivial_hash_func, trivial_compare_func)) < 0)
3464 goto finish;
3465
3466 if ((r = set_put(runlevel_services[i], service)) < 0)
3467 goto finish;
3468
3469 } else if (de->d_name[0] == 'K' &&
3470 (rcnd_table[i].type == RUNLEVEL_DOWN)) {
3471
3472 if ((r = set_ensure_allocated(&shutdown_services, trivial_hash_func, trivial_compare_func)) < 0)
3473 goto finish;
3474
3475 if ((r = set_put(shutdown_services, service)) < 0)
3476 goto finish;
3477 }
3478 }
3479 }
3480
3481 /* Now we loaded all stubs and are aware of the lowest
3482 start-up priority for all services, not let's actually load
3483 the services, this will also tell us which services are
3484 actually native now */
3485 manager_dispatch_load_queue(m);
3486
3487 /* If this is a native service, rely on native ways to pull in
3488 * a service, don't pull it in via sysv rcN.d links. */
3489 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3490 SET_FOREACH(service, runlevel_services[i], j) {
3491 service = unit_follow_merge(service);
3492
3493 if (service->fragment_path)
3494 continue;
3495
3496 if ((r = unit_add_two_dependencies_by_name_inverse(service, UNIT_AFTER, UNIT_WANTS, rcnd_table[i].target, NULL, true)) < 0)
3497 goto finish;
3498 }
3499
3500 /* We honour K links only for halt/reboot. For the normal
3501 * runlevels we assume the stop jobs will be implicitly added
3502 * by the core logic. Also, we don't really distinguish here
3503 * between the runlevels 0 and 6 and just add them to the
3504 * special shutdown target. */
3505 SET_FOREACH(service, shutdown_services, j) {
3506 service = unit_follow_merge(service);
3507
3508 if (service->fragment_path)
3509 continue;
3510
3511 if ((r = unit_add_two_dependencies_by_name(service, UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true)) < 0)
3512 goto finish;
3513 }
3514
3515 r = 0;
3516
3517 finish:
3518 free(path);
3519 free(fpath);
3520 free(name);
3521
3522 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3523 set_free(runlevel_services[i]);
3524 set_free(shutdown_services);
3525
3526 if (d)
3527 closedir(d);
3528
3529 return r;
3530 }
3531 #endif
3532
3533 static void service_bus_name_owner_change(
3534 Unit *u,
3535 const char *name,
3536 const char *old_owner,
3537 const char *new_owner) {
3538
3539 Service *s = SERVICE(u);
3540
3541 assert(s);
3542 assert(name);
3543
3544 assert(streq(s->bus_name, name));
3545 assert(old_owner || new_owner);
3546
3547 if (old_owner && new_owner)
3548 log_debug_unit(u->id,
3549 "%s's D-Bus name %s changed owner from %s to %s",
3550 u->id, name, old_owner, new_owner);
3551 else if (old_owner)
3552 log_debug_unit(u->id,
3553 "%s's D-Bus name %s no longer registered by %s",
3554 u->id, name, old_owner);
3555 else
3556 log_debug_unit(u->id,
3557 "%s's D-Bus name %s now registered by %s",
3558 u->id, name, new_owner);
3559
3560 s->bus_name_good = !!new_owner;
3561
3562 if (s->type == SERVICE_DBUS) {
3563
3564 /* service_enter_running() will figure out what to
3565 * do */
3566 if (s->state == SERVICE_RUNNING)
3567 service_enter_running(s, SERVICE_SUCCESS);
3568 else if (s->state == SERVICE_START && new_owner)
3569 service_enter_start_post(s);
3570
3571 } else if (new_owner &&
3572 s->main_pid <= 0 &&
3573 (s->state == SERVICE_START ||
3574 s->state == SERVICE_START_POST ||
3575 s->state == SERVICE_RUNNING ||
3576 s->state == SERVICE_RELOAD)) {
3577
3578 /* Try to acquire PID from bus service */
3579 log_debug_unit(u->id,
3580 "Trying to acquire PID from D-Bus name...");
3581
3582 bus_query_pid(u->manager, name);
3583 }
3584 }
3585
3586 static void service_bus_query_pid_done(
3587 Unit *u,
3588 const char *name,
3589 pid_t pid) {
3590
3591 Service *s = SERVICE(u);
3592
3593 assert(s);
3594 assert(name);
3595
3596 log_debug_unit(u->id,
3597 "%s's D-Bus name %s is now owned by process %u",
3598 u->id, name, (unsigned) pid);
3599
3600 if (s->main_pid <= 0 &&
3601 (s->state == SERVICE_START ||
3602 s->state == SERVICE_START_POST ||
3603 s->state == SERVICE_RUNNING ||
3604 s->state == SERVICE_RELOAD))
3605 service_set_main_pid(s, pid);
3606 }
3607
3608 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
3609
3610 assert(s);
3611 assert(fd >= 0);
3612
3613 /* This is called by the socket code when instantiating a new
3614 * service for a stream socket and the socket needs to be
3615 * configured. */
3616
3617 if (UNIT(s)->load_state != UNIT_LOADED)
3618 return -EINVAL;
3619
3620 if (s->socket_fd >= 0)
3621 return -EBUSY;
3622
3623 if (s->state != SERVICE_DEAD)
3624 return -EAGAIN;
3625
3626 s->socket_fd = fd;
3627 s->got_socket_fd = true;
3628
3629 unit_ref_set(&s->accept_socket, UNIT(sock));
3630
3631 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3632 }
3633
3634 static void service_reset_failed(Unit *u) {
3635 Service *s = SERVICE(u);
3636
3637 assert(s);
3638
3639 if (s->state == SERVICE_FAILED)
3640 service_set_state(s, SERVICE_DEAD);
3641
3642 s->result = SERVICE_SUCCESS;
3643 s->reload_result = SERVICE_SUCCESS;
3644
3645 RATELIMIT_RESET(s->start_limit);
3646 }
3647
3648 static int service_kill(Unit *u, KillWho who, int signo, DBusError *error) {
3649 Service *s = SERVICE(u);
3650 int r = 0;
3651 Set *pid_set = NULL;
3652
3653 assert(s);
3654
3655 if (s->main_pid <= 0 && who == KILL_MAIN) {
3656 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3657 return -ESRCH;
3658 }
3659
3660 if (s->control_pid <= 0 && who == KILL_CONTROL) {
3661 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3662 return -ESRCH;
3663 }
3664
3665 if (who == KILL_CONTROL || who == KILL_ALL)
3666 if (s->control_pid > 0)
3667 if (kill(s->control_pid, signo) < 0)
3668 r = -errno;
3669
3670 if (who == KILL_MAIN || who == KILL_ALL)
3671 if (s->main_pid > 0)
3672 if (kill(s->main_pid, signo) < 0)
3673 r = -errno;
3674
3675 if (who == KILL_ALL) {
3676 int q;
3677
3678 pid_set = set_new(trivial_hash_func, trivial_compare_func);
3679 if (!pid_set)
3680 return -ENOMEM;
3681
3682 /* Exclude the control/main pid from being killed via the cgroup */
3683 if (s->control_pid > 0) {
3684 q = set_put(pid_set, LONG_TO_PTR(s->control_pid));
3685 if (q < 0) {
3686 r = q;
3687 goto finish;
3688 }
3689 }
3690
3691 if (s->main_pid > 0) {
3692 q = set_put(pid_set, LONG_TO_PTR(s->main_pid));
3693 if (q < 0) {
3694 r = q;
3695 goto finish;
3696 }
3697 }
3698
3699 q = cgroup_bonding_kill_list(UNIT(s)->cgroup_bondings, signo, false, false, pid_set, NULL);
3700 if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3701 r = q;
3702 }
3703
3704 finish:
3705 if (pid_set)
3706 set_free(pid_set);
3707
3708 return r;
3709 }
3710
3711 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3712 [SERVICE_DEAD] = "dead",
3713 [SERVICE_START_PRE] = "start-pre",
3714 [SERVICE_START] = "start",
3715 [SERVICE_START_POST] = "start-post",
3716 [SERVICE_RUNNING] = "running",
3717 [SERVICE_EXITED] = "exited",
3718 [SERVICE_RELOAD] = "reload",
3719 [SERVICE_STOP] = "stop",
3720 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3721 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3722 [SERVICE_STOP_POST] = "stop-post",
3723 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3724 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3725 [SERVICE_FAILED] = "failed",
3726 [SERVICE_AUTO_RESTART] = "auto-restart",
3727 };
3728
3729 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3730
3731 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3732 [SERVICE_RESTART_NO] = "no",
3733 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3734 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3735 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3736 [SERVICE_RESTART_ALWAYS] = "always"
3737 };
3738
3739 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3740
3741 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3742 [SERVICE_SIMPLE] = "simple",
3743 [SERVICE_FORKING] = "forking",
3744 [SERVICE_ONESHOT] = "oneshot",
3745 [SERVICE_DBUS] = "dbus",
3746 [SERVICE_NOTIFY] = "notify",
3747 [SERVICE_IDLE] = "idle"
3748 };
3749
3750 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3751
3752 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3753 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3754 [SERVICE_EXEC_START] = "ExecStart",
3755 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3756 [SERVICE_EXEC_RELOAD] = "ExecReload",
3757 [SERVICE_EXEC_STOP] = "ExecStop",
3758 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3759 };
3760
3761 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3762
3763 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3764 [NOTIFY_NONE] = "none",
3765 [NOTIFY_MAIN] = "main",
3766 [NOTIFY_ALL] = "all"
3767 };
3768
3769 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3770
3771 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3772 [SERVICE_SUCCESS] = "success",
3773 [SERVICE_FAILURE_RESOURCES] = "resources",
3774 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3775 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3776 [SERVICE_FAILURE_SIGNAL] = "signal",
3777 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3778 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3779 [SERVICE_FAILURE_START_LIMIT] = "start-limit"
3780 };
3781
3782 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3783
3784 static const char* const start_limit_action_table[_SERVICE_START_LIMIT_MAX] = {
3785 [SERVICE_START_LIMIT_NONE] = "none",
3786 [SERVICE_START_LIMIT_REBOOT] = "reboot",
3787 [SERVICE_START_LIMIT_REBOOT_FORCE] = "reboot-force",
3788 [SERVICE_START_LIMIT_REBOOT_IMMEDIATE] = "reboot-immediate"
3789 };
3790 DEFINE_STRING_TABLE_LOOKUP(start_limit_action, StartLimitAction);
3791
3792 const UnitVTable service_vtable = {
3793 .object_size = sizeof(Service),
3794
3795 .sections =
3796 "Unit\0"
3797 "Service\0"
3798 "Install\0",
3799
3800 .exec_context_offset = offsetof(Service, exec_context),
3801 .exec_section = "Service",
3802
3803 .init = service_init,
3804 .done = service_done,
3805 .load = service_load,
3806
3807 .coldplug = service_coldplug,
3808
3809 .dump = service_dump,
3810
3811 .start = service_start,
3812 .stop = service_stop,
3813 .reload = service_reload,
3814
3815 .can_reload = service_can_reload,
3816
3817 .kill = service_kill,
3818
3819 .serialize = service_serialize,
3820 .deserialize_item = service_deserialize_item,
3821
3822 .active_state = service_active_state,
3823 .sub_state_to_string = service_sub_state_to_string,
3824
3825 .check_gc = service_check_gc,
3826 .check_snapshot = service_check_snapshot,
3827
3828 .sigchld_event = service_sigchld_event,
3829 .timer_event = service_timer_event,
3830 .fd_event = service_fd_event,
3831
3832 .reset_failed = service_reset_failed,
3833
3834 .cgroup_notify_empty = service_cgroup_notify_event,
3835 .notify_message = service_notify_message,
3836
3837 .bus_name_owner_change = service_bus_name_owner_change,
3838 .bus_query_pid_done = service_bus_query_pid_done,
3839
3840 .bus_interface = "org.freedesktop.systemd1.Service",
3841 .bus_message_handler = bus_service_message_handler,
3842 .bus_invalidating_properties = bus_service_invalidating_properties,
3843
3844 #ifdef HAVE_SYSV_COMPAT
3845 .enumerate = service_enumerate,
3846 #endif
3847 .status_message_formats = {
3848 .starting_stopping = {
3849 [0] = "Starting %s...",
3850 [1] = "Stopping %s...",
3851 },
3852 .finished_start_job = {
3853 [JOB_DONE] = "Started %s.",
3854 [JOB_FAILED] = "Failed to start %s.",
3855 [JOB_DEPENDENCY] = "Dependency failed for %s.",
3856 [JOB_TIMEOUT] = "Timed out starting %s.",
3857 },
3858 .finished_stop_job = {
3859 [JOB_DONE] = "Stopped %s.",
3860 [JOB_FAILED] = "Stopped (with error) %s.",
3861 [JOB_TIMEOUT] = "Timed out stopping %s.",
3862 },
3863 },
3864 };