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