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