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