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