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