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