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