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