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