tizen 2.4 release
[external/systemd.git] / src / core / service.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 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   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser 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 #include <sys/reboot.h>
27 #include <linux/reboot.h>
28 #include <sys/syscall.h>
29
30 #include "async.h"
31 #include "manager.h"
32 #include "unit.h"
33 #include "service.h"
34 #include "load-fragment.h"
35 #include "load-dropin.h"
36 #include "log.h"
37 #include "strv.h"
38 #include "unit-name.h"
39 #include "unit-printf.h"
40 #include "dbus-service.h"
41 #include "special.h"
42 #include "exit-status.h"
43 #include "def.h"
44 #include "path-util.h"
45 #include "util.h"
46 #include "utf8.h"
47 #include "env-util.h"
48 #include "fileio.h"
49 #include "bus-error.h"
50 #include "bus-util.h"
51
52 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
53         [SERVICE_DEAD] = UNIT_INACTIVE,
54         [SERVICE_START_PRE] = UNIT_ACTIVATING,
55         [SERVICE_START] = UNIT_ACTIVATING,
56         [SERVICE_START_POST] = UNIT_ACTIVATING,
57         [SERVICE_RUNNING] = UNIT_ACTIVE,
58         [SERVICE_EXITED] = UNIT_ACTIVE,
59         [SERVICE_RELOAD] = UNIT_RELOADING,
60         [SERVICE_STOP] = UNIT_DEACTIVATING,
61         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
62         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
63         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
64         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
65         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
66         [SERVICE_FAILED] = UNIT_FAILED,
67         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
68 };
69
70 /* For Type=idle we never want to delay any other jobs, hence we
71  * consider idle jobs active as soon as we start working on them */
72 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
73         [SERVICE_DEAD] = UNIT_INACTIVE,
74         [SERVICE_START_PRE] = UNIT_ACTIVE,
75         [SERVICE_START] = UNIT_ACTIVE,
76         [SERVICE_START_POST] = UNIT_ACTIVE,
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_FAILED] = UNIT_FAILED,
87         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
88 };
89
90 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
91 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
92 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
93
94 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
95
96 static void service_init(Unit *u) {
97         Service *s = SERVICE(u);
98
99         assert(u);
100         assert(u->load_state == UNIT_STUB);
101
102         s->timeout_start_usec = u->manager->default_timeout_start_usec;
103         s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
104         s->restart_usec = u->manager->default_restart_usec;
105         s->type = _SERVICE_TYPE_INVALID;
106         s->socket_fd = -1;
107         s->guess_main_pid = true;
108
109         RATELIMIT_INIT(s->start_limit, u->manager->default_start_limit_interval, u->manager->default_start_limit_burst);
110
111         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
112 }
113
114 static void service_unwatch_control_pid(Service *s) {
115         assert(s);
116
117         if (s->control_pid <= 0)
118                 return;
119
120         unit_unwatch_pid(UNIT(s), s->control_pid);
121         s->control_pid = 0;
122 }
123
124 static void service_unwatch_main_pid(Service *s) {
125         assert(s);
126
127         if (s->main_pid <= 0)
128                 return;
129
130         unit_unwatch_pid(UNIT(s), s->main_pid);
131         s->main_pid = 0;
132 }
133
134 static void service_unwatch_pid_file(Service *s) {
135         if (!s->pid_file_pathspec)
136                 return;
137
138         log_debug_unit(UNIT(s)->id, "Stopping watch for %s's PID file %s",
139                        UNIT(s)->id, s->pid_file_pathspec->path);
140         path_spec_unwatch(s->pid_file_pathspec);
141         path_spec_done(s->pid_file_pathspec);
142         free(s->pid_file_pathspec);
143         s->pid_file_pathspec = NULL;
144 }
145
146 static int service_set_main_pid(Service *s, pid_t pid) {
147         pid_t ppid;
148
149         assert(s);
150
151         if (pid <= 1)
152                 return -EINVAL;
153
154         if (pid == getpid())
155                 return -EINVAL;
156
157         if (s->main_pid == pid && s->main_pid_known)
158                 return 0;
159
160         if (s->main_pid != pid) {
161                 service_unwatch_main_pid(s);
162                 exec_status_start(&s->main_exec_status, pid);
163         }
164
165         s->main_pid = pid;
166         s->main_pid_known = true;
167
168         if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
169                 log_warning_unit(UNIT(s)->id,
170                                  "%s: Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.",
171                                  UNIT(s)->id, pid);
172
173                 s->main_pid_alien = true;
174         } else
175                 s->main_pid_alien = false;
176
177         return 0;
178 }
179
180 static void service_close_socket_fd(Service *s) {
181         assert(s);
182
183         if (s->socket_fd < 0)
184                 return;
185
186         s->socket_fd = asynchronous_close(s->socket_fd);
187 }
188
189 static void service_connection_unref(Service *s) {
190         assert(s);
191
192         if (!UNIT_ISSET(s->accept_socket))
193                 return;
194
195         socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
196         unit_ref_unset(&s->accept_socket);
197 }
198
199 static void service_stop_watchdog(Service *s) {
200         assert(s);
201
202         s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
203         s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
204 }
205
206 static void service_start_watchdog(Service *s) {
207         int r;
208
209         assert(s);
210
211         if (s->watchdog_usec <= 0)
212                 return;
213
214         if (s->watchdog_event_source) {
215                 r = sd_event_source_set_time(s->watchdog_event_source, s->watchdog_timestamp.monotonic + s->watchdog_usec);
216                 if (r < 0) {
217                         log_warning_unit(UNIT(s)->id, "%s failed to reset watchdog timer: %s", UNIT(s)->id, strerror(-r));
218                         return;
219                 }
220
221                 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
222         } else {
223                 r = sd_event_add_time(
224                                 UNIT(s)->manager->event,
225                                 &s->watchdog_event_source,
226                                 CLOCK_MONOTONIC,
227                                 s->watchdog_timestamp.monotonic + s->watchdog_usec, 0,
228                                 service_dispatch_watchdog, s);
229                 if (r < 0) {
230                         log_warning_unit(UNIT(s)->id, "%s failed to add watchdog timer: %s", UNIT(s)->id, strerror(-r));
231                         return;
232                 }
233
234                 /* Let's process everything else which might be a sign
235                  * of living before we consider a service died. */
236                 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
237         }
238
239         if (r < 0)
240                 log_warning_unit(UNIT(s)->id, "%s failed to install watchdog timer: %s", UNIT(s)->id, strerror(-r));
241 }
242
243 static void service_reset_watchdog(Service *s) {
244         assert(s);
245
246         dual_timestamp_get(&s->watchdog_timestamp);
247         service_start_watchdog(s);
248 }
249
250 static void service_done(Unit *u) {
251         Service *s = SERVICE(u);
252
253         assert(s);
254
255         free(s->pid_file);
256         s->pid_file = NULL;
257
258         free(s->status_text);
259         s->status_text = NULL;
260
261         free(s->reboot_arg);
262         s->reboot_arg = NULL;
263
264         s->exec_runtime = exec_runtime_unref(s->exec_runtime);
265         exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
266         s->control_command = NULL;
267         s->main_command = NULL;
268
269         exit_status_set_free(&s->restart_prevent_status);
270         exit_status_set_free(&s->restart_force_status);
271         exit_status_set_free(&s->success_status);
272
273         /* This will leak a process, but at least no memory or any of
274          * our resources */
275         service_unwatch_main_pid(s);
276         service_unwatch_control_pid(s);
277         service_unwatch_pid_file(s);
278
279         if (s->bus_name)  {
280                 unit_unwatch_bus_name(u, s->bus_name);
281                 free(s->bus_name);
282                 s->bus_name = NULL;
283         }
284
285         service_close_socket_fd(s);
286         service_connection_unref(s);
287
288         unit_ref_unset(&s->accept_socket);
289
290         service_stop_watchdog(s);
291
292         s->timer_event_source = sd_event_source_unref(s->timer_event_source);
293 }
294
295 static int service_arm_timer(Service *s, usec_t usec) {
296         int r;
297
298         assert(s);
299
300         if (s->timer_event_source) {
301                 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
302                 if (r < 0)
303                         return r;
304
305                 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
306         }
307
308         return sd_event_add_time(
309                         UNIT(s)->manager->event,
310                         &s->timer_event_source,
311                         CLOCK_MONOTONIC,
312                         now(CLOCK_MONOTONIC) + usec, 0,
313                         service_dispatch_timer, s);
314 }
315
316 static int service_verify(Service *s) {
317         assert(s);
318
319         if (UNIT(s)->load_state != UNIT_LOADED)
320                 return 0;
321
322         if (!s->exec_command[SERVICE_EXEC_START]) {
323                 log_error_unit(UNIT(s)->id, "%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
324                 return -EINVAL;
325         }
326
327         if (s->type != SERVICE_ONESHOT &&
328             s->exec_command[SERVICE_EXEC_START]->command_next) {
329                 log_error_unit(UNIT(s)->id, "%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
330                 return -EINVAL;
331         }
332
333         if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
334                 log_error_unit(UNIT(s)->id, "%s has Restart= setting other than no, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
335                 return -EINVAL;
336         }
337
338         if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status)) {
339                 log_error_unit(UNIT(s)->id, "%s has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
340                 return -EINVAL;
341         }
342
343         if (s->type == SERVICE_DBUS && !s->bus_name) {
344                 log_error_unit(UNIT(s)->id, "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
345                 return -EINVAL;
346         }
347
348         if (s->bus_name && s->type != SERVICE_DBUS)
349                 log_warning_unit(UNIT(s)->id, "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
350
351         if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
352                 log_error_unit(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.", UNIT(s)->id);
353                 return -EINVAL;
354         }
355
356         return 0;
357 }
358
359 #ifdef CONFIG_TIZEN
360 static int service_add_default_extra_dependencies(Service *s) {
361         char *t = NULL;
362         char **d;
363         int r;
364         bool ignore;
365
366         if (!(UNIT(s)->manager->dependencies))
367                 return 0;
368
369         /* Do NOT add dependencies for systemd unit files */
370         if (startswith(UNIT(s)->id, "systemd-")
371             || startswith(UNIT(s)->id, "serial-getty"))
372                 return 0;
373
374         t = unit_name_template(UNIT(s)->id);
375         if (!t)
376                 return -ENOMEM;
377
378         ignore = hashmap_contains(UNIT(s)->manager->dep_ignore_list, t);
379         free(t);
380         if (ignore)
381                 return 0;
382
383         STRV_FOREACH(d, UNIT(s)->manager->dependencies) {
384                 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, *d, NULL, true);
385                 if (r < 0)
386                         return r;
387         }
388
389         return 0;
390 }
391 #endif
392
393 static int service_add_default_dependencies(Service *s) {
394         int r;
395
396         assert(s);
397
398         /* Add a number of automatic dependencies useful for the
399          * majority of services. */
400
401         /* First, pull in base system */
402         r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
403                                               SPECIAL_BASIC_TARGET, NULL, true);
404         if (r < 0)
405                 return r;
406
407 #ifdef CONFIG_TIZEN
408         r = service_add_default_extra_dependencies(s);
409         if (r < 0)
410                 return r;
411 #endif
412
413         /* Second, activate normal shutdown */
414         r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS,
415                                               SPECIAL_SHUTDOWN_TARGET, NULL, true);
416         return r;
417 }
418
419 static void service_fix_output(Service *s) {
420         assert(s);
421
422         /* If nothing has been explicitly configured, patch default
423          * output in. If input is socket/tty we avoid this however,
424          * since in that case we want output to default to the same
425          * place as we read input from. */
426
427         if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
428             s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
429             s->exec_context.std_input == EXEC_INPUT_NULL)
430                 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
431
432         if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
433             s->exec_context.std_input == EXEC_INPUT_NULL)
434                 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
435 }
436
437 static int service_load(Unit *u) {
438         int r;
439         Service *s = SERVICE(u);
440
441         assert(s);
442
443         /* Load a .service file */
444         r = unit_load_fragment(u);
445         if (r < 0)
446                 return r;
447
448         /* Still nothing found? Then let's give up */
449         if (u->load_state == UNIT_STUB)
450                 return -ENOENT;
451
452         /* This is a new unit? Then let's add in some extras */
453         if (u->load_state == UNIT_LOADED) {
454
455                 /* We were able to load something, then let's add in
456                  * the dropin directories. */
457                 r = unit_load_dropin(u);
458                 if (r < 0)
459                         return r;
460
461                 if (s->type == _SERVICE_TYPE_INVALID)
462                         s->type = s->bus_name ? SERVICE_DBUS : SERVICE_SIMPLE;
463
464                 /* Oneshot services have disabled start timeout by default */
465                 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
466                         s->timeout_start_usec = 0;
467
468                 service_fix_output(s);
469
470                 r = unit_patch_contexts(u);
471                 if (r < 0)
472                         return r;
473
474                 r = unit_add_exec_dependencies(u, &s->exec_context);
475                 if (r < 0)
476                         return r;
477
478                 r = unit_add_default_slice(u, &s->cgroup_context);
479                 if (r < 0)
480                         return r;
481
482                 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
483                         s->notify_access = NOTIFY_MAIN;
484
485                 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
486                         s->notify_access = NOTIFY_MAIN;
487
488                 if (s->bus_name) {
489                         r = unit_watch_bus_name(u, s->bus_name);
490                         if (r < 0)
491                                 return r;
492                 }
493
494                 if (u->default_dependencies) {
495                         r = service_add_default_dependencies(s);
496                         if (r < 0)
497
498                                 return r;
499                 }
500         }
501
502         return service_verify(s);
503 }
504
505 static void service_dump(Unit *u, FILE *f, const char *prefix) {
506
507         ServiceExecCommand c;
508         Service *s = SERVICE(u);
509         const char *prefix2;
510         _cleanup_free_ char *p2 = NULL;
511
512         assert(s);
513
514         p2 = strappend(prefix, "\t");
515         prefix2 = p2 ? p2 : prefix;
516
517         fprintf(f,
518                 "%sService State: %s\n"
519                 "%sResult: %s\n"
520                 "%sReload Result: %s\n"
521                 "%sPermissionsStartOnly: %s\n"
522                 "%sRootDirectoryStartOnly: %s\n"
523                 "%sRemainAfterExit: %s\n"
524                 "%sGuessMainPID: %s\n"
525                 "%sType: %s\n"
526                 "%sRestart: %s\n"
527                 "%sNotifyAccess: %s\n",
528                 prefix, service_state_to_string(s->state),
529                 prefix, service_result_to_string(s->result),
530                 prefix, service_result_to_string(s->reload_result),
531                 prefix, yes_no(s->permissions_start_only),
532                 prefix, yes_no(s->root_directory_start_only),
533                 prefix, yes_no(s->remain_after_exit),
534                 prefix, yes_no(s->guess_main_pid),
535                 prefix, service_type_to_string(s->type),
536                 prefix, service_restart_to_string(s->restart),
537                 prefix, notify_access_to_string(s->notify_access));
538
539         if (s->control_pid > 0)
540                 fprintf(f,
541                         "%sControl PID: "PID_FMT"\n",
542                         prefix, s->control_pid);
543
544         if (s->main_pid > 0)
545                 fprintf(f,
546                         "%sMain PID: "PID_FMT"\n"
547                         "%sMain PID Known: %s\n"
548                         "%sMain PID Alien: %s\n",
549                         prefix, s->main_pid,
550                         prefix, yes_no(s->main_pid_known),
551                         prefix, yes_no(s->main_pid_alien));
552
553         if (s->pid_file)
554                 fprintf(f,
555                         "%sPIDFile: %s\n",
556                         prefix, s->pid_file);
557
558         if (s->bus_name)
559                 fprintf(f,
560                         "%sBusName: %s\n"
561                         "%sBus Name Good: %s\n",
562                         prefix, s->bus_name,
563                         prefix, yes_no(s->bus_name_good));
564
565         kill_context_dump(&s->kill_context, f, prefix);
566         exec_context_dump(&s->exec_context, f, prefix);
567
568         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
569
570                 if (!s->exec_command[c])
571                         continue;
572
573                 fprintf(f, "%s-> %s:\n",
574                         prefix, service_exec_command_to_string(c));
575
576                 exec_command_dump_list(s->exec_command[c], f, prefix2);
577         }
578
579 #ifdef HAVE_SYSV_COMPAT
580         if (s->sysv_start_priority >= 0)
581                 fprintf(f,
582                         "%sSysVStartPriority: %i\n",
583                         prefix, s->sysv_start_priority);
584 #endif
585
586         if (s->status_text)
587                 fprintf(f, "%sStatus Text: %s\n",
588                         prefix, s->status_text);
589 }
590
591 static int service_load_pid_file(Service *s, bool may_warn) {
592         _cleanup_free_ char *k = NULL;
593         int r;
594         pid_t pid;
595
596         assert(s);
597
598         if (!s->pid_file)
599                 return -ENOENT;
600
601         r = read_one_line_file(s->pid_file, &k);
602         if (r < 0) {
603                 if (may_warn)
604                         log_info_unit(UNIT(s)->id,
605                                       "PID file %s not readable (yet?) after %s.",
606                                       s->pid_file, service_state_to_string(s->state));
607                 return r;
608         }
609
610         r = parse_pid(k, &pid);
611         if (r < 0) {
612                 if (may_warn)
613                         log_info_unit(UNIT(s)->id,
614                                       "Failed to read PID from file %s: %s",
615                                       s->pid_file, strerror(-r));
616                 return r;
617         }
618
619         if (!pid_is_alive(pid)) {
620                 if (may_warn)
621                         log_info_unit(UNIT(s)->id, "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
622
623                 return -ESRCH;
624         }
625
626         if (s->main_pid_known) {
627                 if (pid == s->main_pid)
628                         return 0;
629
630                 log_debug_unit(UNIT(s)->id,
631                                "Main PID changing: "PID_FMT" -> "PID_FMT,
632                                s->main_pid, pid);
633                 service_unwatch_main_pid(s);
634                 s->main_pid_known = false;
635         } else
636                 log_debug_unit(UNIT(s)->id,
637                                "Main PID loaded: "PID_FMT, pid);
638
639         r = service_set_main_pid(s, pid);
640         if (r < 0)
641                 return r;
642
643         r = unit_watch_pid(UNIT(s), pid);
644         if (r < 0) {
645                 /* FIXME: we need to do something here */
646                 log_warning_unit(UNIT(s)->id,
647                                  "Failed to watch PID "PID_FMT" from service %s",
648                                  pid, UNIT(s)->id);
649                 return r;
650         }
651
652         return 0;
653 }
654
655 static int service_search_main_pid(Service *s) {
656         pid_t pid;
657         int r;
658
659         assert(s);
660
661         /* If we know it anyway, don't ever fallback to unreliable
662          * heuristics */
663         if (s->main_pid_known)
664                 return 0;
665
666         if (!s->guess_main_pid)
667                 return 0;
668
669         assert(s->main_pid <= 0);
670
671         pid = unit_search_main_pid(UNIT(s));
672         if (pid <= 0)
673                 return -ENOENT;
674
675         log_debug_unit(UNIT(s)->id,
676                        "Main PID guessed: "PID_FMT, pid);
677         r = service_set_main_pid(s, pid);
678         if (r < 0)
679                 return r;
680
681         r = unit_watch_pid(UNIT(s), pid);
682         if (r < 0)
683                 /* FIXME: we need to do something here */
684                 log_warning_unit(UNIT(s)->id,
685                                  "Failed to watch PID "PID_FMT" from service %s",
686                                  pid, UNIT(s)->id);
687         return r;
688 }
689
690 static void service_set_state(Service *s, ServiceState state) {
691         ServiceState old_state;
692         const UnitActiveState *table;
693
694         assert(s);
695
696         table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
697
698         old_state = s->state;
699         s->state = state;
700
701         service_unwatch_pid_file(s);
702
703         if (!IN_SET(state,
704                     SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
705                     SERVICE_RELOAD,
706                     SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
707                     SERVICE_STOP_POST,
708                     SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
709                     SERVICE_AUTO_RESTART))
710                 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
711
712         if (!IN_SET(state,
713                     SERVICE_START, SERVICE_START_POST,
714                     SERVICE_RUNNING, SERVICE_RELOAD,
715                     SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
716                     SERVICE_STOP_POST,
717                     SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
718                 service_unwatch_main_pid(s);
719                 s->main_command = NULL;
720         }
721
722         if (!IN_SET(state,
723                     SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
724                     SERVICE_RELOAD,
725                     SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
726                     SERVICE_STOP_POST,
727                     SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
728                 service_unwatch_control_pid(s);
729                 s->control_command = NULL;
730                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
731         }
732
733         if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
734                 unit_unwatch_all_pids(UNIT(s));
735
736         if (!IN_SET(state,
737                     SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
738                     SERVICE_RUNNING, SERVICE_RELOAD,
739                     SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
740                     SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
741             !(state == SERVICE_DEAD && UNIT(s)->job)) {
742                 service_close_socket_fd(s);
743                 service_connection_unref(s);
744         }
745
746         if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
747                 service_stop_watchdog(s);
748
749         /* For the inactive states unit_notify() will trim the cgroup,
750          * but for exit we have to do that ourselves... */
751         if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
752                 unit_destroy_cgroup(UNIT(s));
753
754         /* For remain_after_exit services, let's see if we can "release" the
755          * hold on the console, since unit_notify() only does that in case of
756          * change of state */
757         if (state == SERVICE_EXITED && s->remain_after_exit &&
758             UNIT(s)->manager->n_on_console > 0) {
759                 ExecContext *ec = unit_get_exec_context(UNIT(s));
760                 if (ec && exec_context_may_touch_console(ec)) {
761                         Manager *m = UNIT(s)->manager;
762
763                         m->n_on_console --;
764                         if (m->n_on_console == 0)
765                                 /* unset no_console_output flag, since the console is free */
766                                 m->no_console_output = false;
767                 }
768         }
769
770         if (old_state != state)
771                 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s", UNIT(s)->id, service_state_to_string(old_state), service_state_to_string(state));
772
773         unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
774         s->reload_result = SERVICE_SUCCESS;
775 }
776
777 static int service_coldplug(Unit *u) {
778         Service *s = SERVICE(u);
779         int r;
780
781         assert(s);
782         assert(s->state == SERVICE_DEAD);
783
784         if (s->deserialized_state != s->state) {
785
786                 if (IN_SET(s->deserialized_state,
787                            SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
788                            SERVICE_RELOAD,
789                            SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
790                            SERVICE_STOP_POST,
791                            SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
792
793                         usec_t k;
794
795                         k = IN_SET(s->deserialized_state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec;
796
797                         /* For the start/stop timeouts 0 means off */
798                         if (k > 0) {
799                                 r = service_arm_timer(s, k);
800                                 if (r < 0)
801                                         return r;
802                         }
803                 }
804
805                 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
806
807                         /* The restart timeouts 0 means immediately */
808                         r = service_arm_timer(s, s->restart_usec);
809                         if (r < 0)
810                                 return r;
811                 }
812
813                 if (pid_is_unwaited(s->main_pid) &&
814                     ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
815                      IN_SET(s->deserialized_state,
816                             SERVICE_START, SERVICE_START_POST,
817                             SERVICE_RUNNING, SERVICE_RELOAD,
818                             SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
819                             SERVICE_STOP_POST,
820                             SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
821                         r = unit_watch_pid(UNIT(s), s->main_pid);
822                         if (r < 0)
823                                 return r;
824                 }
825
826                 if (pid_is_unwaited(s->control_pid) &&
827                     IN_SET(s->deserialized_state,
828                            SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
829                            SERVICE_RELOAD,
830                            SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL,
831                            SERVICE_STOP_POST,
832                            SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
833                         r = unit_watch_pid(UNIT(s), s->control_pid);
834                         if (r < 0)
835                                 return r;
836                 }
837
838                 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
839                         unit_watch_all_pids(UNIT(s));
840
841                 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
842                         service_start_watchdog(s);
843
844                 service_set_state(s, s->deserialized_state);
845         }
846
847         return 0;
848 }
849
850 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
851         Iterator i;
852         int r;
853         int *rfds = NULL;
854         unsigned rn_fds = 0;
855         Unit *u;
856
857         assert(s);
858         assert(fds);
859         assert(n_fds);
860
861         if (s->socket_fd >= 0)
862                 return 0;
863
864         SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
865                 int *cfds;
866                 unsigned cn_fds;
867                 Socket *sock;
868
869                 if (u->type != UNIT_SOCKET)
870                         continue;
871
872                 sock = SOCKET(u);
873
874                 r = socket_collect_fds(sock, &cfds, &cn_fds);
875                 if (r < 0)
876                         goto fail;
877
878                 if (!cfds)
879                         continue;
880
881                 if (!rfds) {
882                         rfds = cfds;
883                         rn_fds = cn_fds;
884                 } else {
885                         int *t;
886
887                         t = new(int, rn_fds+cn_fds);
888                         if (!t) {
889                                 free(cfds);
890                                 r = -ENOMEM;
891                                 goto fail;
892                         }
893
894                         memcpy(t, rfds, rn_fds * sizeof(int));
895                         memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
896                         free(rfds);
897                         free(cfds);
898
899                         rfds = t;
900                         rn_fds = rn_fds+cn_fds;
901                 }
902         }
903
904         *fds = rfds;
905         *n_fds = rn_fds;
906
907         return 0;
908
909 fail:
910         free(rfds);
911
912         return r;
913 }
914
915 static int service_spawn(
916                 Service *s,
917                 ExecCommand *c,
918                 bool timeout,
919                 bool pass_fds,
920                 bool apply_permissions,
921                 bool apply_chroot,
922                 bool apply_tty_stdin,
923                 bool set_notify_socket,
924                 bool is_control,
925                 pid_t *_pid) {
926
927         pid_t pid;
928         int r;
929         int *fds = NULL;
930         _cleanup_free_ int *fdsbuf = NULL;
931         unsigned n_fds = 0, n_env = 0;
932         _cleanup_strv_free_ char
933                 **argv = NULL, **final_env = NULL, **our_env = NULL;
934         const char *path;
935
936         assert(s);
937         assert(c);
938         assert(_pid);
939
940         unit_realize_cgroup(UNIT(s));
941
942         r = unit_setup_exec_runtime(UNIT(s));
943         if (r < 0)
944                 goto fail;
945
946         if (pass_fds ||
947             s->exec_context.std_input == EXEC_INPUT_SOCKET ||
948             s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
949             s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
950
951                 if (s->socket_fd >= 0) {
952                         fds = &s->socket_fd;
953                         n_fds = 1;
954                 } else {
955                         r = service_collect_fds(s, &fdsbuf, &n_fds);
956                         if (r < 0)
957                                 goto fail;
958
959                         fds = fdsbuf;
960                 }
961         }
962
963         if (timeout && s->timeout_start_usec > 0) {
964                 r = service_arm_timer(s, s->timeout_start_usec);
965                 if (r < 0)
966                         goto fail;
967         } else
968                 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
969
970         r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
971         if (r < 0)
972                 goto fail;
973
974         our_env = new0(char*, 4);
975         if (!our_env) {
976                 r = -ENOMEM;
977                 goto fail;
978         }
979
980         if (set_notify_socket)
981                 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
982                         r = -ENOMEM;
983                         goto fail;
984                 }
985
986         if (s->main_pid > 0)
987                 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0) {
988                         r = -ENOMEM;
989                         goto fail;
990                 }
991
992         if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
993                 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0) {
994                         r = -ENOMEM;
995                         goto fail;
996                 }
997
998         final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
999         if (!final_env) {
1000                 r = -ENOMEM;
1001                 goto fail;
1002         }
1003
1004         if (is_control && UNIT(s)->cgroup_path) {
1005                 path = strappenda(UNIT(s)->cgroup_path, "/control");
1006                 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1007         } else
1008                 path = UNIT(s)->cgroup_path;
1009
1010         r = exec_spawn(c,
1011                        argv,
1012                        &s->exec_context,
1013                        fds, n_fds,
1014                        final_env,
1015                        apply_permissions,
1016                        apply_chroot,
1017                        apply_tty_stdin,
1018                        UNIT(s)->manager->confirm_spawn,
1019                        UNIT(s)->manager->cgroup_supported,
1020                        path,
1021                        manager_get_runtime_prefix(UNIT(s)->manager),
1022                        UNIT(s)->id,
1023                        s->watchdog_usec,
1024                        s->type == SERVICE_IDLE ? UNIT(s)->manager->idle_pipe : NULL,
1025                        s->exec_runtime,
1026                        &pid);
1027         if (r < 0)
1028                 goto fail;
1029
1030         r = unit_watch_pid(UNIT(s), pid);
1031         if (r < 0)
1032                 /* FIXME: we need to do something here */
1033                 goto fail;
1034
1035         *_pid = pid;
1036
1037         return 0;
1038
1039 fail:
1040         if (timeout)
1041                 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1042
1043         return r;
1044 }
1045
1046 static int main_pid_good(Service *s) {
1047         assert(s);
1048
1049         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1050          * don't know */
1051
1052         /* If we know the pid file, then lets just check if it is
1053          * still valid */
1054         if (s->main_pid_known) {
1055
1056                 /* If it's an alien child let's check if it is still
1057                  * alive ... */
1058                 if (s->main_pid_alien && s->main_pid > 0)
1059                         return pid_is_alive(s->main_pid);
1060
1061                 /* .. otherwise assume we'll get a SIGCHLD for it,
1062                  * which we really should wait for to collect exit
1063                  * status and code */
1064                 return s->main_pid > 0;
1065         }
1066
1067         /* We don't know the pid */
1068         return -EAGAIN;
1069 }
1070
1071 _pure_ static int control_pid_good(Service *s) {
1072         assert(s);
1073
1074         return s->control_pid > 0;
1075 }
1076
1077 static int cgroup_good(Service *s) {
1078         int r;
1079
1080         assert(s);
1081
1082         if (!UNIT(s)->cgroup_path)
1083                 return 0;
1084
1085         r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
1086         if (r < 0)
1087                 return r;
1088
1089         return !r;
1090 }
1091
1092 static int service_execute_action(Service *s, FailureAction action, const char *reason, bool log_action_none);
1093
1094 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1095         int r;
1096         assert(s);
1097
1098         if (f != SERVICE_SUCCESS)
1099                 s->result = f;
1100
1101         service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1102
1103         if (s->result != SERVICE_SUCCESS)
1104                 service_execute_action(s, s->failure_action, "failed", false);
1105
1106         if (allow_restart &&
1107             !s->forbid_restart &&
1108             (s->restart == SERVICE_RESTART_ALWAYS ||
1109              (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1110              (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
1111              (s->restart == SERVICE_RESTART_ON_ABNORMAL && !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE)) ||
1112              (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
1113              (s->restart == SERVICE_RESTART_ON_ABORT && IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP)) ||
1114              (s->main_exec_status.code == CLD_EXITED && set_contains(s->restart_force_status.status, INT_TO_PTR(s->main_exec_status.status))) ||
1115              (IN_SET(s->main_exec_status.code, CLD_KILLED, CLD_DUMPED) && set_contains(s->restart_force_status.signal, INT_TO_PTR(s->main_exec_status.status)))) &&
1116             (s->main_exec_status.code != CLD_EXITED || !set_contains(s->restart_prevent_status.status, INT_TO_PTR(s->main_exec_status.status))) &&
1117             (!IN_SET(s->main_exec_status.code, CLD_KILLED, CLD_DUMPED) || !set_contains(s->restart_prevent_status.signal, INT_TO_PTR(s->main_exec_status.status)))) {
1118
1119                 r = service_arm_timer(s, s->restart_usec);
1120                 if (r < 0)
1121                         goto fail;
1122
1123                 service_set_state(s, SERVICE_AUTO_RESTART);
1124         }
1125
1126         s->forbid_restart = false;
1127
1128         /* We want fresh tmpdirs in case service is started again immediately */
1129         exec_runtime_destroy(s->exec_runtime);
1130         s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1131
1132         /* Also, remove the runtime directory in */
1133         exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1134
1135         /* Try to delete the pid file. At this point it will be
1136          * out-of-date, and some software might be confused by it, so
1137          * let's remove it. */
1138         if (s->pid_file)
1139                 unlink_noerrno(s->pid_file);
1140
1141         return;
1142
1143 fail:
1144         log_warning_unit(UNIT(s)->id,
1145                          "%s failed to run install restart timer: %s",
1146                          UNIT(s)->id, strerror(-r));
1147         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1148 }
1149
1150 static void service_enter_stop_post(Service *s, ServiceResult f) {
1151         int r;
1152         assert(s);
1153
1154         if (f != SERVICE_SUCCESS)
1155                 s->result = f;
1156
1157         service_unwatch_control_pid(s);
1158         unit_watch_all_pids(UNIT(s));
1159
1160         s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1161         if (s->control_command) {
1162                 s->control_command_id = SERVICE_EXEC_STOP_POST;
1163
1164                 r = service_spawn(s,
1165                                   s->control_command,
1166                                   true,
1167                                   false,
1168                                   !s->permissions_start_only,
1169                                   !s->root_directory_start_only,
1170                                   true,
1171                                   false,
1172                                   true,
1173                                   &s->control_pid);
1174                 if (r < 0)
1175                         goto fail;
1176
1177                 service_set_state(s, SERVICE_STOP_POST);
1178         } else
1179                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1180
1181         return;
1182
1183 fail:
1184         log_warning_unit(UNIT(s)->id,
1185                          "%s failed to run 'stop-post' task: %s",
1186                          UNIT(s)->id, strerror(-r));
1187         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1188 }
1189
1190 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1191         int r;
1192
1193         assert(s);
1194
1195         if (f != SERVICE_SUCCESS)
1196                 s->result = f;
1197
1198         unit_watch_all_pids(UNIT(s));
1199
1200         r = unit_kill_context(
1201                         UNIT(s),
1202                         &s->kill_context,
1203                         state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM,
1204                         s->main_pid,
1205                         s->control_pid,
1206                         s->main_pid_alien);
1207
1208         if (r < 0)
1209                 goto fail;
1210
1211         if (r > 0) {
1212                 if (s->timeout_stop_usec > 0) {
1213                         r = service_arm_timer(s, s->timeout_stop_usec);
1214                         if (r < 0)
1215                                 goto fail;
1216                 }
1217
1218                 service_set_state(s, state);
1219         } else if (state == SERVICE_STOP_SIGTERM)
1220                 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1221         else if (state == SERVICE_STOP_SIGKILL)
1222                 service_enter_stop_post(s, SERVICE_SUCCESS);
1223         else if (state == SERVICE_FINAL_SIGTERM)
1224                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1225         else
1226                 service_enter_dead(s, SERVICE_SUCCESS, true);
1227
1228         return;
1229
1230 fail:
1231         log_warning_unit(UNIT(s)->id,
1232                          "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1233
1234         if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1235                 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1236         else
1237                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1238 }
1239
1240 static void service_enter_stop(Service *s, ServiceResult f) {
1241         int r;
1242
1243         assert(s);
1244
1245         if (f != SERVICE_SUCCESS)
1246                 s->result = f;
1247
1248         service_unwatch_control_pid(s);
1249         unit_watch_all_pids(UNIT(s));
1250
1251         s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1252         if (s->control_command) {
1253                 s->control_command_id = SERVICE_EXEC_STOP;
1254
1255                 r = service_spawn(s,
1256                                   s->control_command,
1257                                   true,
1258                                   false,
1259                                   !s->permissions_start_only,
1260                                   !s->root_directory_start_only,
1261                                   false,
1262                                   false,
1263                                   true,
1264                                   &s->control_pid);
1265                 if (r < 0)
1266                         goto fail;
1267
1268                 service_set_state(s, SERVICE_STOP);
1269         } else
1270                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1271
1272         return;
1273
1274 fail:
1275         log_warning_unit(UNIT(s)->id,
1276                          "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
1277         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1278 }
1279
1280 static void service_enter_running(Service *s, ServiceResult f) {
1281         int main_pid_ok, cgroup_ok;
1282         assert(s);
1283
1284         if (f != SERVICE_SUCCESS)
1285                 s->result = f;
1286
1287         main_pid_ok = main_pid_good(s);
1288         cgroup_ok = cgroup_good(s);
1289
1290         if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
1291             (s->bus_name_good || s->type != SERVICE_DBUS))
1292                 service_set_state(s, SERVICE_RUNNING);
1293         else if (s->remain_after_exit)
1294                 service_set_state(s, SERVICE_EXITED);
1295         else
1296                 service_enter_stop(s, SERVICE_SUCCESS);
1297 }
1298
1299 static void service_enter_start_post(Service *s) {
1300         int r;
1301         assert(s);
1302
1303         service_unwatch_control_pid(s);
1304         service_reset_watchdog(s);
1305
1306         s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1307         if (s->control_command) {
1308                 s->control_command_id = SERVICE_EXEC_START_POST;
1309
1310                 r = service_spawn(s,
1311                                   s->control_command,
1312                                   true,
1313                                   false,
1314                                   !s->permissions_start_only,
1315                                   !s->root_directory_start_only,
1316                                   false,
1317                                   false,
1318                                   true,
1319                                   &s->control_pid);
1320                 if (r < 0)
1321                         goto fail;
1322
1323                 service_set_state(s, SERVICE_START_POST);
1324         } else
1325                 service_enter_running(s, SERVICE_SUCCESS);
1326
1327         return;
1328
1329 fail:
1330         log_warning_unit(UNIT(s)->id,
1331                          "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1332         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1333 }
1334
1335 static void service_kill_control_processes(Service *s) {
1336         char *p;
1337
1338         if (!UNIT(s)->cgroup_path)
1339                 return;
1340
1341         p = strappenda(UNIT(s)->cgroup_path, "/control");
1342         cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
1343 }
1344
1345 static void service_enter_start(Service *s) {
1346         ExecCommand *c;
1347         pid_t pid;
1348         int r;
1349
1350         assert(s);
1351
1352         assert(s->exec_command[SERVICE_EXEC_START]);
1353         assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
1354
1355         service_unwatch_control_pid(s);
1356         service_unwatch_main_pid(s);
1357
1358         /* We want to ensure that nobody leaks processes from
1359          * START_PRE here, so let's go on a killing spree, People
1360          * should not spawn long running processes from START_PRE. */
1361         service_kill_control_processes(s);
1362
1363         if (s->type == SERVICE_FORKING) {
1364                 s->control_command_id = SERVICE_EXEC_START;
1365                 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1366
1367                 s->main_command = NULL;
1368         } else {
1369                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1370                 s->control_command = NULL;
1371
1372                 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1373         }
1374
1375         r = service_spawn(s,
1376                           c,
1377                           s->type == SERVICE_FORKING || s->type == SERVICE_DBUS ||
1378                             s->type == SERVICE_NOTIFY || s->type == SERVICE_ONESHOT,
1379                           true,
1380                           true,
1381                           true,
1382                           true,
1383                           s->notify_access != NOTIFY_NONE,
1384                           false,
1385                           &pid);
1386         if (r < 0)
1387                 goto fail;
1388
1389         if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
1390                 /* For simple services we immediately start
1391                  * the START_POST binaries. */
1392
1393                 service_set_main_pid(s, pid);
1394                 service_enter_start_post(s);
1395
1396         } else  if (s->type == SERVICE_FORKING) {
1397
1398                 /* For forking services we wait until the start
1399                  * process exited. */
1400
1401                 s->control_pid = pid;
1402                 service_set_state(s, SERVICE_START);
1403
1404         } else if (s->type == SERVICE_ONESHOT ||
1405                    s->type == SERVICE_DBUS ||
1406                    s->type == SERVICE_NOTIFY) {
1407
1408                 /* For oneshot services we wait until the start
1409                  * process exited, too, but it is our main process. */
1410
1411                 /* For D-Bus services we know the main pid right away,
1412                  * but wait for the bus name to appear on the
1413                  * bus. Notify services are similar. */
1414
1415                 service_set_main_pid(s, pid);
1416                 service_set_state(s, SERVICE_START);
1417         } else
1418                 assert_not_reached("Unknown service type");
1419
1420         return;
1421
1422 fail:
1423         log_warning_unit(UNIT(s)->id,
1424                          "%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
1425         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1426 }
1427
1428 static void service_enter_start_pre(Service *s) {
1429         int r;
1430
1431         assert(s);
1432
1433         service_unwatch_control_pid(s);
1434
1435         s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1436         if (s->control_command) {
1437                 /* Before we start anything, let's clear up what might
1438                  * be left from previous runs. */
1439                 service_kill_control_processes(s);
1440
1441                 s->control_command_id = SERVICE_EXEC_START_PRE;
1442
1443                 r = service_spawn(s,
1444                                   s->control_command,
1445                                   true,
1446                                   false,
1447                                   !s->permissions_start_only,
1448                                   !s->root_directory_start_only,
1449                                   true,
1450                                   false,
1451                                   true,
1452                                   &s->control_pid);
1453                 if (r < 0)
1454                         goto fail;
1455
1456                 service_set_state(s, SERVICE_START_PRE);
1457         } else
1458                 service_enter_start(s);
1459
1460         return;
1461
1462 fail:
1463         log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1464         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1465 }
1466
1467 static void service_enter_restart(Service *s) {
1468         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1469         int r;
1470
1471         assert(s);
1472
1473         if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1474                 /* Don't restart things if we are going down anyway */
1475                 log_info_unit(UNIT(s)->id, "Stop job pending for unit, delaying automatic restart.");
1476
1477                 r = service_arm_timer(s, s->restart_usec);
1478                 if (r < 0)
1479                         goto fail;
1480
1481                 return;
1482         }
1483
1484         /* Any units that are bound to this service must also be
1485          * restarted. We use JOB_RESTART (instead of the more obvious
1486          * JOB_START) here so that those dependency jobs will be added
1487          * as well. */
1488         r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
1489         if (r < 0)
1490                 goto fail;
1491
1492         /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1493          * it will be canceled as part of the service_stop() call that
1494          * is executed as part of JOB_RESTART. */
1495
1496         log_debug_unit(UNIT(s)->id, "%s scheduled restart job.", UNIT(s)->id);
1497         return;
1498
1499 fail:
1500         log_warning_unit(UNIT(s)->id,
1501                          "%s failed to schedule restart job: %s",
1502                          UNIT(s)->id, bus_error_message(&error, -r));
1503         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1504 }
1505
1506 static void service_enter_reload(Service *s) {
1507         int r;
1508
1509         assert(s);
1510
1511         service_unwatch_control_pid(s);
1512
1513         s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1514         if (s->control_command) {
1515                 s->control_command_id = SERVICE_EXEC_RELOAD;
1516
1517                 r = service_spawn(s,
1518                                   s->control_command,
1519                                   true,
1520                                   false,
1521                                   !s->permissions_start_only,
1522                                   !s->root_directory_start_only,
1523                                   false,
1524                                   false,
1525                                   true,
1526                                   &s->control_pid);
1527                 if (r < 0)
1528                         goto fail;
1529
1530                 service_set_state(s, SERVICE_RELOAD);
1531         } else
1532                 service_enter_running(s, SERVICE_SUCCESS);
1533
1534         return;
1535
1536 fail:
1537         log_warning_unit(UNIT(s)->id,
1538                          "%s failed to run 'reload' task: %s",
1539                          UNIT(s)->id, strerror(-r));
1540         s->reload_result = SERVICE_FAILURE_RESOURCES;
1541         service_enter_running(s, SERVICE_SUCCESS);
1542 }
1543
1544 static void service_run_next_control(Service *s) {
1545         int r;
1546
1547         assert(s);
1548         assert(s->control_command);
1549         assert(s->control_command->command_next);
1550
1551         assert(s->control_command_id != SERVICE_EXEC_START);
1552
1553         s->control_command = s->control_command->command_next;
1554         service_unwatch_control_pid(s);
1555
1556         r = service_spawn(s,
1557                           s->control_command,
1558                           true,
1559                           false,
1560                           !s->permissions_start_only,
1561                           !s->root_directory_start_only,
1562                           s->control_command_id == SERVICE_EXEC_START_PRE ||
1563                           s->control_command_id == SERVICE_EXEC_STOP_POST,
1564                           false,
1565                           true,
1566                           &s->control_pid);
1567         if (r < 0)
1568                 goto fail;
1569
1570         return;
1571
1572 fail:
1573         log_warning_unit(UNIT(s)->id,
1574                          "%s failed to run next control task: %s",
1575                          UNIT(s)->id, strerror(-r));
1576
1577         if (s->state == SERVICE_START_PRE)
1578                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1579         else if (s->state == SERVICE_STOP)
1580                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1581         else if (s->state == SERVICE_STOP_POST)
1582                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1583         else if (s->state == SERVICE_RELOAD) {
1584                 s->reload_result = SERVICE_FAILURE_RESOURCES;
1585                 service_enter_running(s, SERVICE_SUCCESS);
1586         } else
1587                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1588 }
1589
1590 static void service_run_next_main(Service *s) {
1591         pid_t pid;
1592         int r;
1593
1594         assert(s);
1595         assert(s->main_command);
1596         assert(s->main_command->command_next);
1597         assert(s->type == SERVICE_ONESHOT);
1598
1599         s->main_command = s->main_command->command_next;
1600         service_unwatch_main_pid(s);
1601
1602         r = service_spawn(s,
1603                           s->main_command,
1604                           true,
1605                           true,
1606                           true,
1607                           true,
1608                           true,
1609                           s->notify_access != NOTIFY_NONE,
1610                           false,
1611                           &pid);
1612         if (r < 0)
1613                 goto fail;
1614
1615         service_set_main_pid(s, pid);
1616
1617         return;
1618
1619 fail:
1620         log_warning_unit(UNIT(s)->id,
1621                          "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
1622         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1623 }
1624
1625 static int service_execute_action(Service *s, FailureAction action, const char *reason, bool log_action_none) {
1626         assert(s);
1627
1628         if (action == SERVICE_FAILURE_ACTION_REBOOT ||
1629             action == SERVICE_FAILURE_ACTION_REBOOT_FORCE)
1630                 update_reboot_param_file(s->reboot_arg);
1631
1632         switch (action) {
1633
1634         case SERVICE_FAILURE_ACTION_NONE:
1635                 if (log_action_none)
1636                         log_warning_unit(UNIT(s)->id,
1637                                          "%s %s, refusing to start.", UNIT(s)->id, reason);
1638                 break;
1639
1640         case SERVICE_FAILURE_ACTION_REBOOT: {
1641                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1642                 int r;
1643
1644                 log_warning_unit(UNIT(s)->id,
1645                                  "%s %s, rebooting.", UNIT(s)->id, reason);
1646
1647                 r = manager_add_job_by_name(UNIT(s)->manager, JOB_START,
1648                                             SPECIAL_REBOOT_TARGET, JOB_REPLACE,
1649                                             true, &error, NULL);
1650                 if (r < 0)
1651                         log_error_unit(UNIT(s)->id,
1652                                        "Failed to reboot: %s.", bus_error_message(&error, r));
1653
1654                 break;
1655         }
1656
1657         case SERVICE_FAILURE_ACTION_REBOOT_FORCE:
1658                 log_warning_unit(UNIT(s)->id,
1659                                  "%s %s, forcibly rebooting.", UNIT(s)->id, reason);
1660                 UNIT(s)->manager->exit_code = MANAGER_REBOOT;
1661                 break;
1662
1663         case SERVICE_FAILURE_ACTION_REBOOT_IMMEDIATE:
1664                 log_warning_unit(UNIT(s)->id,
1665                                  "%s %s, rebooting immediately.", UNIT(s)->id, reason);
1666                 sync();
1667                 if (s->reboot_arg) {
1668                         log_info("Rebooting with argument '%s'.", s->reboot_arg);
1669                         syscall(SYS_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
1670                                 LINUX_REBOOT_CMD_RESTART2, s->reboot_arg);
1671                 }
1672
1673                 log_info("Rebooting.");
1674                 reboot(RB_AUTOBOOT);
1675                 break;
1676
1677         default:
1678                 log_error_unit(UNIT(s)->id,
1679                                "failure action=%i", action);
1680                 assert_not_reached("Unknown FailureAction.");
1681         }
1682
1683         return -ECANCELED;
1684 }
1685
1686 static int service_start_limit_test(Service *s) {
1687         assert(s);
1688
1689         if (ratelimit_test(&s->start_limit))
1690                 return 0;
1691
1692         return service_execute_action(s, s->start_limit_action, "start request repeated too quickly", true);
1693 }
1694
1695 static int service_start(Unit *u) {
1696         Service *s = SERVICE(u);
1697         int r;
1698
1699         assert(s);
1700
1701         /* We cannot fulfill this request right now, try again later
1702          * please! */
1703         if (s->state == SERVICE_STOP ||
1704             s->state == SERVICE_STOP_SIGTERM ||
1705             s->state == SERVICE_STOP_SIGKILL ||
1706             s->state == SERVICE_STOP_POST ||
1707             s->state == SERVICE_FINAL_SIGTERM ||
1708             s->state == SERVICE_FINAL_SIGKILL)
1709                 return -EAGAIN;
1710
1711         /* Already on it! */
1712         if (s->state == SERVICE_START_PRE ||
1713             s->state == SERVICE_START ||
1714             s->state == SERVICE_START_POST)
1715                 return 0;
1716
1717         /* A service that will be restarted must be stopped first to
1718          * trigger BindsTo and/or OnFailure dependencies. If a user
1719          * does not want to wait for the holdoff time to elapse, the
1720          * service should be manually restarted, not started. We
1721          * simply return EAGAIN here, so that any start jobs stay
1722          * queued, and assume that the auto restart timer will
1723          * eventually trigger the restart. */
1724         if (s->state == SERVICE_AUTO_RESTART)
1725                 return -EAGAIN;
1726
1727         assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
1728
1729         /* Make sure we don't enter a busy loop of some kind. */
1730         r = service_start_limit_test(s);
1731         if (r < 0) {
1732                 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
1733                 return r;
1734         }
1735
1736         s->result = SERVICE_SUCCESS;
1737         s->reload_result = SERVICE_SUCCESS;
1738         s->main_pid_known = false;
1739         s->main_pid_alien = false;
1740         s->forbid_restart = false;
1741
1742         free(s->status_text);
1743         s->status_text = NULL;
1744         s->status_errno = 0;
1745
1746         service_enter_start_pre(s);
1747         return 0;
1748 }
1749
1750 static int service_stop(Unit *u) {
1751         Service *s = SERVICE(u);
1752
1753         assert(s);
1754
1755         /* Don't create restart jobs from here. */
1756         s->forbid_restart = true;
1757
1758         /* Already on it */
1759         if (s->state == SERVICE_STOP ||
1760             s->state == SERVICE_STOP_SIGTERM ||
1761             s->state == SERVICE_STOP_SIGKILL ||
1762             s->state == SERVICE_STOP_POST ||
1763             s->state == SERVICE_FINAL_SIGTERM ||
1764             s->state == SERVICE_FINAL_SIGKILL)
1765                 return 0;
1766
1767         /* A restart will be scheduled or is in progress. */
1768         if (s->state == SERVICE_AUTO_RESTART) {
1769                 service_set_state(s, SERVICE_DEAD);
1770                 return 0;
1771         }
1772
1773         /* If there's already something running we go directly into
1774          * kill mode. */
1775         if (s->state == SERVICE_START_PRE ||
1776             s->state == SERVICE_START ||
1777             s->state == SERVICE_START_POST ||
1778             s->state == SERVICE_RELOAD) {
1779                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1780                 return 0;
1781         }
1782
1783         assert(s->state == SERVICE_RUNNING ||
1784                s->state == SERVICE_EXITED);
1785
1786         service_enter_stop(s, SERVICE_SUCCESS);
1787         return 0;
1788 }
1789
1790 static int service_reload(Unit *u) {
1791         Service *s = SERVICE(u);
1792
1793         assert(s);
1794
1795         assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1796
1797         service_enter_reload(s);
1798         return 0;
1799 }
1800
1801 _pure_ static bool service_can_reload(Unit *u) {
1802         Service *s = SERVICE(u);
1803
1804         assert(s);
1805
1806         return !!s->exec_command[SERVICE_EXEC_RELOAD];
1807 }
1808
1809 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
1810         Service *s = SERVICE(u);
1811
1812         assert(u);
1813         assert(f);
1814         assert(fds);
1815
1816         unit_serialize_item(u, f, "state", service_state_to_string(s->state));
1817         unit_serialize_item(u, f, "result", service_result_to_string(s->result));
1818         unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
1819
1820         if (s->control_pid > 0)
1821                 unit_serialize_item_format(u, f, "control-pid", PID_FMT,
1822                                            s->control_pid);
1823
1824         if (s->main_pid_known && s->main_pid > 0)
1825                 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
1826
1827         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
1828
1829         if (s->status_text)
1830                 unit_serialize_item(u, f, "status-text", s->status_text);
1831
1832         /* FIXME: There's a minor uncleanliness here: if there are
1833          * multiple commands attached here, we will start from the
1834          * first one again */
1835         if (s->control_command_id >= 0)
1836                 unit_serialize_item(u, f, "control-command",
1837                                     service_exec_command_to_string(s->control_command_id));
1838
1839         if (s->socket_fd >= 0) {
1840                 int copy;
1841
1842                 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
1843                         return copy;
1844
1845                 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
1846         }
1847
1848         if (s->main_exec_status.pid > 0) {
1849                 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT,
1850                                            s->main_exec_status.pid);
1851                 dual_timestamp_serialize(f, "main-exec-status-start",
1852                                          &s->main_exec_status.start_timestamp);
1853                 dual_timestamp_serialize(f, "main-exec-status-exit",
1854                                          &s->main_exec_status.exit_timestamp);
1855
1856                 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1857                         unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
1858                                                    s->main_exec_status.code);
1859                         unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
1860                                                    s->main_exec_status.status);
1861                 }
1862         }
1863         if (dual_timestamp_is_set(&s->watchdog_timestamp))
1864                 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
1865
1866         if (s->forbid_restart)
1867                 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
1868
1869         return 0;
1870 }
1871
1872 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1873         Service *s = SERVICE(u);
1874
1875         assert(u);
1876         assert(key);
1877         assert(value);
1878         assert(fds);
1879
1880         if (streq(key, "state")) {
1881                 ServiceState state;
1882
1883                 state = service_state_from_string(value);
1884                 if (state < 0)
1885                         log_debug_unit(u->id, "Failed to parse state value %s", value);
1886                 else
1887                         s->deserialized_state = state;
1888         } else if (streq(key, "result")) {
1889                 ServiceResult f;
1890
1891                 f = service_result_from_string(value);
1892                 if (f < 0)
1893                         log_debug_unit(u->id, "Failed to parse result value %s", value);
1894                 else if (f != SERVICE_SUCCESS)
1895                         s->result = f;
1896
1897         } else if (streq(key, "reload-result")) {
1898                 ServiceResult f;
1899
1900                 f = service_result_from_string(value);
1901                 if (f < 0)
1902                         log_debug_unit(u->id, "Failed to parse reload result value %s", value);
1903                 else if (f != SERVICE_SUCCESS)
1904                         s->reload_result = f;
1905
1906         } else if (streq(key, "control-pid")) {
1907                 pid_t pid;
1908
1909                 if (parse_pid(value, &pid) < 0)
1910                         log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
1911                 else
1912                         s->control_pid = pid;
1913         } else if (streq(key, "main-pid")) {
1914                 pid_t pid;
1915
1916                 if (parse_pid(value, &pid) < 0)
1917                         log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
1918                 else {
1919                         service_set_main_pid(s, pid);
1920                         unit_watch_pid(UNIT(s), pid);
1921                 }
1922         } else if (streq(key, "main-pid-known")) {
1923                 int b;
1924
1925                 b = parse_boolean(value);
1926                 if (b < 0)
1927                         log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
1928                 else
1929                         s->main_pid_known = b;
1930         } else if (streq(key, "status-text")) {
1931                 char *t;
1932
1933                 t = strdup(value);
1934                 if (!t)
1935                         log_oom();
1936                 else {
1937                         free(s->status_text);
1938                         s->status_text = t;
1939                 }
1940
1941         } else if (streq(key, "control-command")) {
1942                 ServiceExecCommand id;
1943
1944                 id = service_exec_command_from_string(value);
1945                 if (id < 0)
1946                         log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
1947                 else {
1948                         s->control_command_id = id;
1949                         s->control_command = s->exec_command[id];
1950                 }
1951         } else if (streq(key, "socket-fd")) {
1952                 int fd;
1953
1954                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
1955                         log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
1956                 else {
1957
1958                         asynchronous_close(s->socket_fd);
1959                         s->socket_fd = fdset_remove(fds, fd);
1960                 }
1961         } else if (streq(key, "main-exec-status-pid")) {
1962                 pid_t pid;
1963
1964                 if (parse_pid(value, &pid) < 0)
1965                         log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
1966                 else
1967                         s->main_exec_status.pid = pid;
1968         } else if (streq(key, "main-exec-status-code")) {
1969                 int i;
1970
1971                 if (safe_atoi(value, &i) < 0)
1972                         log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
1973                 else
1974                         s->main_exec_status.code = i;
1975         } else if (streq(key, "main-exec-status-status")) {
1976                 int i;
1977
1978                 if (safe_atoi(value, &i) < 0)
1979                         log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
1980                 else
1981                         s->main_exec_status.status = i;
1982         } else if (streq(key, "main-exec-status-start"))
1983                 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
1984         else if (streq(key, "main-exec-status-exit"))
1985                 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
1986         else if (streq(key, "watchdog-timestamp"))
1987                 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
1988         else if (streq(key, "forbid-restart")) {
1989                 int b;
1990
1991                 b = parse_boolean(value);
1992                 if (b < 0)
1993                         log_debug_unit(u->id, "Failed to parse forbid-restart value %s", value);
1994                 else
1995                         s->forbid_restart = b;
1996         } else
1997                 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
1998
1999         return 0;
2000 }
2001
2002 _pure_ static UnitActiveState service_active_state(Unit *u) {
2003         const UnitActiveState *table;
2004
2005         assert(u);
2006
2007         table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2008
2009         return table[SERVICE(u)->state];
2010 }
2011
2012 static const char *service_sub_state_to_string(Unit *u) {
2013         assert(u);
2014
2015         return service_state_to_string(SERVICE(u)->state);
2016 }
2017
2018 static bool service_check_gc(Unit *u) {
2019         Service *s = SERVICE(u);
2020
2021         assert(s);
2022
2023         /* Never clean up services that still have a process around,
2024          * even if the service is formally dead. */
2025         if (cgroup_good(s) > 0 ||
2026             main_pid_good(s) > 0 ||
2027             control_pid_good(s) > 0)
2028                 return true;
2029
2030         return false;
2031 }
2032
2033 _pure_ static bool service_check_snapshot(Unit *u) {
2034         Service *s = SERVICE(u);
2035
2036         assert(s);
2037
2038         return (s->socket_fd < 0);
2039 }
2040
2041 static int service_retry_pid_file(Service *s) {
2042         int r;
2043
2044         assert(s->pid_file);
2045         assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2046
2047         r = service_load_pid_file(s, false);
2048         if (r < 0)
2049                 return r;
2050
2051         service_unwatch_pid_file(s);
2052
2053         service_enter_running(s, SERVICE_SUCCESS);
2054         return 0;
2055 }
2056
2057 static int service_watch_pid_file(Service *s) {
2058         int r;
2059
2060         log_debug_unit(UNIT(s)->id,
2061                        "Setting watch for %s's PID file %s",
2062                        UNIT(s)->id, s->pid_file_pathspec->path);
2063         r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2064         if (r < 0)
2065                 goto fail;
2066
2067         /* the pidfile might have appeared just before we set the watch */
2068         log_debug_unit(UNIT(s)->id,
2069                        "Trying to read %s's PID file %s in case it changed",
2070                        UNIT(s)->id, s->pid_file_pathspec->path);
2071         service_retry_pid_file(s);
2072
2073         return 0;
2074 fail:
2075         log_error_unit(UNIT(s)->id,
2076                        "Failed to set a watch for %s's PID file %s: %s",
2077                        UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
2078         service_unwatch_pid_file(s);
2079         return r;
2080 }
2081
2082 static int service_demand_pid_file(Service *s) {
2083         PathSpec *ps;
2084
2085         assert(s->pid_file);
2086         assert(!s->pid_file_pathspec);
2087
2088         ps = new0(PathSpec, 1);
2089         if (!ps)
2090                 return -ENOMEM;
2091
2092         ps->unit = UNIT(s);
2093         ps->path = strdup(s->pid_file);
2094         if (!ps->path) {
2095                 free(ps);
2096                 return -ENOMEM;
2097         }
2098
2099         path_kill_slashes(ps->path);
2100
2101         /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2102          * keep their PID file open all the time. */
2103         ps->type = PATH_MODIFIED;
2104         ps->inotify_fd = -1;
2105
2106         s->pid_file_pathspec = ps;
2107
2108         return service_watch_pid_file(s);
2109 }
2110
2111 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2112         PathSpec *p = userdata;
2113         Service *s;
2114
2115         assert(p);
2116
2117         s = SERVICE(p->unit);
2118
2119         assert(s);
2120         assert(fd >= 0);
2121         assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2122         assert(s->pid_file_pathspec);
2123         assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2124
2125         log_debug_unit(UNIT(s)->id, "inotify event for %s", UNIT(s)->id);
2126
2127         if (path_spec_fd_event(p, events) < 0)
2128                 goto fail;
2129
2130         if (service_retry_pid_file(s) == 0)
2131                 return 0;
2132
2133         if (service_watch_pid_file(s) < 0)
2134                 goto fail;
2135
2136         return 0;
2137
2138 fail:
2139         service_unwatch_pid_file(s);
2140         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2141         return 0;
2142 }
2143
2144 static void service_notify_cgroup_empty_event(Unit *u) {
2145         Service *s = SERVICE(u);
2146
2147         assert(u);
2148
2149         log_debug_unit(u->id, "%s: cgroup is empty", u->id);
2150
2151         switch (s->state) {
2152
2153                 /* Waiting for SIGCHLD is usually more interesting,
2154                  * because it includes return codes/signals. Which is
2155                  * why we ignore the cgroup events for most cases,
2156                  * except when we don't know pid which to expect the
2157                  * SIGCHLD for. */
2158
2159         case SERVICE_START:
2160         case SERVICE_START_POST:
2161                 /* If we were hoping for the daemon to write its PID file,
2162                  * we can give up now. */
2163                 if (s->pid_file_pathspec) {
2164                         log_warning_unit(u->id,
2165                                          "%s never wrote its PID file. Failing.", UNIT(s)->id);
2166                         service_unwatch_pid_file(s);
2167                         if (s->state == SERVICE_START)
2168                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2169                         else
2170                                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2171                 }
2172                 break;
2173
2174         case SERVICE_RUNNING:
2175                 /* service_enter_running() will figure out what to do */
2176                 service_enter_running(s, SERVICE_SUCCESS);
2177                 break;
2178
2179         case SERVICE_STOP_SIGTERM:
2180         case SERVICE_STOP_SIGKILL:
2181
2182                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2183                         service_enter_stop_post(s, SERVICE_SUCCESS);
2184
2185                 break;
2186
2187         case SERVICE_STOP_POST:
2188         case SERVICE_FINAL_SIGTERM:
2189         case SERVICE_FINAL_SIGKILL:
2190                 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2191                         service_enter_dead(s, SERVICE_SUCCESS, true);
2192
2193                 break;
2194
2195         default:
2196                 ;
2197         }
2198 }
2199
2200 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2201         Service *s = SERVICE(u);
2202         ServiceResult f;
2203
2204         assert(s);
2205         assert(pid >= 0);
2206
2207         if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2208                                      is_clean_exit_lsb(code, status, &s->success_status))
2209                 f = SERVICE_SUCCESS;
2210         else if (code == CLD_EXITED)
2211                 f = SERVICE_FAILURE_EXIT_CODE;
2212         else if (code == CLD_KILLED)
2213                 f = SERVICE_FAILURE_SIGNAL;
2214         else if (code == CLD_DUMPED)
2215                 f = SERVICE_FAILURE_CORE_DUMP;
2216         else
2217                 assert_not_reached("Unknown code");
2218
2219         if (s->main_pid == pid) {
2220                 /* Forking services may occasionally move to a new PID.
2221                  * As long as they update the PID file before exiting the old
2222                  * PID, they're fine. */
2223                 if (service_load_pid_file(s, false) == 0)
2224                         return;
2225
2226                 s->main_pid = 0;
2227                 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2228
2229                 if (s->main_command) {
2230                         /* If this is not a forking service than the
2231                          * main process got started and hence we copy
2232                          * the exit status so that it is recorded both
2233                          * as main and as control process exit
2234                          * status */
2235
2236                         s->main_command->exec_status = s->main_exec_status;
2237
2238                         if (s->main_command->ignore)
2239                                 f = SERVICE_SUCCESS;
2240                 } else if (s->exec_command[SERVICE_EXEC_START]) {
2241
2242                         /* If this is a forked process, then we should
2243                          * ignore the return value if this was
2244                          * configured for the starter process */
2245
2246                         if (s->exec_command[SERVICE_EXEC_START]->ignore)
2247                                 f = SERVICE_SUCCESS;
2248                 }
2249
2250                 log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2251                            u->id,
2252                            "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
2253                                   u->id, sigchld_code_to_string(code), status,
2254                                   strna(code == CLD_EXITED
2255                                         ? exit_status_to_string(status, EXIT_STATUS_FULL)
2256                                         : signal_to_string(status)),
2257                            "EXIT_CODE=%s", sigchld_code_to_string(code),
2258                            "EXIT_STATUS=%i", status,
2259                            NULL);
2260
2261                 if (f != SERVICE_SUCCESS)
2262                         s->result = f;
2263
2264                 if (s->main_command &&
2265                     s->main_command->command_next &&
2266                     f == SERVICE_SUCCESS) {
2267
2268                         /* There is another command to *
2269                          * execute, so let's do that. */
2270
2271                         log_debug_unit(u->id,
2272                                        "%s running next main command for state %s",
2273                                        u->id, service_state_to_string(s->state));
2274                         service_run_next_main(s);
2275
2276                 } else {
2277
2278                         /* The service exited, so the service is officially
2279                          * gone. */
2280                         s->main_command = NULL;
2281
2282                         switch (s->state) {
2283
2284                         case SERVICE_START_POST:
2285                         case SERVICE_RELOAD:
2286                         case SERVICE_STOP:
2287                                 /* Need to wait until the operation is
2288                                  * done */
2289                                 break;
2290
2291                         case SERVICE_START:
2292                                 if (s->type == SERVICE_ONESHOT) {
2293                                         /* This was our main goal, so let's go on */
2294                                         if (f == SERVICE_SUCCESS)
2295                                                 service_enter_start_post(s);
2296                                         else
2297                                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2298                                         break;
2299                                 }
2300
2301                                 /* Fall through */
2302
2303                         case SERVICE_RUNNING:
2304                                 service_enter_running(s, f);
2305                                 break;
2306
2307                         case SERVICE_STOP_SIGTERM:
2308                         case SERVICE_STOP_SIGKILL:
2309
2310                                 if (!control_pid_good(s))
2311                                         service_enter_stop_post(s, f);
2312
2313                                 /* If there is still a control process, wait for that first */
2314                                 break;
2315
2316                         case SERVICE_STOP_POST:
2317                         case SERVICE_FINAL_SIGTERM:
2318                         case SERVICE_FINAL_SIGKILL:
2319
2320                                 if (!control_pid_good(s))
2321                                         service_enter_dead(s, f, true);
2322                                 break;
2323
2324                         default:
2325                                 assert_not_reached("Uh, main process died at wrong time.");
2326                         }
2327                 }
2328
2329         } else if (s->control_pid == pid) {
2330                 s->control_pid = 0;
2331
2332                 if (s->control_command) {
2333                         exec_status_exit(&s->control_command->exec_status,
2334                                          &s->exec_context, pid, code, status);
2335
2336                         if (s->control_command->ignore)
2337                                 f = SERVICE_SUCCESS;
2338                 }
2339
2340                 log_full_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
2341                               "%s: control process exited, code=%s status=%i",
2342                               u->id, sigchld_code_to_string(code), status);
2343
2344                 if (f != SERVICE_SUCCESS)
2345                         s->result = f;
2346
2347                 /* Immediately get rid of the cgroup, so that the
2348                  * kernel doesn't delay the cgroup empty messages for
2349                  * the service cgroup any longer than necessary */
2350                 service_kill_control_processes(s);
2351
2352                 if (s->control_command &&
2353                     s->control_command->command_next &&
2354                     f == SERVICE_SUCCESS) {
2355
2356                         /* There is another command to *
2357                          * execute, so let's do that. */
2358
2359                         log_debug_unit(u->id,
2360                                        "%s running next control command for state %s",
2361                                        u->id, service_state_to_string(s->state));
2362                         service_run_next_control(s);
2363
2364                 } else {
2365                         /* No further commands for this step, so let's
2366                          * figure out what to do next */
2367
2368                         s->control_command = NULL;
2369                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2370
2371                         log_debug_unit(u->id,
2372                                        "%s got final SIGCHLD for state %s",
2373                                        u->id, service_state_to_string(s->state));
2374
2375                         switch (s->state) {
2376
2377                         case SERVICE_START_PRE:
2378                                 if (f == SERVICE_SUCCESS)
2379                                         service_enter_start(s);
2380                                 else
2381                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2382                                 break;
2383
2384                         case SERVICE_START:
2385                                 if (s->type != SERVICE_FORKING)
2386                                         /* Maybe spurious event due to a reload that changed the type? */
2387                                         break;
2388
2389                                 if (f != SERVICE_SUCCESS) {
2390                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2391                                         break;
2392                                 }
2393
2394                                 if (s->pid_file) {
2395                                         bool has_start_post;
2396                                         int r;
2397
2398                                         /* Let's try to load the pid file here if we can.
2399                                          * The PID file might actually be created by a START_POST
2400                                          * script. In that case don't worry if the loading fails. */
2401
2402                                         has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2403                                         r = service_load_pid_file(s, !has_start_post);
2404                                         if (!has_start_post && r < 0) {
2405                                                 r = service_demand_pid_file(s);
2406                                                 if (r < 0 || !cgroup_good(s))
2407                                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2408                                                 break;
2409                                         }
2410                                 } else
2411                                         service_search_main_pid(s);
2412
2413                                 service_enter_start_post(s);
2414                                 break;
2415
2416                         case SERVICE_START_POST:
2417                                 if (f != SERVICE_SUCCESS) {
2418                                         service_enter_stop(s, f);
2419                                         break;
2420                                 }
2421
2422                                 if (s->pid_file) {
2423                                         int r;
2424
2425                                         r = service_load_pid_file(s, true);
2426                                         if (r < 0) {
2427                                                 r = service_demand_pid_file(s);
2428                                                 if (r < 0 || !cgroup_good(s))
2429                                                         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2430                                                 break;
2431                                         }
2432                                 } else
2433                                         service_search_main_pid(s);
2434
2435                                 service_enter_running(s, SERVICE_SUCCESS);
2436                                 break;
2437
2438                         case SERVICE_RELOAD:
2439                                 if (f == SERVICE_SUCCESS) {
2440                                         service_load_pid_file(s, true);
2441                                         service_search_main_pid(s);
2442                                 }
2443
2444                                 s->reload_result = f;
2445                                 service_enter_running(s, SERVICE_SUCCESS);
2446                                 break;
2447
2448                         case SERVICE_STOP:
2449                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2450                                 break;
2451
2452                         case SERVICE_STOP_SIGTERM:
2453                         case SERVICE_STOP_SIGKILL:
2454                                 if (main_pid_good(s) <= 0)
2455                                         service_enter_stop_post(s, f);
2456
2457                                 /* If there is still a service
2458                                  * process around, wait until
2459                                  * that one quit, too */
2460                                 break;
2461
2462                         case SERVICE_STOP_POST:
2463                         case SERVICE_FINAL_SIGTERM:
2464                         case SERVICE_FINAL_SIGKILL:
2465                                 if (main_pid_good(s) <= 0)
2466                                         service_enter_dead(s, f, true);
2467                                 break;
2468
2469                         default:
2470                                 assert_not_reached("Uh, control process died at wrong time.");
2471                         }
2472                 }
2473         }
2474
2475         /* Notify clients about changed exit status */
2476         unit_add_to_dbus_queue(u);
2477
2478         /* We got one SIGCHLD for the service, let's watch all
2479          * processes that are now running of the service, and watch
2480          * that. Among the PIDs we then watch will be children
2481          * reassigned to us, which hopefully allows us to identify
2482          * when all children are gone */
2483         unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2484         unit_watch_all_pids(u);
2485
2486         /* If the PID set is empty now, then let's finish this off */
2487         if (set_isempty(u->pids))
2488                 service_notify_cgroup_empty_event(u);
2489 }
2490
2491 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2492         Service *s = SERVICE(userdata);
2493
2494         assert(s);
2495         assert(source == s->timer_event_source);
2496
2497         switch (s->state) {
2498
2499         case SERVICE_START_PRE:
2500         case SERVICE_START:
2501                 log_warning_unit(UNIT(s)->id,
2502                                  "%s %s operation timed out. Terminating.",
2503                                  UNIT(s)->id,
2504                                  s->state == SERVICE_START ? "start" : "start-pre");
2505                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2506                 break;
2507
2508         case SERVICE_START_POST:
2509                 log_warning_unit(UNIT(s)->id,
2510                                  "%s start-post operation timed out. Stopping.", UNIT(s)->id);
2511                 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2512                 break;
2513
2514         case SERVICE_RELOAD:
2515                 log_warning_unit(UNIT(s)->id,
2516                                  "%s reload operation timed out. Stopping.", UNIT(s)->id);
2517                 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2518                 service_enter_running(s, SERVICE_SUCCESS);
2519                 break;
2520
2521         case SERVICE_STOP:
2522                 log_warning_unit(UNIT(s)->id,
2523                                  "%s stopping timed out. Terminating.", UNIT(s)->id);
2524                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2525                 break;
2526
2527         case SERVICE_STOP_SIGTERM:
2528                 if (s->kill_context.send_sigkill) {
2529                         log_warning_unit(UNIT(s)->id,
2530                                          "%s stop-sigterm timed out. Killing.", UNIT(s)->id);
2531                         service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2532                 } else {
2533                         log_warning_unit(UNIT(s)->id,
2534                                          "%s stop-sigterm timed out. Skipping SIGKILL.", UNIT(s)->id);
2535                         service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2536                 }
2537
2538                 break;
2539
2540         case SERVICE_STOP_SIGKILL:
2541                 /* Uh, we sent a SIGKILL and it is still not gone?
2542                  * Must be something we cannot kill, so let's just be
2543                  * weirded out and continue */
2544
2545                 log_warning_unit(UNIT(s)->id,
2546                                  "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2547                 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2548                 break;
2549
2550         case SERVICE_STOP_POST:
2551                 log_warning_unit(UNIT(s)->id,
2552                                  "%s stop-post timed out. Terminating.", UNIT(s)->id);
2553                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2554                 break;
2555
2556         case SERVICE_FINAL_SIGTERM:
2557                 if (s->kill_context.send_sigkill) {
2558                         log_warning_unit(UNIT(s)->id,
2559                                          "%s stop-final-sigterm timed out. Killing.", UNIT(s)->id);
2560                         service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2561                 } else {
2562                         log_warning_unit(UNIT(s)->id,
2563                                          "%s stop-final-sigterm timed out. Skipping SIGKILL. Entering failed mode.",
2564                                          UNIT(s)->id);
2565                         service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2566                 }
2567
2568                 break;
2569
2570         case SERVICE_FINAL_SIGKILL:
2571                 log_warning_unit(UNIT(s)->id,
2572                                  "%s still around after final SIGKILL. Entering failed mode.", UNIT(s)->id);
2573                 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2574                 break;
2575
2576         case SERVICE_AUTO_RESTART:
2577                 log_info_unit(UNIT(s)->id,
2578                               s->restart_usec > 0 ?
2579                               "%s holdoff time over, scheduling restart." :
2580                               "%s has no holdoff time, scheduling restart.",
2581                               UNIT(s)->id);
2582                 service_enter_restart(s);
2583                 break;
2584
2585         default:
2586                 assert_not_reached("Timeout at wrong time.");
2587         }
2588
2589         return 0;
2590 }
2591
2592 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2593         Service *s = SERVICE(userdata);
2594         char t[FORMAT_TIMESPAN_MAX];
2595
2596         assert(s);
2597         assert(source == s->watchdog_event_source);
2598
2599         log_error_unit(UNIT(s)->id,
2600                        "%s watchdog timeout (limit %s)!",
2601                        UNIT(s)->id,
2602                        format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2603         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_WATCHDOG);
2604
2605         return 0;
2606 }
2607
2608 static void service_notify_message(Unit *u, pid_t pid, char **tags) {
2609         Service *s = SERVICE(u);
2610         const char *e;
2611         bool notify_dbus = false;
2612
2613         assert(u);
2614
2615         log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT" (%s...)",
2616                        u->id, pid, tags && *tags ? tags[0] : "(empty)");
2617
2618         if (s->notify_access == NOTIFY_NONE) {
2619                 log_warning_unit(u->id,
2620                                  "%s: Got notification message from PID "PID_FMT", but reception is disabled.",
2621                                  u->id, pid);
2622                 return;
2623         }
2624
2625         if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2626                 if (s->main_pid != 0)
2627                         log_warning_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, u->id, pid, s->main_pid);
2628                 else
2629                         log_debug_unit(u->id, "%s: Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", u->id, pid);
2630                 return;
2631         }
2632
2633         /* Interpret MAINPID= */
2634         e = strv_find_prefix(tags, "MAINPID=");
2635         if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2636                 if (parse_pid(e + 8, &pid) < 0)
2637                         log_warning_unit(u->id, "Failed to parse MAINPID= field in notification message: %s", e);
2638                 else {
2639                         log_debug_unit(u->id, "%s: got %s", u->id, e);
2640                         service_set_main_pid(s, pid);
2641                         unit_watch_pid(UNIT(s), pid);
2642                         notify_dbus = true;
2643                 }
2644         }
2645
2646         /* Interpret READY= */
2647         if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START && strv_find(tags, "READY=1")) {
2648                 log_debug_unit(u->id, "%s: got READY=1", u->id);
2649                 service_enter_start_post(s);
2650                 notify_dbus = true;
2651         }
2652
2653         /* Interpret STATUS= */
2654         e = strv_find_prefix(tags, "STATUS=");
2655         if (e) {
2656                 char *t;
2657
2658                 if (e[7]) {
2659                         if (!utf8_is_valid(e+7)) {
2660                                 log_warning_unit(u->id, "Status message in notification is not UTF-8 clean.");
2661                                 return;
2662                         }
2663
2664                         log_debug_unit(u->id, "%s: got %s", u->id, e);
2665
2666                         t = strdup(e+7);
2667                         if (!t) {
2668                                 log_oom();
2669                                 return;
2670                         }
2671
2672                 } else
2673                         t = NULL;
2674
2675                 if (!streq_ptr(s->status_text, t)) {
2676                         free(s->status_text);
2677                         s->status_text = t;
2678                         notify_dbus = true;
2679                 } else
2680                         free(t);
2681         }
2682
2683         /* Interpret ERRNO= */
2684         e = strv_find_prefix(tags, "ERRNO=");
2685         if (e) {
2686                 int status_errno;
2687
2688                 if (safe_atoi(e + 6, &status_errno) < 0 || status_errno < 0)
2689                         log_warning_unit(u->id, "Failed to parse ERRNO= field in notification message: %s", e);
2690                 else {
2691                         log_debug_unit(u->id, "%s: got %s", u->id, e);
2692
2693                         if (s->status_errno != status_errno) {
2694                                 s->status_errno = status_errno;
2695                                 notify_dbus = true;
2696                         }
2697                 }
2698         }
2699
2700         /* Interpret WATCHDOG= */
2701         if (strv_find(tags, "WATCHDOG=1")) {
2702                 log_debug_unit(u->id, "%s: got WATCHDOG=1", u->id);
2703                 service_reset_watchdog(s);
2704         }
2705
2706         /* Notify clients about changed status or main pid */
2707         if (notify_dbus)
2708                 unit_add_to_dbus_queue(u);
2709 }
2710
2711 static int service_get_timeout(Unit *u, uint64_t *timeout) {
2712         Service *s = SERVICE(u);
2713         int r;
2714
2715         if (!s->timer_event_source)
2716                 return 0;
2717
2718         r = sd_event_source_get_time(s->timer_event_source, timeout);
2719         if (r < 0)
2720                 return r;
2721
2722         return 1;
2723 }
2724
2725 static void service_bus_name_owner_change(
2726                 Unit *u,
2727                 const char *name,
2728                 const char *old_owner,
2729                 const char *new_owner) {
2730
2731         Service *s = SERVICE(u);
2732         int r;
2733
2734         assert(s);
2735         assert(name);
2736
2737         assert(streq(s->bus_name, name));
2738         assert(old_owner || new_owner);
2739
2740         if (old_owner && new_owner)
2741                 log_debug_unit(u->id,
2742                                "%s's D-Bus name %s changed owner from %s to %s",
2743                                u->id, name, old_owner, new_owner);
2744         else if (old_owner)
2745                 log_debug_unit(u->id,
2746                                "%s's D-Bus name %s no longer registered by %s",
2747                                u->id, name, old_owner);
2748         else
2749                 log_debug_unit(u->id,
2750                                "%s's D-Bus name %s now registered by %s",
2751                                u->id, name, new_owner);
2752
2753         s->bus_name_good = !!new_owner;
2754
2755         if (s->type == SERVICE_DBUS) {
2756
2757                 /* service_enter_running() will figure out what to
2758                  * do */
2759                 if (s->state == SERVICE_RUNNING)
2760                         service_enter_running(s, SERVICE_SUCCESS);
2761                 else if (s->state == SERVICE_START && new_owner)
2762                         service_enter_start_post(s);
2763
2764         } else if (new_owner &&
2765                    s->main_pid <= 0 &&
2766                    (s->state == SERVICE_START ||
2767                     s->state == SERVICE_START_POST ||
2768                     s->state == SERVICE_RUNNING ||
2769                     s->state == SERVICE_RELOAD)) {
2770
2771                 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
2772                 pid_t pid;
2773
2774                 /* Try to acquire PID from bus service */
2775
2776                 r = sd_bus_get_owner(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
2777                 if (r >= 0)
2778                         r = sd_bus_creds_get_pid(creds, &pid);
2779                 if (r >= 0) {
2780                         log_debug_unit(u->id, "%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
2781
2782                         service_set_main_pid(s, pid);
2783                         unit_watch_pid(UNIT(s), pid);
2784                 }
2785         }
2786 }
2787
2788 int service_set_socket_fd(Service *s, int fd, Socket *sock) {
2789         _cleanup_free_ char *peer = NULL;
2790         int r;
2791
2792         assert(s);
2793         assert(fd >= 0);
2794
2795         /* This is called by the socket code when instantiating a new
2796          * service for a stream socket and the socket needs to be
2797          * configured. */
2798
2799         if (UNIT(s)->load_state != UNIT_LOADED)
2800                 return -EINVAL;
2801
2802         if (s->socket_fd >= 0)
2803                 return -EBUSY;
2804
2805         if (s->state != SERVICE_DEAD)
2806                 return -EAGAIN;
2807
2808         if (getpeername_pretty(fd, &peer) >= 0) {
2809
2810                 if (UNIT(s)->description) {
2811                         _cleanup_free_ char *a;
2812
2813                         a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
2814                         if (!a)
2815                                 return -ENOMEM;
2816
2817                         r = unit_set_description(UNIT(s), a);
2818                 }  else
2819                         r = unit_set_description(UNIT(s), peer);
2820
2821                 if (r < 0)
2822                         return r;
2823         }
2824
2825         s->socket_fd = fd;
2826
2827         unit_ref_set(&s->accept_socket, UNIT(sock));
2828
2829         return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
2830 }
2831
2832 static void service_reset_failed(Unit *u) {
2833         Service *s = SERVICE(u);
2834
2835         assert(s);
2836
2837         if (s->state == SERVICE_FAILED)
2838                 service_set_state(s, SERVICE_DEAD);
2839
2840         s->result = SERVICE_SUCCESS;
2841         s->reload_result = SERVICE_SUCCESS;
2842
2843         RATELIMIT_RESET(s->start_limit);
2844 }
2845
2846 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2847         Service *s = SERVICE(u);
2848
2849         return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
2850 }
2851
2852 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
2853         [SERVICE_DEAD] = "dead",
2854         [SERVICE_START_PRE] = "start-pre",
2855         [SERVICE_START] = "start",
2856         [SERVICE_START_POST] = "start-post",
2857         [SERVICE_RUNNING] = "running",
2858         [SERVICE_EXITED] = "exited",
2859         [SERVICE_RELOAD] = "reload",
2860         [SERVICE_STOP] = "stop",
2861         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
2862         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
2863         [SERVICE_STOP_POST] = "stop-post",
2864         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
2865         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
2866         [SERVICE_FAILED] = "failed",
2867         [SERVICE_AUTO_RESTART] = "auto-restart",
2868 };
2869
2870 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
2871
2872 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
2873         [SERVICE_RESTART_NO] = "no",
2874         [SERVICE_RESTART_ON_SUCCESS] = "on-success",
2875         [SERVICE_RESTART_ON_FAILURE] = "on-failure",
2876         [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
2877         [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
2878         [SERVICE_RESTART_ON_ABORT] = "on-abort",
2879         [SERVICE_RESTART_ALWAYS] = "always",
2880 };
2881
2882 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2883
2884 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
2885         [SERVICE_SIMPLE] = "simple",
2886         [SERVICE_FORKING] = "forking",
2887         [SERVICE_ONESHOT] = "oneshot",
2888         [SERVICE_DBUS] = "dbus",
2889         [SERVICE_NOTIFY] = "notify",
2890         [SERVICE_IDLE] = "idle"
2891 };
2892
2893 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
2894
2895 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
2896         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
2897         [SERVICE_EXEC_START] = "ExecStart",
2898         [SERVICE_EXEC_START_POST] = "ExecStartPost",
2899         [SERVICE_EXEC_RELOAD] = "ExecReload",
2900         [SERVICE_EXEC_STOP] = "ExecStop",
2901         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
2902 };
2903
2904 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
2905
2906 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
2907         [NOTIFY_NONE] = "none",
2908         [NOTIFY_MAIN] = "main",
2909         [NOTIFY_ALL] = "all"
2910 };
2911
2912 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
2913
2914 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
2915         [SERVICE_SUCCESS] = "success",
2916         [SERVICE_FAILURE_RESOURCES] = "resources",
2917         [SERVICE_FAILURE_TIMEOUT] = "timeout",
2918         [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
2919         [SERVICE_FAILURE_SIGNAL] = "signal",
2920         [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
2921         [SERVICE_FAILURE_WATCHDOG] = "watchdog",
2922         [SERVICE_FAILURE_START_LIMIT] = "start-limit"
2923 };
2924
2925 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
2926
2927 static const char* const failure_action_table[_SERVICE_FAILURE_ACTION_MAX] = {
2928         [SERVICE_FAILURE_ACTION_NONE] = "none",
2929         [SERVICE_FAILURE_ACTION_REBOOT] = "reboot",
2930         [SERVICE_FAILURE_ACTION_REBOOT_FORCE] = "reboot-force",
2931         [SERVICE_FAILURE_ACTION_REBOOT_IMMEDIATE] = "reboot-immediate"
2932 };
2933 DEFINE_STRING_TABLE_LOOKUP(failure_action, FailureAction);
2934
2935 const UnitVTable service_vtable = {
2936         .object_size = sizeof(Service),
2937         .exec_context_offset = offsetof(Service, exec_context),
2938         .cgroup_context_offset = offsetof(Service, cgroup_context),
2939         .kill_context_offset = offsetof(Service, kill_context),
2940         .exec_runtime_offset = offsetof(Service, exec_runtime),
2941
2942         .sections =
2943                 "Unit\0"
2944                 "Service\0"
2945                 "Install\0",
2946         .private_section = "Service",
2947
2948         .init = service_init,
2949         .done = service_done,
2950         .load = service_load,
2951
2952         .coldplug = service_coldplug,
2953
2954         .dump = service_dump,
2955
2956         .start = service_start,
2957         .stop = service_stop,
2958         .reload = service_reload,
2959
2960         .can_reload = service_can_reload,
2961
2962         .kill = service_kill,
2963
2964         .serialize = service_serialize,
2965         .deserialize_item = service_deserialize_item,
2966
2967         .active_state = service_active_state,
2968         .sub_state_to_string = service_sub_state_to_string,
2969
2970         .check_gc = service_check_gc,
2971         .check_snapshot = service_check_snapshot,
2972
2973         .sigchld_event = service_sigchld_event,
2974
2975         .reset_failed = service_reset_failed,
2976
2977         .notify_cgroup_empty = service_notify_cgroup_empty_event,
2978         .notify_message = service_notify_message,
2979
2980         .bus_name_owner_change = service_bus_name_owner_change,
2981
2982         .bus_interface = "org.freedesktop.systemd1.Service",
2983         .bus_vtable = bus_service_vtable,
2984         .bus_set_property = bus_service_set_property,
2985         .bus_commit_properties = bus_service_commit_properties,
2986
2987         .get_timeout = service_get_timeout,
2988         .can_transient = true,
2989
2990         .status_message_formats = {
2991                 .starting_stopping = {
2992                         [0] = "Starting %s...",
2993                         [1] = "Stopping %s...",
2994                 },
2995                 .finished_start_job = {
2996                         [JOB_DONE]       = "Started %s.",
2997                         [JOB_FAILED]     = "Failed to start %s.",
2998                         [JOB_DEPENDENCY] = "Dependency failed for %s.",
2999                         [JOB_TIMEOUT]    = "Timed out starting %s.",
3000                 },
3001                 .finished_stop_job = {
3002                         [JOB_DONE]       = "Stopped %s.",
3003                         [JOB_FAILED]     = "Stopped (with error) %s.",
3004                         [JOB_TIMEOUT]    = "Timed out stopping %s.",
3005                 },
3006         },
3007 };