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