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