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