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