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