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