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