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