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