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