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