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