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