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