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