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