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