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