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