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