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