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