1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <errno.h>
4 #include <sys/stat.h>
5 #include <sys/types.h>
6 #include <unistd.h>
7 
8 #include "sd-messages.h"
9 
10 #include "alloc-util.h"
11 #include "async.h"
12 #include "bus-error.h"
13 #include "bus-kernel.h"
14 #include "bus-util.h"
15 #include "chase-symlinks.h"
16 #include "dbus-service.h"
17 #include "dbus-unit.h"
18 #include "def.h"
19 #include "env-util.h"
20 #include "escape.h"
21 #include "exit-status.h"
22 #include "fd-util.h"
23 #include "fileio.h"
24 #include "format-util.h"
25 #include "load-dropin.h"
26 #include "load-fragment.h"
27 #include "log.h"
28 #include "manager.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
32 #include "random-util.h"
33 #include "serialize.h"
34 #include "service.h"
35 #include "signal-util.h"
36 #include "special.h"
37 #include "stdio-util.h"
38 #include "string-table.h"
39 #include "string-util.h"
40 #include "strv.h"
41 #include "unit-name.h"
42 #include "unit.h"
43 #include "utf8.h"
44 #include "util.h"
45 
46 #define service_spawn(...) service_spawn_internal(__func__, __VA_ARGS__)
47 
48 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
49         [SERVICE_DEAD] = UNIT_INACTIVE,
50         [SERVICE_CONDITION] = UNIT_ACTIVATING,
51         [SERVICE_START_PRE] = UNIT_ACTIVATING,
52         [SERVICE_START] = UNIT_ACTIVATING,
53         [SERVICE_START_POST] = UNIT_ACTIVATING,
54         [SERVICE_RUNNING] = UNIT_ACTIVE,
55         [SERVICE_EXITED] = UNIT_ACTIVE,
56         [SERVICE_RELOAD] = UNIT_RELOADING,
57         [SERVICE_STOP] = UNIT_DEACTIVATING,
58         [SERVICE_STOP_WATCHDOG] = UNIT_DEACTIVATING,
59         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
60         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
61         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
62         [SERVICE_FINAL_WATCHDOG] = UNIT_DEACTIVATING,
63         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
64         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
65         [SERVICE_FAILED] = UNIT_FAILED,
66         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
67         [SERVICE_CLEANING] = UNIT_MAINTENANCE,
68 };
69 
70 /* For Type=idle we never want to delay any other jobs, hence we
71  * consider idle jobs active as soon as we start working on them */
72 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
73         [SERVICE_DEAD] = UNIT_INACTIVE,
74         [SERVICE_CONDITION] = UNIT_ACTIVE,
75         [SERVICE_START_PRE] = UNIT_ACTIVE,
76         [SERVICE_START] = UNIT_ACTIVE,
77         [SERVICE_START_POST] = UNIT_ACTIVE,
78         [SERVICE_RUNNING] = UNIT_ACTIVE,
79         [SERVICE_EXITED] = UNIT_ACTIVE,
80         [SERVICE_RELOAD] = UNIT_RELOADING,
81         [SERVICE_STOP] = UNIT_DEACTIVATING,
82         [SERVICE_STOP_WATCHDOG] = UNIT_DEACTIVATING,
83         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
84         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
85         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
86         [SERVICE_FINAL_WATCHDOG] = UNIT_DEACTIVATING,
87         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
88         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
89         [SERVICE_FAILED] = UNIT_FAILED,
90         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
91         [SERVICE_CLEANING] = UNIT_MAINTENANCE,
92 };
93 
94 static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
95 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
96 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
97 static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
98 
99 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
100 static void service_enter_reload_by_notify(Service *s);
101 
service_init(Unit * u)102 static void service_init(Unit *u) {
103         Service *s = SERVICE(u);
104 
105         assert(u);
106         assert(u->load_state == UNIT_STUB);
107 
108         s->timeout_start_usec = u->manager->default_timeout_start_usec;
109         s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
110         s->timeout_abort_usec = u->manager->default_timeout_abort_usec;
111         s->timeout_abort_set = u->manager->default_timeout_abort_set;
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         s->exec_context.keyring_mode = MANAGER_IS_SYSTEM(u->manager) ?
122                 EXEC_KEYRING_PRIVATE : EXEC_KEYRING_INHERIT;
123 
124         s->watchdog_original_usec = USEC_INFINITY;
125 
126         s->oom_policy = _OOM_POLICY_INVALID;
127 }
128 
service_unwatch_control_pid(Service * s)129 static void service_unwatch_control_pid(Service *s) {
130         assert(s);
131 
132         if (s->control_pid <= 0)
133                 return;
134 
135         unit_unwatch_pid(UNIT(s), TAKE_PID(s->control_pid));
136 }
137 
service_unwatch_main_pid(Service * s)138 static void service_unwatch_main_pid(Service *s) {
139         assert(s);
140 
141         if (s->main_pid <= 0)
142                 return;
143 
144         unit_unwatch_pid(UNIT(s), TAKE_PID(s->main_pid));
145 }
146 
service_unwatch_pid_file(Service * s)147 static void service_unwatch_pid_file(Service *s) {
148         if (!s->pid_file_pathspec)
149                 return;
150 
151         log_unit_debug(UNIT(s), "Stopping watch for PID file %s", s->pid_file_pathspec->path);
152         path_spec_unwatch(s->pid_file_pathspec);
153         path_spec_done(s->pid_file_pathspec);
154         s->pid_file_pathspec = mfree(s->pid_file_pathspec);
155 }
156 
service_set_main_pid(Service * s,pid_t pid)157 static int service_set_main_pid(Service *s, pid_t pid) {
158         assert(s);
159 
160         if (pid <= 1)
161                 return -EINVAL;
162 
163         if (pid == getpid_cached())
164                 return -EINVAL;
165 
166         if (s->main_pid == pid && s->main_pid_known)
167                 return 0;
168 
169         if (s->main_pid != pid) {
170                 service_unwatch_main_pid(s);
171                 exec_status_start(&s->main_exec_status, pid);
172         }
173 
174         s->main_pid = pid;
175         s->main_pid_known = true;
176         s->main_pid_alien = pid_is_my_child(pid) == 0;
177 
178         if (s->main_pid_alien)
179                 log_unit_warning(UNIT(s), "Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.", pid);
180 
181         return 0;
182 }
183 
service_close_socket_fd(Service * s)184 void service_close_socket_fd(Service *s) {
185         assert(s);
186 
187         /* Undo the effect of service_set_socket_fd(). */
188 
189         s->socket_fd = asynchronous_close(s->socket_fd);
190 
191         if (UNIT_ISSET(s->accept_socket)) {
192                 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
193                 unit_ref_unset(&s->accept_socket);
194         }
195 
196         s->socket_peer = socket_peer_unref(s->socket_peer);
197 }
198 
service_stop_watchdog(Service * s)199 static void service_stop_watchdog(Service *s) {
200         assert(s);
201 
202         s->watchdog_event_source = sd_event_source_disable_unref(s->watchdog_event_source);
203         s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
204 }
205 
service_start_watchdog(Service * s)206 static void service_start_watchdog(Service *s) {
207         usec_t watchdog_usec;
208         int r;
209 
210         assert(s);
211 
212         watchdog_usec = service_get_watchdog_usec(s);
213         if (!timestamp_is_set(watchdog_usec)) {
214                 service_stop_watchdog(s);
215                 return;
216         }
217 
218         if (s->watchdog_event_source) {
219                 r = sd_event_source_set_time(s->watchdog_event_source, usec_add(s->watchdog_timestamp.monotonic, watchdog_usec));
220                 if (r < 0) {
221                         log_unit_warning_errno(UNIT(s), r, "Failed to reset watchdog timer: %m");
222                         return;
223                 }
224 
225                 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
226         } else {
227                 r = sd_event_add_time(
228                                 UNIT(s)->manager->event,
229                                 &s->watchdog_event_source,
230                                 CLOCK_MONOTONIC,
231                                 usec_add(s->watchdog_timestamp.monotonic, watchdog_usec), 0,
232                                 service_dispatch_watchdog, s);
233                 if (r < 0) {
234                         log_unit_warning_errno(UNIT(s), r, "Failed to add watchdog timer: %m");
235                         return;
236                 }
237 
238                 (void) sd_event_source_set_description(s->watchdog_event_source, "service-watchdog");
239 
240                 /* Let's process everything else which might be a sign
241                  * of living before we consider a service died. */
242                 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
243         }
244         if (r < 0)
245                 log_unit_warning_errno(UNIT(s), r, "Failed to install watchdog timer: %m");
246 }
247 
service_extend_event_source_timeout(Service * s,sd_event_source * source,usec_t extended)248 static void service_extend_event_source_timeout(Service *s, sd_event_source *source, usec_t extended) {
249         usec_t current;
250         int r;
251 
252         assert(s);
253 
254         /* Extends the specified event source timer to at least the specified time, unless it is already later
255          * anyway. */
256 
257         if (!source)
258                 return;
259 
260         r = sd_event_source_get_time(source, &current);
261         if (r < 0) {
262                 const char *desc;
263                 (void) sd_event_source_get_description(s->timer_event_source, &desc);
264                 log_unit_warning_errno(UNIT(s), r, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc));
265                 return;
266         }
267 
268         if (current >= extended) /* Current timeout is already longer, ignore this. */
269                 return;
270 
271         r = sd_event_source_set_time(source, extended);
272         if (r < 0) {
273                 const char *desc;
274                 (void) sd_event_source_get_description(s->timer_event_source, &desc);
275                 log_unit_warning_errno(UNIT(s), r, "Failed to set timeout time for even source '%s', ignoring %m", strna(desc));
276         }
277 }
278 
service_extend_timeout(Service * s,usec_t extend_timeout_usec)279 static void service_extend_timeout(Service *s, usec_t extend_timeout_usec) {
280         usec_t extended;
281 
282         assert(s);
283 
284         if (!timestamp_is_set(extend_timeout_usec))
285                 return;
286 
287         extended = usec_add(now(CLOCK_MONOTONIC), extend_timeout_usec);
288 
289         service_extend_event_source_timeout(s, s->timer_event_source, extended);
290         service_extend_event_source_timeout(s, s->watchdog_event_source, extended);
291 }
292 
service_reset_watchdog(Service * s)293 static void service_reset_watchdog(Service *s) {
294         assert(s);
295 
296         dual_timestamp_get(&s->watchdog_timestamp);
297         service_start_watchdog(s);
298 }
299 
service_override_watchdog_timeout(Service * s,usec_t watchdog_override_usec)300 static void service_override_watchdog_timeout(Service *s, usec_t watchdog_override_usec) {
301         assert(s);
302 
303         s->watchdog_override_enable = true;
304         s->watchdog_override_usec = watchdog_override_usec;
305         service_reset_watchdog(s);
306 
307         log_unit_debug(UNIT(s), "watchdog_usec="USEC_FMT, s->watchdog_usec);
308         log_unit_debug(UNIT(s), "watchdog_override_usec="USEC_FMT, s->watchdog_override_usec);
309 }
310 
service_fd_store_unlink(ServiceFDStore * fs)311 static void service_fd_store_unlink(ServiceFDStore *fs) {
312 
313         if (!fs)
314                 return;
315 
316         if (fs->service) {
317                 assert(fs->service->n_fd_store > 0);
318                 LIST_REMOVE(fd_store, fs->service->fd_store, fs);
319                 fs->service->n_fd_store--;
320         }
321 
322         sd_event_source_disable_unref(fs->event_source);
323 
324         free(fs->fdname);
325         safe_close(fs->fd);
326         free(fs);
327 }
328 
service_release_fd_store(Service * s)329 static void service_release_fd_store(Service *s) {
330         assert(s);
331 
332         if (s->n_keep_fd_store > 0)
333                 return;
334 
335         log_unit_debug(UNIT(s), "Releasing all stored fds");
336         while (s->fd_store)
337                 service_fd_store_unlink(s->fd_store);
338 
339         assert(s->n_fd_store == 0);
340 }
341 
service_release_resources(Unit * u)342 static void service_release_resources(Unit *u) {
343         Service *s = SERVICE(u);
344 
345         assert(s);
346 
347         if (!s->fd_store && s->stdin_fd < 0 && s->stdout_fd < 0 && s->stderr_fd < 0)
348                 return;
349 
350         log_unit_debug(u, "Releasing resources.");
351 
352         s->stdin_fd = safe_close(s->stdin_fd);
353         s->stdout_fd = safe_close(s->stdout_fd);
354         s->stderr_fd = safe_close(s->stderr_fd);
355 
356         service_release_fd_store(s);
357 }
358 
service_done(Unit * u)359 static void service_done(Unit *u) {
360         Service *s = SERVICE(u);
361 
362         assert(s);
363 
364         s->pid_file = mfree(s->pid_file);
365         s->status_text = mfree(s->status_text);
366 
367         s->exec_runtime = exec_runtime_unref(s->exec_runtime, false);
368         exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
369         s->control_command = NULL;
370         s->main_command = NULL;
371 
372         dynamic_creds_unref(&s->dynamic_creds);
373 
374         exit_status_set_free(&s->restart_prevent_status);
375         exit_status_set_free(&s->restart_force_status);
376         exit_status_set_free(&s->success_status);
377 
378         /* This will leak a process, but at least no memory or any of
379          * our resources */
380         service_unwatch_main_pid(s);
381         service_unwatch_control_pid(s);
382         service_unwatch_pid_file(s);
383 
384         if (s->bus_name)  {
385                 unit_unwatch_bus_name(u, s->bus_name);
386                 s->bus_name = mfree(s->bus_name);
387         }
388 
389         s->bus_name_owner = mfree(s->bus_name_owner);
390 
391         s->usb_function_descriptors = mfree(s->usb_function_descriptors);
392         s->usb_function_strings = mfree(s->usb_function_strings);
393 
394         service_close_socket_fd(s);
395 
396         unit_ref_unset(&s->accept_socket);
397 
398         service_stop_watchdog(s);
399 
400         s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
401         s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
402 
403         s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
404 
405         service_release_resources(u);
406 }
407 
on_fd_store_io(sd_event_source * e,int fd,uint32_t revents,void * userdata)408 static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
409         ServiceFDStore *fs = userdata;
410 
411         assert(e);
412         assert(fs);
413 
414         /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
415         log_unit_debug(UNIT(fs->service),
416                        "Received %s on stored fd %d (%s), closing.",
417                        revents & EPOLLERR ? "EPOLLERR" : "EPOLLHUP",
418                        fs->fd, strna(fs->fdname));
419         service_fd_store_unlink(fs);
420         return 0;
421 }
422 
service_add_fd_store(Service * s,int fd,const char * name,bool do_poll)423 static int service_add_fd_store(Service *s, int fd, const char *name, bool do_poll) {
424         ServiceFDStore *fs;
425         int r;
426 
427         /* fd is always consumed if we return >= 0 */
428 
429         assert(s);
430         assert(fd >= 0);
431 
432         if (s->n_fd_store >= s->n_fd_store_max)
433                 return -EXFULL; /* Our store is full.
434                                  * Use this errno rather than E[NM]FILE to distinguish from
435                                  * the case where systemd itself hits the file limit. */
436 
437         LIST_FOREACH(fd_store, i, s->fd_store) {
438                 r = same_fd(i->fd, fd);
439                 if (r < 0)
440                         return r;
441                 if (r > 0) {
442                         safe_close(fd);
443                         return 0; /* fd already included */
444                 }
445         }
446 
447         fs = new(ServiceFDStore, 1);
448         if (!fs)
449                 return -ENOMEM;
450 
451         *fs = (ServiceFDStore) {
452                 .fd = fd,
453                 .service = s,
454                 .do_poll = do_poll,
455                 .fdname = strdup(name ?: "stored"),
456         };
457 
458         if (!fs->fdname) {
459                 free(fs);
460                 return -ENOMEM;
461         }
462 
463         if (do_poll) {
464                 r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fd, 0, on_fd_store_io, fs);
465                 if (r < 0 && r != -EPERM) { /* EPERM indicates fds that aren't pollable, which is OK */
466                         free(fs->fdname);
467                         free(fs);
468                         return r;
469                 } else if (r >= 0)
470                         (void) sd_event_source_set_description(fs->event_source, "service-fd-store");
471         }
472 
473         LIST_PREPEND(fd_store, s->fd_store, fs);
474         s->n_fd_store++;
475 
476         return 1; /* fd newly stored */
477 }
478 
service_add_fd_store_set(Service * s,FDSet * fds,const char * name,bool do_poll)479 static int service_add_fd_store_set(Service *s, FDSet *fds, const char *name, bool do_poll) {
480         int r;
481 
482         assert(s);
483 
484         while (fdset_size(fds) > 0) {
485                 _cleanup_close_ int fd = -1;
486 
487                 fd = fdset_steal_first(fds);
488                 if (fd < 0)
489                         break;
490 
491                 r = service_add_fd_store(s, fd, name, do_poll);
492                 if (r == -EXFULL)
493                         return log_unit_warning_errno(UNIT(s), r,
494                                                       "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
495                                                       s->n_fd_store_max);
496                 if (r < 0)
497                         return log_unit_error_errno(UNIT(s), r, "Failed to add fd to store: %m");
498                 if (r > 0)
499                         log_unit_debug(UNIT(s), "Added fd %u (%s) to fd store.", fd, strna(name));
500                 fd = -1;
501         }
502 
503         return 0;
504 }
505 
service_remove_fd_store(Service * s,const char * name)506 static void service_remove_fd_store(Service *s, const char *name) {
507         assert(s);
508         assert(name);
509 
510         LIST_FOREACH(fd_store, fs, s->fd_store) {
511                 if (!streq(fs->fdname, name))
512                         continue;
513 
514                 log_unit_debug(UNIT(s), "Got explicit request to remove fd %i (%s), closing.", fs->fd, name);
515                 service_fd_store_unlink(fs);
516         }
517 }
518 
service_running_timeout(Service * s)519 static usec_t service_running_timeout(Service *s) {
520         usec_t delta = 0;
521 
522         assert(s);
523 
524         if (s->runtime_rand_extra_usec != 0) {
525                 delta = random_u64_range(s->runtime_rand_extra_usec);
526                 log_unit_debug(UNIT(s), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta, USEC_PER_SEC));
527         }
528 
529         return usec_add(usec_add(UNIT(s)->active_enter_timestamp.monotonic,
530                                  s->runtime_max_usec),
531                         delta);
532 }
533 
service_arm_timer(Service * s,usec_t usec)534 static int service_arm_timer(Service *s, usec_t usec) {
535         int r;
536 
537         assert(s);
538 
539         if (s->timer_event_source) {
540                 r = sd_event_source_set_time(s->timer_event_source, usec);
541                 if (r < 0)
542                         return r;
543 
544                 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
545         }
546 
547         if (usec == USEC_INFINITY)
548                 return 0;
549 
550         r = sd_event_add_time(
551                         UNIT(s)->manager->event,
552                         &s->timer_event_source,
553                         CLOCK_MONOTONIC,
554                         usec, 0,
555                         service_dispatch_timer, s);
556         if (r < 0)
557                 return r;
558 
559         (void) sd_event_source_set_description(s->timer_event_source, "service-timer");
560 
561         return 0;
562 }
563 
service_verify(Service * s)564 static int service_verify(Service *s) {
565         assert(s);
566         assert(UNIT(s)->load_state == UNIT_LOADED);
567 
568         for (ServiceExecCommand c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++)
569                 LIST_FOREACH(command, command, s->exec_command[c]) {
570                         if (!path_is_absolute(command->path) && !filename_is_valid(command->path))
571                                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC),
572                                                             "Service %s= binary path \"%s\" is neither a valid executable name nor an absolute path. Refusing.",
573                                                             command->path,
574                                                             service_exec_command_to_string(c));
575                         if (strv_isempty(command->argv))
576                                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC),
577                                                             "Service has an empty argv in %s=. Refusing.",
578                                                             service_exec_command_to_string(c));
579                 }
580 
581         if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP] &&
582             UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
583                 /* FailureAction= only makes sense if one of the start or stop commands is specified.
584                  * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
585                  * either a command or SuccessAction= are required. */
586 
587                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
588 
589         if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START])
590                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
591 
592         if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START] && UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
593                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart= and no SuccessAction= settings and does not have RemainAfterExit=yes set. Refusing.");
594 
595         if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next)
596                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
597 
598         if (s->type == SERVICE_ONESHOT &&
599             !IN_SET(s->restart, SERVICE_RESTART_NO, SERVICE_RESTART_ON_FAILURE, SERVICE_RESTART_ON_ABNORMAL, SERVICE_RESTART_ON_WATCHDOG, SERVICE_RESTART_ON_ABORT))
600                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has Restart= set to either always or on-success, which isn't allowed for Type=oneshot services. Refusing.");
601 
602         if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status))
603                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
604 
605         if (s->type == SERVICE_ONESHOT && s->exit_type == SERVICE_EXIT_CGROUP)
606                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
607 
608         if (s->type == SERVICE_DBUS && !s->bus_name)
609                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service is of type D-Bus but no D-Bus service name has been specified. Refusing.");
610 
611         if (s->exec_context.pam_name && !IN_SET(s->kill_context.kill_mode, KILL_CONTROL_GROUP, KILL_MIXED))
612                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.");
613 
614         if (s->usb_function_descriptors && !s->usb_function_strings)
615                 log_unit_warning(UNIT(s), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
616 
617         if (!s->usb_function_descriptors && s->usb_function_strings)
618                 log_unit_warning(UNIT(s), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
619 
620         if (s->runtime_max_usec != USEC_INFINITY && s->type == SERVICE_ONESHOT)
621                 log_unit_warning(UNIT(s), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
622 
623         if (s->runtime_max_usec == USEC_INFINITY && s->runtime_rand_extra_usec != 0)
624                 log_unit_warning(UNIT(s), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
625 
626         if (s->exit_type == SERVICE_EXIT_CGROUP && cg_unified() < CGROUP_UNIFIED_SYSTEMD)
627                 log_unit_warning(UNIT(s), "Service has ExitType=cgroup set, but we are running with legacy cgroups v1, which might not work correctly. Continuing.");
628 
629         return 0;
630 }
631 
service_add_default_dependencies(Service * s)632 static int service_add_default_dependencies(Service *s) {
633         int r;
634 
635         assert(s);
636 
637         if (!UNIT(s)->default_dependencies)
638                 return 0;
639 
640         /* Add a number of automatic dependencies useful for the
641          * majority of services. */
642 
643         if (MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
644                 /* First, pull in the really early boot stuff, and
645                  * require it, so that we fail if we can't acquire
646                  * it. */
647 
648                 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
649                 if (r < 0)
650                         return r;
651         } else {
652 
653                 /* In the --user instance there's no sysinit.target,
654                  * in that case require basic.target instead. */
655 
656                 r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
657                 if (r < 0)
658                         return r;
659         }
660 
661         /* Second, if the rest of the base system is in the same
662          * transaction, order us after it, but do not pull it in or
663          * even require it. */
664         r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
665         if (r < 0)
666                 return r;
667 
668         /* Third, add us in for normal shutdown. */
669         return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
670 }
671 
service_fix_stdio(Service * s)672 static void service_fix_stdio(Service *s) {
673         assert(s);
674 
675         /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
676          * default value that is subject to automatic overriding triggered by other settings and an explicit
677          * choice the user can make. We don't distinguish between these cases currently. */
678 
679         if (s->exec_context.std_input == EXEC_INPUT_NULL &&
680             s->exec_context.stdin_data_size > 0)
681                 s->exec_context.std_input = EXEC_INPUT_DATA;
682 
683         if (IN_SET(s->exec_context.std_input,
684                     EXEC_INPUT_TTY,
685                     EXEC_INPUT_TTY_FORCE,
686                     EXEC_INPUT_TTY_FAIL,
687                     EXEC_INPUT_SOCKET,
688                     EXEC_INPUT_NAMED_FD))
689                 return;
690 
691         /* We assume these listed inputs refer to bidirectional streams, and hence duplicating them from
692          * stdin to stdout/stderr makes sense and hence leaving EXEC_OUTPUT_INHERIT in place makes sense,
693          * too. Outputs such as regular files or sealed data memfds otoh don't really make sense to be
694          * duplicated for both input and output at the same time (since they then would cause a feedback
695          * loop), hence override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting.  */
696 
697         if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
698             s->exec_context.std_output == EXEC_OUTPUT_INHERIT)
699                 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
700 
701         if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT)
702                 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
703 }
704 
service_setup_bus_name(Service * s)705 static int service_setup_bus_name(Service *s) {
706         int r;
707 
708         assert(s);
709 
710         /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
711         if (!s->bus_name)
712                 return 0;
713 
714         if (s->type == SERVICE_DBUS) {
715                 r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, true, UNIT_DEPENDENCY_FILE);
716                 if (r < 0)
717                         return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on " SPECIAL_DBUS_SOCKET ": %m");
718 
719                 /* We always want to be ordered against dbus.socket if both are in the transaction. */
720                 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_DBUS_SOCKET, true, UNIT_DEPENDENCY_FILE);
721                 if (r < 0)
722                         return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on " SPECIAL_DBUS_SOCKET ": %m");
723         }
724 
725         r = unit_watch_bus_name(UNIT(s), s->bus_name);
726         if (r == -EEXIST)
727                 return log_unit_error_errno(UNIT(s), r, "Two services allocated for the same bus name %s, refusing operation.", s->bus_name);
728         if (r < 0)
729                 return log_unit_error_errno(UNIT(s), r, "Cannot watch bus name %s: %m", s->bus_name);
730 
731         return 0;
732 }
733 
service_add_extras(Service * s)734 static int service_add_extras(Service *s) {
735         int r;
736 
737         assert(s);
738 
739         if (s->type == _SERVICE_TYPE_INVALID) {
740                 /* Figure out a type automatically */
741                 if (s->bus_name)
742                         s->type = SERVICE_DBUS;
743                 else if (s->exec_command[SERVICE_EXEC_START])
744                         s->type = SERVICE_SIMPLE;
745                 else
746                         s->type = SERVICE_ONESHOT;
747         }
748 
749         /* Oneshot services have disabled start timeout by default */
750         if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
751                 s->timeout_start_usec = USEC_INFINITY;
752 
753         service_fix_stdio(s);
754 
755         r = unit_patch_contexts(UNIT(s));
756         if (r < 0)
757                 return r;
758 
759         r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
760         if (r < 0)
761                 return r;
762 
763         r = unit_set_default_slice(UNIT(s));
764         if (r < 0)
765                 return r;
766 
767         /* If the service needs the notify socket, let's enable it automatically. */
768         if (s->notify_access == NOTIFY_NONE &&
769             (s->type == SERVICE_NOTIFY || s->watchdog_usec > 0 || s->n_fd_store_max > 0))
770                 s->notify_access = NOTIFY_MAIN;
771 
772         /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
773          * delegation is on, in that case it we assume the payload knows better what to do and can process
774          * things in a more focused way. */
775         if (s->oom_policy < 0)
776                 s->oom_policy = s->cgroup_context.delegate ? OOM_CONTINUE : UNIT(s)->manager->default_oom_policy;
777 
778         /* Let the kernel do the killing if that's requested. */
779         s->cgroup_context.memory_oom_group = s->oom_policy == OOM_KILL;
780 
781         r = service_add_default_dependencies(s);
782         if (r < 0)
783                 return r;
784 
785         r = service_setup_bus_name(s);
786         if (r < 0)
787                 return r;
788 
789         return 0;
790 }
791 
service_load(Unit * u)792 static int service_load(Unit *u) {
793         Service *s = SERVICE(u);
794         int r;
795 
796         r = unit_load_fragment_and_dropin(u, true);
797         if (r < 0)
798                 return r;
799 
800         if (u->load_state != UNIT_LOADED)
801                 return 0;
802 
803         /* This is a new unit? Then let's add in some extras */
804         r = service_add_extras(s);
805         if (r < 0)
806                 return r;
807 
808         return service_verify(s);
809 }
810 
service_dump(Unit * u,FILE * f,const char * prefix)811 static void service_dump(Unit *u, FILE *f, const char *prefix) {
812         ServiceExecCommand c;
813         Service *s = SERVICE(u);
814         const char *prefix2;
815 
816         assert(s);
817 
818         prefix = strempty(prefix);
819         prefix2 = strjoina(prefix, "\t");
820 
821         fprintf(f,
822                 "%sService State: %s\n"
823                 "%sResult: %s\n"
824                 "%sReload Result: %s\n"
825                 "%sClean Result: %s\n"
826                 "%sPermissionsStartOnly: %s\n"
827                 "%sRootDirectoryStartOnly: %s\n"
828                 "%sRemainAfterExit: %s\n"
829                 "%sGuessMainPID: %s\n"
830                 "%sType: %s\n"
831                 "%sRestart: %s\n"
832                 "%sNotifyAccess: %s\n"
833                 "%sNotifyState: %s\n"
834                 "%sOOMPolicy: %s\n",
835                 prefix, service_state_to_string(s->state),
836                 prefix, service_result_to_string(s->result),
837                 prefix, service_result_to_string(s->reload_result),
838                 prefix, service_result_to_string(s->clean_result),
839                 prefix, yes_no(s->permissions_start_only),
840                 prefix, yes_no(s->root_directory_start_only),
841                 prefix, yes_no(s->remain_after_exit),
842                 prefix, yes_no(s->guess_main_pid),
843                 prefix, service_type_to_string(s->type),
844                 prefix, service_restart_to_string(s->restart),
845                 prefix, notify_access_to_string(s->notify_access),
846                 prefix, notify_state_to_string(s->notify_state),
847                 prefix, oom_policy_to_string(s->oom_policy));
848 
849         if (s->control_pid > 0)
850                 fprintf(f,
851                         "%sControl PID: "PID_FMT"\n",
852                         prefix, s->control_pid);
853 
854         if (s->main_pid > 0)
855                 fprintf(f,
856                         "%sMain PID: "PID_FMT"\n"
857                         "%sMain PID Known: %s\n"
858                         "%sMain PID Alien: %s\n",
859                         prefix, s->main_pid,
860                         prefix, yes_no(s->main_pid_known),
861                         prefix, yes_no(s->main_pid_alien));
862 
863         if (s->pid_file)
864                 fprintf(f,
865                         "%sPIDFile: %s\n",
866                         prefix, s->pid_file);
867 
868         if (s->bus_name)
869                 fprintf(f,
870                         "%sBusName: %s\n"
871                         "%sBus Name Good: %s\n",
872                         prefix, s->bus_name,
873                         prefix, yes_no(s->bus_name_good));
874 
875         if (UNIT_ISSET(s->accept_socket))
876                 fprintf(f,
877                         "%sAccept Socket: %s\n",
878                         prefix, UNIT_DEREF(s->accept_socket)->id);
879 
880         fprintf(f,
881                 "%sRestartSec: %s\n"
882                 "%sTimeoutStartSec: %s\n"
883                 "%sTimeoutStopSec: %s\n"
884                 "%sTimeoutStartFailureMode: %s\n"
885                 "%sTimeoutStopFailureMode: %s\n",
886                 prefix, FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC),
887                 prefix, FORMAT_TIMESPAN(s->timeout_start_usec, USEC_PER_SEC),
888                 prefix, FORMAT_TIMESPAN(s->timeout_stop_usec, USEC_PER_SEC),
889                 prefix, service_timeout_failure_mode_to_string(s->timeout_start_failure_mode),
890                 prefix, service_timeout_failure_mode_to_string(s->timeout_stop_failure_mode));
891 
892         if (s->timeout_abort_set)
893                 fprintf(f,
894                         "%sTimeoutAbortSec: %s\n",
895                         prefix, FORMAT_TIMESPAN(s->timeout_abort_usec, USEC_PER_SEC));
896 
897         fprintf(f,
898                 "%sRuntimeMaxSec: %s\n"
899                 "%sRuntimeRandomizedExtraSec: %s\n"
900                 "%sWatchdogSec: %s\n",
901                 prefix, FORMAT_TIMESPAN(s->runtime_max_usec, USEC_PER_SEC),
902                 prefix, FORMAT_TIMESPAN(s->runtime_rand_extra_usec, USEC_PER_SEC),
903                 prefix, FORMAT_TIMESPAN(s->watchdog_usec, USEC_PER_SEC));
904 
905         kill_context_dump(&s->kill_context, f, prefix);
906         exec_context_dump(&s->exec_context, f, prefix);
907 
908         for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
909 
910                 if (!s->exec_command[c])
911                         continue;
912 
913                 fprintf(f, "%s-> %s:\n",
914                         prefix, service_exec_command_to_string(c));
915 
916                 exec_command_dump_list(s->exec_command[c], f, prefix2);
917         }
918 
919         if (s->status_text)
920                 fprintf(f, "%sStatus Text: %s\n",
921                         prefix, s->status_text);
922 
923         if (s->n_fd_store_max > 0)
924                 fprintf(f,
925                         "%sFile Descriptor Store Max: %u\n"
926                         "%sFile Descriptor Store Current: %zu\n",
927                         prefix, s->n_fd_store_max,
928                         prefix, s->n_fd_store);
929 
930         cgroup_context_dump(UNIT(s), f, prefix);
931 }
932 
service_is_suitable_main_pid(Service * s,pid_t pid,int prio)933 static int service_is_suitable_main_pid(Service *s, pid_t pid, int prio) {
934         Unit *owner;
935 
936         assert(s);
937         assert(pid_is_valid(pid));
938 
939         /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
940          * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
941          * good */
942 
943         if (pid == getpid_cached() || pid == 1)
944                 return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(EPERM), "New main PID "PID_FMT" is the manager, refusing.", pid);
945 
946         if (pid == s->control_pid)
947                 return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(EPERM), "New main PID "PID_FMT" is the control process, refusing.", pid);
948 
949         if (!pid_is_alive(pid))
950                 return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(ESRCH), "New main PID "PID_FMT" does not exist or is a zombie.", pid);
951 
952         owner = manager_get_unit_by_pid(UNIT(s)->manager, pid);
953         if (owner == UNIT(s)) {
954                 log_unit_debug(UNIT(s), "New main PID "PID_FMT" belongs to service, we are happy.", pid);
955                 return 1; /* Yay, it's definitely a good PID */
956         }
957 
958         return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
959 }
960 
service_load_pid_file(Service * s,bool may_warn)961 static int service_load_pid_file(Service *s, bool may_warn) {
962         bool questionable_pid_file = false;
963         _cleanup_free_ char *k = NULL;
964         _cleanup_close_ int fd = -1;
965         int r, prio;
966         pid_t pid;
967 
968         assert(s);
969 
970         if (!s->pid_file)
971                 return -ENOENT;
972 
973         prio = may_warn ? LOG_INFO : LOG_DEBUG;
974 
975         r = chase_symlinks(s->pid_file, NULL, CHASE_SAFE, NULL, &fd);
976         if (r == -ENOLINK) {
977                 log_unit_debug_errno(UNIT(s), r,
978                                      "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s->pid_file);
979 
980                 questionable_pid_file = true;
981 
982                 r = chase_symlinks(s->pid_file, NULL, 0, NULL, &fd);
983         }
984         if (r < 0)
985                 return log_unit_full_errno(UNIT(s), prio, fd,
986                                            "Can't open PID file %s (yet?) after %s: %m", s->pid_file, service_state_to_string(s->state));
987 
988         /* Let's read the PID file now that we chased it down. But we need to convert the O_PATH fd
989          * chase_symlinks() returned us into a proper fd first. */
990         r = read_one_line_file(FORMAT_PROC_FD_PATH(fd), &k);
991         if (r < 0)
992                 return log_unit_error_errno(UNIT(s), r,
993                                             "Can't convert PID files %s O_PATH file descriptor to proper file descriptor: %m",
994                                             s->pid_file);
995 
996         r = parse_pid(k, &pid);
997         if (r < 0)
998                 return log_unit_full_errno(UNIT(s), prio, r, "Failed to parse PID from file %s: %m", s->pid_file);
999 
1000         if (s->main_pid_known && pid == s->main_pid)
1001                 return 0;
1002 
1003         r = service_is_suitable_main_pid(s, pid, prio);
1004         if (r < 0)
1005                 return r;
1006         if (r == 0) {
1007                 struct stat st;
1008 
1009                 if (questionable_pid_file)
1010                         return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EPERM),
1011                                                     "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s->pid_file);
1012 
1013                 /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
1014 
1015                 if (fstat(fd, &st) < 0)
1016                         return log_unit_error_errno(UNIT(s), errno, "Failed to fstat() PID file O_PATH fd: %m");
1017 
1018                 if (st.st_uid != 0)
1019                         return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EPERM),
1020                                                     "New main PID "PID_FMT" does not belong to service, and PID file is not owned by root. Refusing.", pid);
1021 
1022                 log_unit_debug(UNIT(s), "New main PID "PID_FMT" does not belong to service, but we'll accept it since PID file is owned by root.", pid);
1023         }
1024 
1025         if (s->main_pid_known) {
1026                 log_unit_debug(UNIT(s), "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid, pid);
1027 
1028                 service_unwatch_main_pid(s);
1029                 s->main_pid_known = false;
1030         } else
1031                 log_unit_debug(UNIT(s), "Main PID loaded: "PID_FMT, pid);
1032 
1033         r = service_set_main_pid(s, pid);
1034         if (r < 0)
1035                 return r;
1036 
1037         r = unit_watch_pid(UNIT(s), pid, false);
1038         if (r < 0) /* FIXME: we need to do something here */
1039                 return log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" for service: %m", pid);
1040 
1041         return 1;
1042 }
1043 
service_search_main_pid(Service * s)1044 static void service_search_main_pid(Service *s) {
1045         pid_t pid = 0;
1046         int r;
1047 
1048         assert(s);
1049 
1050         /* If we know it anyway, don't ever fall back to unreliable
1051          * heuristics */
1052         if (s->main_pid_known)
1053                 return;
1054 
1055         if (!s->guess_main_pid)
1056                 return;
1057 
1058         assert(s->main_pid <= 0);
1059 
1060         if (unit_search_main_pid(UNIT(s), &pid) < 0)
1061                 return;
1062 
1063         log_unit_debug(UNIT(s), "Main PID guessed: "PID_FMT, pid);
1064         if (service_set_main_pid(s, pid) < 0)
1065                 return;
1066 
1067         r = unit_watch_pid(UNIT(s), pid, false);
1068         if (r < 0)
1069                 /* FIXME: we need to do something here */
1070                 log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" from: %m", pid);
1071 }
1072 
service_set_state(Service * s,ServiceState state)1073 static void service_set_state(Service *s, ServiceState state) {
1074         ServiceState old_state;
1075         const UnitActiveState *table;
1076 
1077         assert(s);
1078 
1079         if (s->state != state)
1080                 bus_unit_send_pending_change_signal(UNIT(s), false);
1081 
1082         table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1083 
1084         old_state = s->state;
1085         s->state = state;
1086 
1087         service_unwatch_pid_file(s);
1088 
1089         if (!IN_SET(state,
1090                     SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1091                     SERVICE_RUNNING,
1092                     SERVICE_RELOAD,
1093                     SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1094                     SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
1095                     SERVICE_AUTO_RESTART,
1096                     SERVICE_CLEANING))
1097                 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
1098 
1099         if (!IN_SET(state,
1100                     SERVICE_START, SERVICE_START_POST,
1101                     SERVICE_RUNNING, SERVICE_RELOAD,
1102                     SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1103                     SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
1104                 service_unwatch_main_pid(s);
1105                 s->main_command = NULL;
1106         }
1107 
1108         if (!IN_SET(state,
1109                     SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1110                     SERVICE_RELOAD,
1111                     SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1112                     SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
1113                     SERVICE_CLEANING)) {
1114                 service_unwatch_control_pid(s);
1115                 s->control_command = NULL;
1116                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1117         }
1118 
1119         if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART)) {
1120                 unit_unwatch_all_pids(UNIT(s));
1121                 unit_dequeue_rewatch_pids(UNIT(s));
1122         }
1123 
1124         if (!IN_SET(state,
1125                     SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1126                     SERVICE_RUNNING, SERVICE_RELOAD,
1127                     SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1128                     SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
1129             !(state == SERVICE_DEAD && UNIT(s)->job))
1130                 service_close_socket_fd(s);
1131 
1132         if (state != SERVICE_START)
1133                 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
1134 
1135         if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1136                 service_stop_watchdog(s);
1137 
1138         /* For the inactive states unit_notify() will trim the cgroup,
1139          * but for exit we have to do that ourselves... */
1140         if (state == SERVICE_EXITED && !MANAGER_IS_RELOADING(UNIT(s)->manager))
1141                 unit_prune_cgroup(UNIT(s));
1142 
1143         if (old_state != state)
1144                 log_unit_debug(UNIT(s), "Changed %s -> %s", service_state_to_string(old_state), service_state_to_string(state));
1145 
1146         unit_notify(UNIT(s), table[old_state], table[state],
1147                     (s->reload_result == SERVICE_SUCCESS ? 0 : UNIT_NOTIFY_RELOAD_FAILURE) |
1148                     (s->will_auto_restart ? UNIT_NOTIFY_WILL_AUTO_RESTART : 0));
1149 }
1150 
service_coldplug_timeout(Service * s)1151 static usec_t service_coldplug_timeout(Service *s) {
1152         assert(s);
1153 
1154         switch (s->deserialized_state) {
1155 
1156         case SERVICE_CONDITION:
1157         case SERVICE_START_PRE:
1158         case SERVICE_START:
1159         case SERVICE_START_POST:
1160         case SERVICE_RELOAD:
1161                 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_start_usec);
1162 
1163         case SERVICE_RUNNING:
1164                 return service_running_timeout(s);
1165 
1166         case SERVICE_STOP:
1167         case SERVICE_STOP_SIGTERM:
1168         case SERVICE_STOP_SIGKILL:
1169         case SERVICE_STOP_POST:
1170         case SERVICE_FINAL_SIGTERM:
1171         case SERVICE_FINAL_SIGKILL:
1172                 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_stop_usec);
1173 
1174         case SERVICE_STOP_WATCHDOG:
1175         case SERVICE_FINAL_WATCHDOG:
1176                 return usec_add(UNIT(s)->state_change_timestamp.monotonic, service_timeout_abort_usec(s));
1177 
1178         case SERVICE_AUTO_RESTART:
1179                 return usec_add(UNIT(s)->inactive_enter_timestamp.monotonic, s->restart_usec);
1180 
1181         case SERVICE_CLEANING:
1182                 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->exec_context.timeout_clean_usec);
1183 
1184         default:
1185                 return USEC_INFINITY;
1186         }
1187 }
1188 
service_coldplug(Unit * u)1189 static int service_coldplug(Unit *u) {
1190         Service *s = SERVICE(u);
1191         int r;
1192 
1193         assert(s);
1194         assert(s->state == SERVICE_DEAD);
1195 
1196         if (s->deserialized_state == s->state)
1197                 return 0;
1198 
1199         r = service_arm_timer(s, service_coldplug_timeout(s));
1200         if (r < 0)
1201                 return r;
1202 
1203         if (s->main_pid > 0 &&
1204             pid_is_unwaited(s->main_pid) &&
1205             (IN_SET(s->deserialized_state,
1206                     SERVICE_START, SERVICE_START_POST,
1207                     SERVICE_RUNNING, SERVICE_RELOAD,
1208                     SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1209                     SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
1210                 r = unit_watch_pid(UNIT(s), s->main_pid, false);
1211                 if (r < 0)
1212                         return r;
1213         }
1214 
1215         if (s->control_pid > 0 &&
1216             pid_is_unwaited(s->control_pid) &&
1217             IN_SET(s->deserialized_state,
1218                    SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1219                    SERVICE_RELOAD,
1220                    SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1221                    SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
1222                    SERVICE_CLEANING)) {
1223                 r = unit_watch_pid(UNIT(s), s->control_pid, false);
1224                 if (r < 0)
1225                         return r;
1226         }
1227 
1228         if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART, SERVICE_CLEANING)) {
1229                 (void) unit_enqueue_rewatch_pids(u);
1230                 (void) unit_setup_dynamic_creds(u);
1231                 (void) unit_setup_exec_runtime(u);
1232         }
1233 
1234         if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1235                 service_start_watchdog(s);
1236 
1237         if (UNIT_ISSET(s->accept_socket)) {
1238                 Socket* socket = SOCKET(UNIT_DEREF(s->accept_socket));
1239 
1240                 if (socket->max_connections_per_source > 0) {
1241                         SocketPeer *peer;
1242 
1243                         /* Make a best-effort attempt at bumping the connection count */
1244                         if (socket_acquire_peer(socket, s->socket_fd, &peer) > 0) {
1245                                 socket_peer_unref(s->socket_peer);
1246                                 s->socket_peer = peer;
1247                         }
1248                 }
1249         }
1250 
1251         service_set_state(s, s->deserialized_state);
1252         return 0;
1253 }
1254 
service_collect_fds(Service * s,int ** fds,char *** fd_names,size_t * n_socket_fds,size_t * n_storage_fds)1255 static int service_collect_fds(
1256                 Service *s,
1257                 int **fds,
1258                 char ***fd_names,
1259                 size_t *n_socket_fds,
1260                 size_t *n_storage_fds) {
1261 
1262         _cleanup_strv_free_ char **rfd_names = NULL;
1263         _cleanup_free_ int *rfds = NULL;
1264         size_t rn_socket_fds = 0, rn_storage_fds = 0;
1265         int r;
1266 
1267         assert(s);
1268         assert(fds);
1269         assert(fd_names);
1270         assert(n_socket_fds);
1271         assert(n_storage_fds);
1272 
1273         if (s->socket_fd >= 0) {
1274 
1275                 /* Pass the per-connection socket */
1276 
1277                 rfds = new(int, 1);
1278                 if (!rfds)
1279                         return -ENOMEM;
1280                 rfds[0] = s->socket_fd;
1281 
1282                 rfd_names = strv_new("connection");
1283                 if (!rfd_names)
1284                         return -ENOMEM;
1285 
1286                 rn_socket_fds = 1;
1287         } else {
1288                 Unit *u;
1289 
1290                 /* Pass all our configured sockets for singleton services */
1291 
1292                 UNIT_FOREACH_DEPENDENCY(u, UNIT(s), UNIT_ATOM_TRIGGERED_BY) {
1293                         _cleanup_free_ int *cfds = NULL;
1294                         Socket *sock;
1295                         int cn_fds;
1296 
1297                         if (u->type != UNIT_SOCKET)
1298                                 continue;
1299 
1300                         sock = SOCKET(u);
1301 
1302                         cn_fds = socket_collect_fds(sock, &cfds);
1303                         if (cn_fds < 0)
1304                                 return cn_fds;
1305 
1306                         if (cn_fds <= 0)
1307                                 continue;
1308 
1309                         if (!rfds) {
1310                                 rfds = TAKE_PTR(cfds);
1311                                 rn_socket_fds = cn_fds;
1312                         } else {
1313                                 int *t;
1314 
1315                                 t = reallocarray(rfds, rn_socket_fds + cn_fds, sizeof(int));
1316                                 if (!t)
1317                                         return -ENOMEM;
1318 
1319                                 memcpy(t + rn_socket_fds, cfds, cn_fds * sizeof(int));
1320 
1321                                 rfds = t;
1322                                 rn_socket_fds += cn_fds;
1323                         }
1324 
1325                         r = strv_extend_n(&rfd_names, socket_fdname(sock), cn_fds);
1326                         if (r < 0)
1327                                 return r;
1328                 }
1329         }
1330 
1331         if (s->n_fd_store > 0) {
1332                 size_t n_fds;
1333                 char **nl;
1334                 int *t;
1335 
1336                 t = reallocarray(rfds, rn_socket_fds + s->n_fd_store, sizeof(int));
1337                 if (!t)
1338                         return -ENOMEM;
1339 
1340                 rfds = t;
1341 
1342                 nl = reallocarray(rfd_names, rn_socket_fds + s->n_fd_store + 1, sizeof(char *));
1343                 if (!nl)
1344                         return -ENOMEM;
1345 
1346                 rfd_names = nl;
1347                 n_fds = rn_socket_fds;
1348 
1349                 LIST_FOREACH(fd_store, fs, s->fd_store) {
1350                         rfds[n_fds] = fs->fd;
1351                         rfd_names[n_fds] = strdup(strempty(fs->fdname));
1352                         if (!rfd_names[n_fds])
1353                                 return -ENOMEM;
1354 
1355                         rn_storage_fds++;
1356                         n_fds++;
1357                 }
1358 
1359                 rfd_names[n_fds] = NULL;
1360         }
1361 
1362         *fds = TAKE_PTR(rfds);
1363         *fd_names = TAKE_PTR(rfd_names);
1364         *n_socket_fds = rn_socket_fds;
1365         *n_storage_fds = rn_storage_fds;
1366 
1367         return 0;
1368 }
1369 
service_allocate_exec_fd_event_source(Service * s,int fd,sd_event_source ** ret_event_source)1370 static int service_allocate_exec_fd_event_source(
1371                 Service *s,
1372                 int fd,
1373                 sd_event_source **ret_event_source) {
1374 
1375         _cleanup_(sd_event_source_unrefp) sd_event_source *source = NULL;
1376         int r;
1377 
1378         assert(s);
1379         assert(fd >= 0);
1380         assert(ret_event_source);
1381 
1382         r = sd_event_add_io(UNIT(s)->manager->event, &source, fd, 0, service_dispatch_exec_io, s);
1383         if (r < 0)
1384                 return log_unit_error_errno(UNIT(s), r, "Failed to allocate exec_fd event source: %m");
1385 
1386         /* This is a bit lower priority than SIGCHLD, as that carries a lot more interesting failure information */
1387 
1388         r = sd_event_source_set_priority(source, SD_EVENT_PRIORITY_NORMAL-3);
1389         if (r < 0)
1390                 return log_unit_error_errno(UNIT(s), r, "Failed to adjust priority of exec_fd event source: %m");
1391 
1392         (void) sd_event_source_set_description(source, "service exec_fd");
1393 
1394         r = sd_event_source_set_io_fd_own(source, true);
1395         if (r < 0)
1396                 return log_unit_error_errno(UNIT(s), r, "Failed to pass ownership of fd to event source: %m");
1397 
1398         *ret_event_source = TAKE_PTR(source);
1399         return 0;
1400 }
1401 
service_allocate_exec_fd(Service * s,sd_event_source ** ret_event_source,int * ret_exec_fd)1402 static int service_allocate_exec_fd(
1403                 Service *s,
1404                 sd_event_source **ret_event_source,
1405                 int *ret_exec_fd) {
1406 
1407         _cleanup_close_pair_ int p[] = { -1, -1 };
1408         int r;
1409 
1410         assert(s);
1411         assert(ret_event_source);
1412         assert(ret_exec_fd);
1413 
1414         if (pipe2(p, O_CLOEXEC|O_NONBLOCK) < 0)
1415                 return log_unit_error_errno(UNIT(s), errno, "Failed to allocate exec_fd pipe: %m");
1416 
1417         r = service_allocate_exec_fd_event_source(s, p[0], ret_event_source);
1418         if (r < 0)
1419                 return r;
1420 
1421         TAKE_FD(p[0]);
1422         *ret_exec_fd = TAKE_FD(p[1]);
1423 
1424         return 0;
1425 }
1426 
service_exec_needs_notify_socket(Service * s,ExecFlags flags)1427 static bool service_exec_needs_notify_socket(Service *s, ExecFlags flags) {
1428         assert(s);
1429 
1430         /* Notifications are accepted depending on the process and
1431          * the access setting of the service:
1432          *     process: \ access:  NONE  MAIN  EXEC   ALL
1433          *     main                  no   yes   yes   yes
1434          *     control               no    no   yes   yes
1435          *     other (forked)        no    no    no   yes */
1436 
1437         if (flags & EXEC_IS_CONTROL)
1438                 /* A control process */
1439                 return IN_SET(s->notify_access, NOTIFY_EXEC, NOTIFY_ALL);
1440 
1441         /* We only spawn main processes and control processes, so any
1442          * process that is not a control process is a main process */
1443         return s->notify_access != NOTIFY_NONE;
1444 }
1445 
service_get_triggering_service(Service * s)1446 static Service *service_get_triggering_service(Service *s) {
1447         Unit *candidate = NULL, *other;
1448 
1449         assert(s);
1450 
1451         /* Return the service which triggered service 's', this means dependency
1452          * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
1453          *
1454          * N.B. if there are multiple services which could trigger 's' via OnFailure=
1455          * or OnSuccess= then we return NULL. This is since we don't know from which
1456          * one to propagate the exit status. */
1457 
1458         UNIT_FOREACH_DEPENDENCY(other, UNIT(s), UNIT_ATOM_ON_FAILURE_OF) {
1459                 if (candidate)
1460                         goto have_other;
1461                 candidate = other;
1462         }
1463 
1464         UNIT_FOREACH_DEPENDENCY(other, UNIT(s), UNIT_ATOM_ON_SUCCESS_OF) {
1465                 if (candidate)
1466                         goto have_other;
1467                 candidate = other;
1468         }
1469 
1470         return SERVICE(candidate);
1471 
1472  have_other:
1473         log_unit_warning(UNIT(s), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
1474                          candidate->id, other->id);
1475         return NULL;
1476 }
1477 
service_spawn_internal(const char * caller,Service * s,ExecCommand * c,usec_t timeout,ExecFlags flags,pid_t * ret_pid)1478 static int service_spawn_internal(
1479                 const char *caller,
1480                 Service *s,
1481                 ExecCommand *c,
1482                 usec_t timeout,
1483                 ExecFlags flags,
1484                 pid_t *ret_pid) {
1485 
1486         _cleanup_(exec_params_clear) ExecParameters exec_params = {
1487                 .flags     = flags,
1488                 .stdin_fd  = -1,
1489                 .stdout_fd = -1,
1490                 .stderr_fd = -1,
1491                 .exec_fd   = -1,
1492         };
1493         _cleanup_(sd_event_source_unrefp) sd_event_source *exec_fd_source = NULL;
1494         _cleanup_strv_free_ char **final_env = NULL, **our_env = NULL;
1495         size_t n_env = 0;
1496         pid_t pid;
1497         int r;
1498 
1499         assert(caller);
1500         assert(s);
1501         assert(c);
1502         assert(ret_pid);
1503 
1504         log_unit_debug(UNIT(s), "Will spawn child (%s): %s", caller, c->path);
1505 
1506         r = unit_prepare_exec(UNIT(s)); /* This realizes the cgroup, among other things */
1507         if (r < 0)
1508                 return r;
1509 
1510         assert(!s->exec_fd_event_source);
1511 
1512         if (flags & EXEC_IS_CONTROL) {
1513                 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1514                 if (s->permissions_start_only)
1515                         exec_params.flags &= ~EXEC_APPLY_SANDBOXING;
1516                 if (s->root_directory_start_only)
1517                         exec_params.flags &= ~EXEC_APPLY_CHROOT;
1518         }
1519 
1520         if ((flags & EXEC_PASS_FDS) ||
1521             s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1522             s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1523             s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1524 
1525                 r = service_collect_fds(s,
1526                                         &exec_params.fds,
1527                                         &exec_params.fd_names,
1528                                         &exec_params.n_socket_fds,
1529                                         &exec_params.n_storage_fds);
1530                 if (r < 0)
1531                         return r;
1532 
1533                 log_unit_debug(UNIT(s), "Passing %zu fds to service", exec_params.n_socket_fds + exec_params.n_storage_fds);
1534         }
1535 
1536         if (!FLAGS_SET(flags, EXEC_IS_CONTROL) && s->type == SERVICE_EXEC) {
1537                 r = service_allocate_exec_fd(s, &exec_fd_source, &exec_params.exec_fd);
1538                 if (r < 0)
1539                         return r;
1540         }
1541 
1542         r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), timeout));
1543         if (r < 0)
1544                 return r;
1545 
1546         our_env = new0(char*, 12);
1547         if (!our_env)
1548                 return -ENOMEM;
1549 
1550         if (service_exec_needs_notify_socket(s, flags)) {
1551                 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0)
1552                         return -ENOMEM;
1553 
1554                 exec_params.notify_socket = UNIT(s)->manager->notify_socket;
1555         }
1556 
1557         if (s->main_pid > 0)
1558                 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0)
1559                         return -ENOMEM;
1560 
1561         if (MANAGER_IS_USER(UNIT(s)->manager))
1562                 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid_cached()) < 0)
1563                         return -ENOMEM;
1564 
1565         if (s->pid_file)
1566                 if (asprintf(our_env + n_env++, "PIDFILE=%s", s->pid_file) < 0)
1567                         return -ENOMEM;
1568 
1569         if (s->socket_fd >= 0) {
1570                 union sockaddr_union sa;
1571                 socklen_t salen = sizeof(sa);
1572 
1573                 /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1574                  * useful. Note that we do this only when we are still connected at this point in time, which we might
1575                  * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1576                  * in ENOTCONN), and just use whate we can use. */
1577 
1578                 if (getpeername(s->socket_fd, &sa.sa, &salen) >= 0 &&
1579                     IN_SET(sa.sa.sa_family, AF_INET, AF_INET6, AF_VSOCK)) {
1580                         _cleanup_free_ char *addr = NULL;
1581                         char *t;
1582                         unsigned port;
1583 
1584                         r = sockaddr_pretty(&sa.sa, salen, true, false, &addr);
1585                         if (r < 0)
1586                                 return r;
1587 
1588                         t = strjoin("REMOTE_ADDR=", addr);
1589                         if (!t)
1590                                 return -ENOMEM;
1591                         our_env[n_env++] = t;
1592 
1593                         r = sockaddr_port(&sa.sa, &port);
1594                         if (r < 0)
1595                                 return r;
1596 
1597                         if (asprintf(&t, "REMOTE_PORT=%u", port) < 0)
1598                                 return -ENOMEM;
1599                         our_env[n_env++] = t;
1600                 }
1601         }
1602 
1603         Service *env_source = NULL;
1604         const char *monitor_prefix;
1605         if (flags & EXEC_SETENV_RESULT) {
1606                 env_source = s;
1607                 monitor_prefix = "";
1608         } else if (flags & EXEC_SETENV_MONITOR_RESULT) {
1609                 env_source = service_get_triggering_service(s);
1610                 monitor_prefix = "MONITOR_";
1611         }
1612 
1613         if (env_source) {
1614                 if (asprintf(our_env + n_env++, "%sSERVICE_RESULT=%s", monitor_prefix, service_result_to_string(env_source->result)) < 0)
1615                         return -ENOMEM;
1616 
1617                 if (env_source->main_exec_status.pid > 0 &&
1618                     dual_timestamp_is_set(&env_source->main_exec_status.exit_timestamp)) {
1619                         if (asprintf(our_env + n_env++, "%sEXIT_CODE=%s", monitor_prefix, sigchld_code_to_string(env_source->main_exec_status.code)) < 0)
1620                                 return -ENOMEM;
1621 
1622                         if (env_source->main_exec_status.code == CLD_EXITED)
1623                                 r = asprintf(our_env + n_env++, "%sEXIT_STATUS=%i", monitor_prefix, env_source->main_exec_status.status);
1624                         else
1625                                 r = asprintf(our_env + n_env++, "%sEXIT_STATUS=%s", monitor_prefix, signal_to_string(env_source->main_exec_status.status));
1626 
1627                         if (r < 0)
1628                                 return -ENOMEM;
1629                 }
1630 
1631                 if (env_source != s) {
1632                         if (!sd_id128_is_null(UNIT(env_source)->invocation_id)) {
1633                                 r = asprintf(our_env + n_env++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR,
1634                                              monitor_prefix, SD_ID128_FORMAT_VAL(UNIT(env_source)->invocation_id));
1635                                 if (r < 0)
1636                                         return -ENOMEM;
1637                         }
1638 
1639                         if (asprintf(our_env + n_env++, "%sUNIT=%s", monitor_prefix, UNIT(env_source)->id) < 0)
1640                                 return -ENOMEM;
1641                 }
1642         }
1643 
1644         r = unit_set_exec_params(UNIT(s), &exec_params);
1645         if (r < 0)
1646                 return r;
1647 
1648         final_env = strv_env_merge(exec_params.environment, our_env);
1649         if (!final_env)
1650                 return -ENOMEM;
1651 
1652         /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
1653         SET_FLAG(exec_params.flags, EXEC_NSS_DYNAMIC_BYPASS,
1654                  MANAGER_IS_SYSTEM(UNIT(s)->manager) && unit_has_name(UNIT(s), SPECIAL_DBUS_SERVICE));
1655 
1656         strv_free_and_replace(exec_params.environment, final_env);
1657         exec_params.watchdog_usec = service_get_watchdog_usec(s);
1658         exec_params.selinux_context_net = s->socket_fd_selinux_context_net;
1659         if (s->type == SERVICE_IDLE)
1660                 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1661         exec_params.stdin_fd = s->stdin_fd;
1662         exec_params.stdout_fd = s->stdout_fd;
1663         exec_params.stderr_fd = s->stderr_fd;
1664 
1665         r = exec_spawn(UNIT(s),
1666                        c,
1667                        &s->exec_context,
1668                        &exec_params,
1669                        s->exec_runtime,
1670                        &s->dynamic_creds,
1671                        &pid);
1672         if (r < 0)
1673                 return r;
1674 
1675         s->exec_fd_event_source = TAKE_PTR(exec_fd_source);
1676         s->exec_fd_hot = false;
1677 
1678         r = unit_watch_pid(UNIT(s), pid, true);
1679         if (r < 0)
1680                 return r;
1681 
1682         *ret_pid = pid;
1683 
1684         return 0;
1685 }
1686 
main_pid_good(Service * s)1687 static int main_pid_good(Service *s) {
1688         assert(s);
1689 
1690         /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
1691 
1692         /* If we know the pid file, then let's just check if it is
1693          * still valid */
1694         if (s->main_pid_known) {
1695 
1696                 /* If it's an alien child let's check if it is still
1697                  * alive ... */
1698                 if (s->main_pid_alien && s->main_pid > 0)
1699                         return pid_is_alive(s->main_pid);
1700 
1701                 /* .. otherwise assume we'll get a SIGCHLD for it,
1702                  * which we really should wait for to collect exit
1703                  * status and code */
1704                 return s->main_pid > 0;
1705         }
1706 
1707         /* We don't know the pid */
1708         return -EAGAIN;
1709 }
1710 
control_pid_good(Service * s)1711 static int control_pid_good(Service *s) {
1712         assert(s);
1713 
1714         /* Returns 0 if the control PID is dead, > 0 if it is good. We never actually return < 0 here, but in order to
1715          * make this function as similar as possible to main_pid_good() and cgroup_good(), we pretend that < 0 also
1716          * means: we can't figure it out. */
1717 
1718         return s->control_pid > 0;
1719 }
1720 
cgroup_good(Service * s)1721 static int cgroup_good(Service *s) {
1722         int r;
1723 
1724         assert(s);
1725 
1726         /* Returns 0 if the cgroup is empty or doesn't exist, > 0 if it is exists and is populated, < 0 if we can't
1727          * figure it out */
1728 
1729         if (!UNIT(s)->cgroup_path)
1730                 return 0;
1731 
1732         r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path);
1733         if (r < 0)
1734                 return r;
1735 
1736         return r == 0;
1737 }
1738 
service_shall_restart(Service * s,const char ** reason)1739 static bool service_shall_restart(Service *s, const char **reason) {
1740         assert(s);
1741 
1742         /* Don't restart after manual stops */
1743         if (s->forbid_restart) {
1744                 *reason = "manual stop";
1745                 return false;
1746         }
1747 
1748         /* Never restart if this is configured as special exception */
1749         if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status)) {
1750                 *reason = "prevented by exit status";
1751                 return false;
1752         }
1753 
1754         /* Restart if the exit code/status are configured as restart triggers */
1755         if (exit_status_set_test(&s->restart_force_status,  s->main_exec_status.code, s->main_exec_status.status)) {
1756                 *reason = "forced by exit status";
1757                 return true;
1758         }
1759 
1760         *reason = "restart setting";
1761         switch (s->restart) {
1762 
1763         case SERVICE_RESTART_NO:
1764                 return false;
1765 
1766         case SERVICE_RESTART_ALWAYS:
1767                 return s->result != SERVICE_SKIP_CONDITION;
1768 
1769         case SERVICE_RESTART_ON_SUCCESS:
1770                 return s->result == SERVICE_SUCCESS;
1771 
1772         case SERVICE_RESTART_ON_FAILURE:
1773                 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_SKIP_CONDITION);
1774 
1775         case SERVICE_RESTART_ON_ABNORMAL:
1776                 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE, SERVICE_SKIP_CONDITION);
1777 
1778         case SERVICE_RESTART_ON_WATCHDOG:
1779                 return s->result == SERVICE_FAILURE_WATCHDOG;
1780 
1781         case SERVICE_RESTART_ON_ABORT:
1782                 return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
1783 
1784         default:
1785                 assert_not_reached();
1786         }
1787 }
1788 
service_will_restart(Unit * u)1789 static bool service_will_restart(Unit *u) {
1790         Service *s = SERVICE(u);
1791 
1792         assert(s);
1793 
1794         if (s->will_auto_restart)
1795                 return true;
1796         if (s->state == SERVICE_AUTO_RESTART)
1797                 return true;
1798 
1799         return unit_will_restart_default(u);
1800 }
1801 
service_enter_dead(Service * s,ServiceResult f,bool allow_restart)1802 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1803         ServiceState end_state;
1804         int r;
1805 
1806         assert(s);
1807 
1808         /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
1809          * undo what has already been enqueued. */
1810         if (unit_stop_pending(UNIT(s)))
1811                 allow_restart = false;
1812 
1813         if (s->result == SERVICE_SUCCESS)
1814                 s->result = f;
1815 
1816         if (s->result == SERVICE_SUCCESS) {
1817                 unit_log_success(UNIT(s));
1818                 end_state = SERVICE_DEAD;
1819         } else if (s->result == SERVICE_SKIP_CONDITION) {
1820                 unit_log_skip(UNIT(s), service_result_to_string(s->result));
1821                 end_state = SERVICE_DEAD;
1822         } else {
1823                 unit_log_failure(UNIT(s), service_result_to_string(s->result));
1824                 end_state = SERVICE_FAILED;
1825         }
1826         unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_stop);
1827 
1828         if (!allow_restart)
1829                 log_unit_debug(UNIT(s), "Service restart not allowed.");
1830         else {
1831                 const char *reason;
1832                 bool shall_restart;
1833 
1834                 shall_restart = service_shall_restart(s, &reason);
1835                 log_unit_debug(UNIT(s), "Service will %srestart (%s)",
1836                                         shall_restart ? "" : "not ",
1837                                         reason);
1838                 if (shall_restart)
1839                         s->will_auto_restart = true;
1840         }
1841 
1842         /* Make sure service_release_resources() doesn't destroy our FD store, while we are changing through
1843          * SERVICE_FAILED/SERVICE_DEAD before entering into SERVICE_AUTO_RESTART. */
1844         s->n_keep_fd_store ++;
1845 
1846         service_set_state(s, end_state);
1847 
1848         if (s->will_auto_restart) {
1849                 s->will_auto_restart = false;
1850 
1851                 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
1852                 if (r < 0) {
1853                         s->n_keep_fd_store--;
1854                         goto fail;
1855                 }
1856 
1857                 service_set_state(s, SERVICE_AUTO_RESTART);
1858         } else
1859                 /* If we shan't restart, then flush out the restart counter. But don't do that immediately, so that the
1860                  * user can still introspect the counter. Do so on the next start. */
1861                 s->flush_n_restarts = true;
1862 
1863         /* The new state is in effect, let's decrease the fd store ref counter again. Let's also re-add us to the GC
1864          * queue, so that the fd store is possibly gc'ed again */
1865         s->n_keep_fd_store--;
1866         unit_add_to_gc_queue(UNIT(s));
1867 
1868         /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
1869         s->forbid_restart = false;
1870 
1871         /* We want fresh tmpdirs in case service is started again immediately */
1872         s->exec_runtime = exec_runtime_unref(s->exec_runtime, true);
1873 
1874         /* Also, remove the runtime directory */
1875         unit_destroy_runtime_data(UNIT(s), &s->exec_context);
1876 
1877         /* Get rid of the IPC bits of the user */
1878         unit_unref_uid_gid(UNIT(s), true);
1879 
1880         /* Release the user, and destroy it if we are the only remaining owner */
1881         dynamic_creds_destroy(&s->dynamic_creds);
1882 
1883         /* Try to delete the pid file. At this point it will be
1884          * out-of-date, and some software might be confused by it, so
1885          * let's remove it. */
1886         if (s->pid_file)
1887                 (void) unlink(s->pid_file);
1888 
1889         /* Reset TTY ownership if necessary */
1890         exec_context_revert_tty(&s->exec_context);
1891 
1892         return;
1893 
1894 fail:
1895         log_unit_warning_errno(UNIT(s), r, "Failed to run install restart timer: %m");
1896         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1897 }
1898 
service_enter_stop_post(Service * s,ServiceResult f)1899 static void service_enter_stop_post(Service *s, ServiceResult f) {
1900         int r;
1901         assert(s);
1902 
1903         if (s->result == SERVICE_SUCCESS)
1904                 s->result = f;
1905 
1906         service_unwatch_control_pid(s);
1907         (void) unit_enqueue_rewatch_pids(UNIT(s));
1908 
1909         s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1910         if (s->control_command) {
1911                 s->control_command_id = SERVICE_EXEC_STOP_POST;
1912 
1913                 r = service_spawn(s,
1914                                   s->control_command,
1915                                   s->timeout_stop_usec,
1916                                   EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_IS_CONTROL|EXEC_SETENV_RESULT|EXEC_CONTROL_CGROUP,
1917                                   &s->control_pid);
1918                 if (r < 0)
1919                         goto fail;
1920 
1921                 service_set_state(s, SERVICE_STOP_POST);
1922         } else
1923                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1924 
1925         return;
1926 
1927 fail:
1928         log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
1929         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1930 }
1931 
state_to_kill_operation(Service * s,ServiceState state)1932 static int state_to_kill_operation(Service *s, ServiceState state) {
1933         switch (state) {
1934 
1935         case SERVICE_STOP_WATCHDOG:
1936         case SERVICE_FINAL_WATCHDOG:
1937                 return KILL_WATCHDOG;
1938 
1939         case SERVICE_STOP_SIGTERM:
1940                 if (unit_has_job_type(UNIT(s), JOB_RESTART))
1941                         return KILL_RESTART;
1942                 _fallthrough_;
1943 
1944         case SERVICE_FINAL_SIGTERM:
1945                 return KILL_TERMINATE;
1946 
1947         case SERVICE_STOP_SIGKILL:
1948         case SERVICE_FINAL_SIGKILL:
1949                 return KILL_KILL;
1950 
1951         default:
1952                 return _KILL_OPERATION_INVALID;
1953         }
1954 }
1955 
service_enter_signal(Service * s,ServiceState state,ServiceResult f)1956 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1957         int kill_operation, r;
1958 
1959         assert(s);
1960 
1961         if (s->result == SERVICE_SUCCESS)
1962                 s->result = f;
1963 
1964         /* Before sending any signal, make sure we track all members of this cgroup */
1965         (void) unit_watch_all_pids(UNIT(s));
1966 
1967         /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
1968          * died now */
1969         (void) unit_enqueue_rewatch_pids(UNIT(s));
1970 
1971         kill_operation = state_to_kill_operation(s, state);
1972         r = unit_kill_context(
1973                         UNIT(s),
1974                         &s->kill_context,
1975                         kill_operation,
1976                         s->main_pid,
1977                         s->control_pid,
1978                         s->main_pid_alien);
1979         if (r < 0)
1980                 goto fail;
1981 
1982         if (r > 0) {
1983                 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC),
1984                                       kill_operation == KILL_WATCHDOG ? service_timeout_abort_usec(s) : s->timeout_stop_usec));
1985                 if (r < 0)
1986                         goto fail;
1987 
1988                 service_set_state(s, state);
1989         } else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
1990                 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1991         else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1992                 service_enter_stop_post(s, SERVICE_SUCCESS);
1993         else if (IN_SET(state, SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM) && s->kill_context.send_sigkill)
1994                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1995         else
1996                 service_enter_dead(s, SERVICE_SUCCESS, true);
1997 
1998         return;
1999 
2000 fail:
2001         log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
2002 
2003         if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
2004                 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
2005         else
2006                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2007 }
2008 
service_enter_stop_by_notify(Service * s)2009 static void service_enter_stop_by_notify(Service *s) {
2010         assert(s);
2011 
2012         (void) unit_enqueue_rewatch_pids(UNIT(s));
2013 
2014         service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
2015 
2016         /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2017         service_set_state(s, SERVICE_STOP_SIGTERM);
2018 }
2019 
service_enter_stop(Service * s,ServiceResult f)2020 static void service_enter_stop(Service *s, ServiceResult f) {
2021         int r;
2022 
2023         assert(s);
2024 
2025         if (s->result == SERVICE_SUCCESS)
2026                 s->result = f;
2027 
2028         service_unwatch_control_pid(s);
2029         (void) unit_enqueue_rewatch_pids(UNIT(s));
2030 
2031         s->control_command = s->exec_command[SERVICE_EXEC_STOP];
2032         if (s->control_command) {
2033                 s->control_command_id = SERVICE_EXEC_STOP;
2034 
2035                 r = service_spawn(s,
2036                                   s->control_command,
2037                                   s->timeout_stop_usec,
2038                                   EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_SETENV_RESULT|EXEC_CONTROL_CGROUP,
2039                                   &s->control_pid);
2040                 if (r < 0)
2041                         goto fail;
2042 
2043                 service_set_state(s, SERVICE_STOP);
2044         } else
2045                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2046 
2047         return;
2048 
2049 fail:
2050         log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop' task: %m");
2051         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2052 }
2053 
service_good(Service * s)2054 static bool service_good(Service *s) {
2055         int main_pid_ok;
2056         assert(s);
2057 
2058         if (s->type == SERVICE_DBUS && !s->bus_name_good)
2059                 return false;
2060 
2061         main_pid_ok = main_pid_good(s);
2062         if (main_pid_ok > 0) /* It's alive */
2063                 return true;
2064         if (main_pid_ok == 0) /* It's dead */
2065                 return false;
2066 
2067         /* OK, we don't know anything about the main PID, maybe
2068          * because there is none. Let's check the control group
2069          * instead. */
2070 
2071         return cgroup_good(s) != 0;
2072 }
2073 
service_enter_running(Service * s,ServiceResult f)2074 static void service_enter_running(Service *s, ServiceResult f) {
2075         assert(s);
2076 
2077         if (s->result == SERVICE_SUCCESS)
2078                 s->result = f;
2079 
2080         service_unwatch_control_pid(s);
2081 
2082         if (s->result != SERVICE_SUCCESS)
2083                 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2084         else if (service_good(s)) {
2085 
2086                 /* If there are any queued up sd_notify() notifications, process them now */
2087                 if (s->notify_state == NOTIFY_RELOADING)
2088                         service_enter_reload_by_notify(s);
2089                 else if (s->notify_state == NOTIFY_STOPPING)
2090                         service_enter_stop_by_notify(s);
2091                 else {
2092                         service_set_state(s, SERVICE_RUNNING);
2093                         service_arm_timer(s, service_running_timeout(s));
2094                 }
2095 
2096         } else if (s->remain_after_exit)
2097                 service_set_state(s, SERVICE_EXITED);
2098         else
2099                 service_enter_stop(s, SERVICE_SUCCESS);
2100 }
2101 
service_enter_start_post(Service * s)2102 static void service_enter_start_post(Service *s) {
2103         int r;
2104         assert(s);
2105 
2106         service_unwatch_control_pid(s);
2107         service_reset_watchdog(s);
2108 
2109         s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
2110         if (s->control_command) {
2111                 s->control_command_id = SERVICE_EXEC_START_POST;
2112 
2113                 r = service_spawn(s,
2114                                   s->control_command,
2115                                   s->timeout_start_usec,
2116                                   EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_CONTROL_CGROUP,
2117                                   &s->control_pid);
2118                 if (r < 0)
2119                         goto fail;
2120 
2121                 service_set_state(s, SERVICE_START_POST);
2122         } else
2123                 service_enter_running(s, SERVICE_SUCCESS);
2124 
2125         return;
2126 
2127 fail:
2128         log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
2129         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2130 }
2131 
service_kill_control_process(Service * s)2132 static void service_kill_control_process(Service *s) {
2133         int r;
2134 
2135         assert(s);
2136 
2137         if (s->control_pid <= 0)
2138                 return;
2139 
2140         r = kill_and_sigcont(s->control_pid, SIGKILL);
2141         if (r < 0) {
2142                 _cleanup_free_ char *comm = NULL;
2143 
2144                 (void) get_process_comm(s->control_pid, &comm);
2145 
2146                 log_unit_debug_errno(UNIT(s), r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m",
2147                                      s->control_pid, strna(comm));
2148         }
2149 }
2150 
service_adverse_to_leftover_processes(Service * s)2151 static int service_adverse_to_leftover_processes(Service *s) {
2152         assert(s);
2153 
2154         /* KillMode=mixed and control group are used to indicate that all process should be killed off.
2155          * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2156          * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2157          * time is quite variable (so Timeout settings aren't of use).
2158          *
2159          * Here we take these two factors and refuse to start a service if there are existing processes
2160          * within a control group. Databases, while generally having some protection against multiple
2161          * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
2162          * aren't as rigoriously written to protect aganst against multiple use. */
2163 
2164         if (unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_start) > 0 &&
2165             IN_SET(s->kill_context.kill_mode, KILL_MIXED, KILL_CONTROL_GROUP) &&
2166             !s->kill_context.send_sigkill)
2167                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EBUSY),
2168                                            "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2169 
2170         return 0;
2171 }
2172 
service_enter_start(Service * s)2173 static void service_enter_start(Service *s) {
2174         ExecCommand *c;
2175         usec_t timeout;
2176         pid_t pid;
2177         int r;
2178 
2179         assert(s);
2180 
2181         service_unwatch_control_pid(s);
2182         service_unwatch_main_pid(s);
2183 
2184         r = service_adverse_to_leftover_processes(s);
2185         if (r < 0)
2186                 goto fail;
2187 
2188         if (s->type == SERVICE_FORKING) {
2189                 s->control_command_id = SERVICE_EXEC_START;
2190                 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2191 
2192                 s->main_command = NULL;
2193         } else {
2194                 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2195                 s->control_command = NULL;
2196 
2197                 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2198         }
2199 
2200         if (!c) {
2201                 if (s->type != SERVICE_ONESHOT) {
2202                         /* There's no command line configured for the main command? Hmm, that is strange.
2203                          * This can only happen if the configuration changes at runtime. In this case,
2204                          * let's enter a failure state. */
2205                         r = log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENXIO), "There's no 'start' task anymore we could start.");
2206                         goto fail;
2207                 }
2208 
2209                 /* We force a fake state transition here. Otherwise, the unit would go directly from
2210                  * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
2211                  * in between. This way we can later trigger actions that depend on the state
2212                  * transition, including SuccessAction=. */
2213                 service_set_state(s, SERVICE_START);
2214 
2215                 service_enter_start_post(s);
2216                 return;
2217         }
2218 
2219         if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
2220                 /* For simple + idle this is the main process. We don't apply any timeout here, but
2221                  * service_enter_running() will later apply the .runtime_max_usec timeout. */
2222                 timeout = USEC_INFINITY;
2223         else
2224                 timeout = s->timeout_start_usec;
2225 
2226         r = service_spawn(s,
2227                           c,
2228                           timeout,
2229                           EXEC_PASS_FDS|EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG|EXEC_WRITE_CREDENTIALS|EXEC_SETENV_MONITOR_RESULT,
2230                           &pid);
2231         if (r < 0)
2232                 goto fail;
2233 
2234         if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE)) {
2235                 /* For simple services we immediately start
2236                  * the START_POST binaries. */
2237 
2238                 service_set_main_pid(s, pid);
2239                 service_enter_start_post(s);
2240 
2241         } else  if (s->type == SERVICE_FORKING) {
2242 
2243                 /* For forking services we wait until the start
2244                  * process exited. */
2245 
2246                 s->control_pid = pid;
2247                 service_set_state(s, SERVICE_START);
2248 
2249         } else if (IN_SET(s->type, SERVICE_ONESHOT, SERVICE_DBUS, SERVICE_NOTIFY, SERVICE_EXEC)) {
2250 
2251                 /* For oneshot services we wait until the start process exited, too, but it is our main process. */
2252 
2253                 /* For D-Bus services we know the main pid right away, but wait for the bus name to appear on the
2254                  * bus. 'notify' and 'exec' services are similar. */
2255 
2256                 service_set_main_pid(s, pid);
2257                 service_set_state(s, SERVICE_START);
2258         } else
2259                 assert_not_reached();
2260 
2261         return;
2262 
2263 fail:
2264         log_unit_warning_errno(UNIT(s), r, "Failed to run 'start' task: %m");
2265         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2266 }
2267 
service_enter_start_pre(Service * s)2268 static void service_enter_start_pre(Service *s) {
2269         int r;
2270 
2271         assert(s);
2272 
2273         service_unwatch_control_pid(s);
2274 
2275         s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
2276         if (s->control_command) {
2277 
2278                 r = service_adverse_to_leftover_processes(s);
2279                 if (r < 0)
2280                         goto fail;
2281 
2282                 s->control_command_id = SERVICE_EXEC_START_PRE;
2283 
2284                 r = service_spawn(s,
2285                                   s->control_command,
2286                                   s->timeout_start_usec,
2287                                   EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_APPLY_TTY_STDIN|EXEC_SETENV_MONITOR_RESULT,
2288                                   &s->control_pid);
2289                 if (r < 0)
2290                         goto fail;
2291 
2292                 service_set_state(s, SERVICE_START_PRE);
2293         } else
2294                 service_enter_start(s);
2295 
2296         return;
2297 
2298 fail:
2299         log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
2300         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2301 }
2302 
service_enter_condition(Service * s)2303 static void service_enter_condition(Service *s) {
2304         int r;
2305 
2306         assert(s);
2307 
2308         service_unwatch_control_pid(s);
2309 
2310         s->control_command = s->exec_command[SERVICE_EXEC_CONDITION];
2311         if (s->control_command) {
2312 
2313                 r = service_adverse_to_leftover_processes(s);
2314                 if (r < 0)
2315                         goto fail;
2316 
2317                 s->control_command_id = SERVICE_EXEC_CONDITION;
2318 
2319                 r = service_spawn(s,
2320                                   s->control_command,
2321                                   s->timeout_start_usec,
2322                                   EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_APPLY_TTY_STDIN,
2323                                   &s->control_pid);
2324 
2325                 if (r < 0)
2326                         goto fail;
2327 
2328                 service_set_state(s, SERVICE_CONDITION);
2329         } else
2330                 service_enter_start_pre(s);
2331 
2332         return;
2333 
2334 fail:
2335         log_unit_warning_errno(UNIT(s), r, "Failed to run 'exec-condition' task: %m");
2336         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2337 }
2338 
service_enter_restart(Service * s)2339 static void service_enter_restart(Service *s) {
2340         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2341         int r;
2342 
2343         assert(s);
2344 
2345         if (unit_has_job_type(UNIT(s), JOB_STOP)) {
2346                 /* Don't restart things if we are going down anyway */
2347                 log_unit_info(UNIT(s), "Stop job pending for unit, skipping automatic restart.");
2348                 return;
2349         }
2350 
2351         /* Any units that are bound to this service must also be
2352          * restarted. We use JOB_RESTART (instead of the more obvious
2353          * JOB_START) here so that those dependency jobs will be added
2354          * as well. */
2355         r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_REPLACE, NULL, &error, NULL);
2356         if (r < 0)
2357                 goto fail;
2358 
2359         /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't fully
2360          * stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset the counter
2361          * explicitly however via the usual "systemctl reset-failure" logic. */
2362         s->n_restarts ++;
2363         s->flush_n_restarts = false;
2364 
2365         log_unit_struct(UNIT(s), LOG_INFO,
2366                         "MESSAGE_ID=" SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR,
2367                         LOG_UNIT_INVOCATION_ID(UNIT(s)),
2368                         LOG_UNIT_MESSAGE(UNIT(s),
2369                                          "Scheduled restart job, restart counter is at %u.", s->n_restarts),
2370                         "N_RESTARTS=%u", s->n_restarts);
2371 
2372         /* Notify clients about changed restart counter */
2373         unit_add_to_dbus_queue(UNIT(s));
2374 
2375         /* Note that we stay in the SERVICE_AUTO_RESTART state here,
2376          * it will be canceled as part of the service_stop() call that
2377          * is executed as part of JOB_RESTART. */
2378 
2379         return;
2380 
2381 fail:
2382         log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, r));
2383         service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
2384 }
2385 
service_enter_reload_by_notify(Service * s)2386 static void service_enter_reload_by_notify(Service *s) {
2387         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2388         int r;
2389 
2390         assert(s);
2391 
2392         service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_start_usec));
2393         service_set_state(s, SERVICE_RELOAD);
2394 
2395         /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2396         r = manager_propagate_reload(UNIT(s)->manager, UNIT(s), JOB_FAIL, &error);
2397         if (r < 0)
2398                 log_unit_warning(UNIT(s), "Failed to schedule propagation of reload: %s", bus_error_message(&error, r));
2399 }
2400 
service_enter_reload(Service * s)2401 static void service_enter_reload(Service *s) {
2402         int r;
2403 
2404         assert(s);
2405 
2406         service_unwatch_control_pid(s);
2407         s->reload_result = SERVICE_SUCCESS;
2408 
2409         s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
2410         if (s->control_command) {
2411                 s->control_command_id = SERVICE_EXEC_RELOAD;
2412 
2413                 r = service_spawn(s,
2414                                   s->control_command,
2415                                   s->timeout_start_usec,
2416                                   EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_CONTROL_CGROUP,
2417                                   &s->control_pid);
2418                 if (r < 0)
2419                         goto fail;
2420 
2421                 service_set_state(s, SERVICE_RELOAD);
2422         } else
2423                 service_enter_running(s, SERVICE_SUCCESS);
2424 
2425         return;
2426 
2427 fail:
2428         log_unit_warning_errno(UNIT(s), r, "Failed to run 'reload' task: %m");
2429         s->reload_result = SERVICE_FAILURE_RESOURCES;
2430         service_enter_running(s, SERVICE_SUCCESS);
2431 }
2432 
service_run_next_control(Service * s)2433 static void service_run_next_control(Service *s) {
2434         usec_t timeout;
2435         int r;
2436 
2437         assert(s);
2438         assert(s->control_command);
2439         assert(s->control_command->command_next);
2440 
2441         assert(s->control_command_id != SERVICE_EXEC_START);
2442 
2443         s->control_command = s->control_command->command_next;
2444         service_unwatch_control_pid(s);
2445 
2446         if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
2447                 timeout = s->timeout_start_usec;
2448         else
2449                 timeout = s->timeout_stop_usec;
2450 
2451         r = service_spawn(s,
2452                           s->control_command,
2453                           timeout,
2454                           EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|
2455                           (IN_SET(s->control_command_id, SERVICE_EXEC_CONDITION, SERVICE_EXEC_START_PRE, SERVICE_EXEC_STOP_POST) ? EXEC_APPLY_TTY_STDIN : 0)|
2456                           (IN_SET(s->control_command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST) ? EXEC_SETENV_RESULT : 0)|
2457                           (IN_SET(s->control_command_id, SERVICE_EXEC_START_PRE, SERVICE_EXEC_START) ? EXEC_SETENV_MONITOR_RESULT : 0)|
2458                           (IN_SET(s->control_command_id, SERVICE_EXEC_START_POST, SERVICE_EXEC_RELOAD, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST) ? EXEC_CONTROL_CGROUP : 0),
2459                           &s->control_pid);
2460         if (r < 0)
2461                 goto fail;
2462 
2463         return;
2464 
2465 fail:
2466         log_unit_warning_errno(UNIT(s), r, "Failed to run next control task: %m");
2467 
2468         if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START_POST, SERVICE_STOP))
2469                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2470         else if (s->state == SERVICE_STOP_POST)
2471                 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2472         else if (s->state == SERVICE_RELOAD) {
2473                 s->reload_result = SERVICE_FAILURE_RESOURCES;
2474                 service_enter_running(s, SERVICE_SUCCESS);
2475         } else
2476                 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2477 }
2478 
service_run_next_main(Service * s)2479 static void service_run_next_main(Service *s) {
2480         pid_t pid;
2481         int r;
2482 
2483         assert(s);
2484         assert(s->main_command);
2485         assert(s->main_command->command_next);
2486         assert(s->type == SERVICE_ONESHOT);
2487 
2488         s->main_command = s->main_command->command_next;
2489         service_unwatch_main_pid(s);
2490 
2491         r = service_spawn(s,
2492                           s->main_command,
2493                           s->timeout_start_usec,
2494                           EXEC_PASS_FDS|EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG|EXEC_SETENV_MONITOR_RESULT,
2495                           &pid);
2496         if (r < 0)
2497                 goto fail;
2498 
2499         service_set_main_pid(s, pid);
2500 
2501         return;
2502 
2503 fail:
2504         log_unit_warning_errno(UNIT(s), r, "Failed to run next main task: %m");
2505         service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2506 }
2507 
service_start(Unit * u)2508 static int service_start(Unit *u) {
2509         Service *s = SERVICE(u);
2510         int r;
2511 
2512         assert(s);
2513 
2514         /* We cannot fulfill this request right now, try again later
2515          * please! */
2516         if (IN_SET(s->state,
2517                    SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2518                    SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL, SERVICE_CLEANING))
2519                 return -EAGAIN;
2520 
2521         /* Already on it! */
2522         if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
2523                 return 0;
2524 
2525         /* A service that will be restarted must be stopped first to
2526          * trigger BindsTo and/or OnFailure dependencies. If a user
2527          * does not want to wait for the holdoff time to elapse, the
2528          * service should be manually restarted, not started. We
2529          * simply return EAGAIN here, so that any start jobs stay
2530          * queued, and assume that the auto restart timer will
2531          * eventually trigger the restart. */
2532         if (s->state == SERVICE_AUTO_RESTART)
2533                 return -EAGAIN;
2534 
2535         assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED));
2536 
2537         r = unit_acquire_invocation_id(u);
2538         if (r < 0)
2539                 return r;
2540 
2541         s->result = SERVICE_SUCCESS;
2542         s->reload_result = SERVICE_SUCCESS;
2543         s->main_pid_known = false;
2544         s->main_pid_alien = false;
2545         s->forbid_restart = false;
2546 
2547         s->status_text = mfree(s->status_text);
2548         s->status_errno = 0;
2549 
2550         s->notify_state = NOTIFY_UNKNOWN;
2551 
2552         s->watchdog_original_usec = s->watchdog_usec;
2553         s->watchdog_override_enable = false;
2554         s->watchdog_override_usec = USEC_INFINITY;
2555 
2556         exec_command_reset_status_list_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
2557         exec_status_reset(&s->main_exec_status);
2558 
2559         /* This is not an automatic restart? Flush the restart counter then */
2560         if (s->flush_n_restarts) {
2561                 s->n_restarts = 0;
2562                 s->flush_n_restarts = false;
2563         }
2564 
2565         u->reset_accounting = true;
2566 
2567         service_enter_condition(s);
2568         return 1;
2569 }
2570 
service_stop(Unit * u)2571 static int service_stop(Unit *u) {
2572         Service *s = SERVICE(u);
2573 
2574         assert(s);
2575 
2576         /* Don't create restart jobs from manual stops. */
2577         s->forbid_restart = true;
2578 
2579         /* Already on it */
2580         if (IN_SET(s->state,
2581                    SERVICE_STOP, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2582                    SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
2583                 return 0;
2584 
2585         /* A restart will be scheduled or is in progress. */
2586         if (s->state == SERVICE_AUTO_RESTART) {
2587                 service_set_state(s, SERVICE_DEAD);
2588                 return 0;
2589         }
2590 
2591         /* If there's already something running we go directly into
2592          * kill mode. */
2593         if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD, SERVICE_STOP_WATCHDOG)) {
2594                 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2595                 return 0;
2596         }
2597 
2598         /* If we are currently cleaning, then abort it, brutally. */
2599         if (s->state == SERVICE_CLEANING) {
2600                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
2601                 return 0;
2602         }
2603 
2604         assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
2605 
2606         service_enter_stop(s, SERVICE_SUCCESS);
2607         return 1;
2608 }
2609 
service_reload(Unit * u)2610 static int service_reload(Unit *u) {
2611         Service *s = SERVICE(u);
2612 
2613         assert(s);
2614 
2615         assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
2616 
2617         service_enter_reload(s);
2618         return 1;
2619 }
2620 
service_can_reload(Unit * u)2621 _pure_ static bool service_can_reload(Unit *u) {
2622         Service *s = SERVICE(u);
2623 
2624         assert(s);
2625 
2626         return !!s->exec_command[SERVICE_EXEC_RELOAD];
2627 }
2628 
service_exec_command_index(Unit * u,ServiceExecCommand id,ExecCommand * current)2629 static unsigned service_exec_command_index(Unit *u, ServiceExecCommand id, ExecCommand *current) {
2630         Service *s = SERVICE(u);
2631         unsigned idx = 0;
2632         ExecCommand *first, *c;
2633 
2634         assert(s);
2635         assert(id >= 0);
2636         assert(id < _SERVICE_EXEC_COMMAND_MAX);
2637 
2638         first = s->exec_command[id];
2639 
2640         /* Figure out where we are in the list by walking back to the beginning */
2641         for (c = current; c != first; c = c->command_prev)
2642                 idx++;
2643 
2644         return idx;
2645 }
2646 
service_serialize_exec_command(Unit * u,FILE * f,ExecCommand * command)2647 static int service_serialize_exec_command(Unit *u, FILE *f, ExecCommand *command) {
2648         _cleanup_free_ char *args = NULL, *p = NULL;
2649         Service *s = SERVICE(u);
2650         const char *type, *key;
2651         ServiceExecCommand id;
2652         size_t length = 0;
2653         unsigned idx;
2654 
2655         assert(s);
2656         assert(f);
2657 
2658         if (!command)
2659                 return 0;
2660 
2661         if (command == s->control_command) {
2662                 type = "control";
2663                 id = s->control_command_id;
2664         } else {
2665                 type = "main";
2666                 id = SERVICE_EXEC_START;
2667         }
2668 
2669         idx = service_exec_command_index(u, id, command);
2670 
2671         STRV_FOREACH(arg, command->argv) {
2672                 _cleanup_free_ char *e = NULL;
2673                 size_t n;
2674 
2675                 e = cescape(*arg);
2676                 if (!e)
2677                         return log_oom();
2678 
2679                 n = strlen(e);
2680                 if (!GREEDY_REALLOC(args, length + 2 + n + 2))
2681                         return log_oom();
2682 
2683                 if (length > 0)
2684                         args[length++] = ' ';
2685 
2686                 args[length++] = '"';
2687                 memcpy(args + length, e, n);
2688                 length += n;
2689                 args[length++] = '"';
2690         }
2691 
2692         if (!GREEDY_REALLOC(args, length + 1))
2693                 return log_oom();
2694 
2695         args[length++] = 0;
2696 
2697         p = cescape(command->path);
2698         if (!p)
2699                 return log_oom();
2700 
2701         key = strjoina(type, "-command");
2702         (void) serialize_item_format(f, key, "%s %u %s %s", service_exec_command_to_string(id), idx, p, args);
2703 
2704         return 0;
2705 }
2706 
service_serialize(Unit * u,FILE * f,FDSet * fds)2707 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2708         Service *s = SERVICE(u);
2709         int r;
2710 
2711         assert(u);
2712         assert(f);
2713         assert(fds);
2714 
2715         (void) serialize_item(f, "state", service_state_to_string(s->state));
2716         (void) serialize_item(f, "result", service_result_to_string(s->result));
2717         (void) serialize_item(f, "reload-result", service_result_to_string(s->reload_result));
2718 
2719         if (s->control_pid > 0)
2720                 (void) serialize_item_format(f, "control-pid", PID_FMT, s->control_pid);
2721 
2722         if (s->main_pid_known && s->main_pid > 0)
2723                 (void) serialize_item_format(f, "main-pid", PID_FMT, s->main_pid);
2724 
2725         (void) serialize_bool(f, "main-pid-known", s->main_pid_known);
2726         (void) serialize_bool(f, "bus-name-good", s->bus_name_good);
2727         (void) serialize_bool(f, "bus-name-owner", s->bus_name_owner);
2728 
2729         (void) serialize_item_format(f, "n-restarts", "%u", s->n_restarts);
2730         (void) serialize_bool(f, "flush-n-restarts", s->flush_n_restarts);
2731 
2732         r = serialize_item_escaped(f, "status-text", s->status_text);
2733         if (r < 0)
2734                 return r;
2735 
2736         service_serialize_exec_command(u, f, s->control_command);
2737         service_serialize_exec_command(u, f, s->main_command);
2738 
2739         r = serialize_fd(f, fds, "stdin-fd", s->stdin_fd);
2740         if (r < 0)
2741                 return r;
2742         r = serialize_fd(f, fds, "stdout-fd", s->stdout_fd);
2743         if (r < 0)
2744                 return r;
2745         r = serialize_fd(f, fds, "stderr-fd", s->stderr_fd);
2746         if (r < 0)
2747                 return r;
2748 
2749         if (s->exec_fd_event_source) {
2750                 r = serialize_fd(f, fds, "exec-fd", sd_event_source_get_io_fd(s->exec_fd_event_source));
2751                 if (r < 0)
2752                         return r;
2753 
2754                 (void) serialize_bool(f, "exec-fd-hot", s->exec_fd_hot);
2755         }
2756 
2757         if (UNIT_ISSET(s->accept_socket)) {
2758                 r = serialize_item(f, "accept-socket", UNIT_DEREF(s->accept_socket)->id);
2759                 if (r < 0)
2760                         return r;
2761         }
2762 
2763         r = serialize_fd(f, fds, "socket-fd", s->socket_fd);
2764         if (r < 0)
2765                 return r;
2766 
2767         LIST_FOREACH(fd_store, fs, s->fd_store) {
2768                 _cleanup_free_ char *c = NULL;
2769                 int copy;
2770 
2771                 copy = fdset_put_dup(fds, fs->fd);
2772                 if (copy < 0)
2773                         return log_error_errno(copy, "Failed to copy file descriptor for serialization: %m");
2774 
2775                 c = cescape(fs->fdname);
2776                 if (!c)
2777                         return log_oom();
2778 
2779                 (void) serialize_item_format(f, "fd-store-fd", "%i \"%s\" %i", copy, c, fs->do_poll);
2780         }
2781 
2782         if (s->main_exec_status.pid > 0) {
2783                 (void) serialize_item_format(f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
2784                 (void) serialize_dual_timestamp(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2785                 (void) serialize_dual_timestamp(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2786 
2787                 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2788                         (void) serialize_item_format(f, "main-exec-status-code", "%i", s->main_exec_status.code);
2789                         (void) serialize_item_format(f, "main-exec-status-status", "%i", s->main_exec_status.status);
2790                 }
2791         }
2792 
2793         (void) serialize_dual_timestamp(f, "watchdog-timestamp", &s->watchdog_timestamp);
2794         (void) serialize_bool(f, "forbid-restart", s->forbid_restart);
2795 
2796         if (s->watchdog_override_enable)
2797                 (void) serialize_item_format(f, "watchdog-override-usec", USEC_FMT, s->watchdog_override_usec);
2798 
2799         if (s->watchdog_original_usec != USEC_INFINITY)
2800                 (void) serialize_item_format(f, "watchdog-original-usec", USEC_FMT, s->watchdog_original_usec);
2801 
2802         return 0;
2803 }
2804 
service_deserialize_exec_command(Unit * u,const char * key,const char * value)2805 int service_deserialize_exec_command(
2806                 Unit *u,
2807                 const char *key,
2808                 const char *value) {
2809 
2810         Service *s = SERVICE(u);
2811         int r;
2812         unsigned idx = 0, i;
2813         bool control, found = false;
2814         ServiceExecCommand id = _SERVICE_EXEC_COMMAND_INVALID;
2815         ExecCommand *command = NULL;
2816         _cleanup_free_ char *path = NULL;
2817         _cleanup_strv_free_ char **argv = NULL;
2818 
2819         enum ExecCommandState {
2820                 STATE_EXEC_COMMAND_TYPE,
2821                 STATE_EXEC_COMMAND_INDEX,
2822                 STATE_EXEC_COMMAND_PATH,
2823                 STATE_EXEC_COMMAND_ARGS,
2824                 _STATE_EXEC_COMMAND_MAX,
2825                 _STATE_EXEC_COMMAND_INVALID = -EINVAL,
2826         } state;
2827 
2828         assert(s);
2829         assert(key);
2830         assert(value);
2831 
2832         control = streq(key, "control-command");
2833 
2834         state = STATE_EXEC_COMMAND_TYPE;
2835 
2836         for (;;) {
2837                 _cleanup_free_ char *arg = NULL;
2838 
2839                 r = extract_first_word(&value, &arg, NULL, EXTRACT_CUNESCAPE | EXTRACT_UNQUOTE);
2840                 if (r < 0)
2841                         return r;
2842                 if (r == 0)
2843                         break;
2844 
2845                 switch (state) {
2846                 case STATE_EXEC_COMMAND_TYPE:
2847                         id = service_exec_command_from_string(arg);
2848                         if (id < 0)
2849                                 return id;
2850 
2851                         state = STATE_EXEC_COMMAND_INDEX;
2852                         break;
2853                 case STATE_EXEC_COMMAND_INDEX:
2854                         r = safe_atou(arg, &idx);
2855                         if (r < 0)
2856                                 return r;
2857 
2858                         state = STATE_EXEC_COMMAND_PATH;
2859                         break;
2860                 case STATE_EXEC_COMMAND_PATH:
2861                         path = TAKE_PTR(arg);
2862                         state = STATE_EXEC_COMMAND_ARGS;
2863                         break;
2864                 case STATE_EXEC_COMMAND_ARGS:
2865                         r = strv_extend(&argv, arg);
2866                         if (r < 0)
2867                                 return -ENOMEM;
2868                         break;
2869                 default:
2870                         assert_not_reached();
2871                 }
2872         }
2873 
2874         if (state != STATE_EXEC_COMMAND_ARGS)
2875                 return -EINVAL;
2876         if (strv_isempty(argv))
2877                 return -EINVAL; /* At least argv[0] must be always present. */
2878 
2879         /* Let's check whether exec command on given offset matches data that we just deserialized */
2880         for (command = s->exec_command[id], i = 0; command; command = command->command_next, i++) {
2881                 if (i != idx)
2882                         continue;
2883 
2884                 found = strv_equal(argv, command->argv) && streq(command->path, path);
2885                 break;
2886         }
2887 
2888         if (!found) {
2889                 /* Command at the index we serialized is different, let's look for command that exactly
2890                  * matches but is on different index. If there is no such command we will not resume execution. */
2891                 for (command = s->exec_command[id]; command; command = command->command_next)
2892                         if (strv_equal(command->argv, argv) && streq(command->path, path))
2893                                 break;
2894         }
2895 
2896         if (command && control) {
2897                 s->control_command = command;
2898                 s->control_command_id = id;
2899         } else if (command)
2900                 s->main_command = command;
2901         else
2902                 log_unit_warning(u, "Current command vanished from the unit file, execution of the command list won't be resumed.");
2903 
2904         return 0;
2905 }
2906 
service_deserialize_item(Unit * u,const char * key,const char * value,FDSet * fds)2907 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2908         Service *s = SERVICE(u);
2909         int r;
2910 
2911         assert(u);
2912         assert(key);
2913         assert(value);
2914         assert(fds);
2915 
2916         if (streq(key, "state")) {
2917                 ServiceState state;
2918 
2919                 state = service_state_from_string(value);
2920                 if (state < 0)
2921                         log_unit_debug(u, "Failed to parse state value: %s", value);
2922                 else
2923                         s->deserialized_state = state;
2924         } else if (streq(key, "result")) {
2925                 ServiceResult f;
2926 
2927                 f = service_result_from_string(value);
2928                 if (f < 0)
2929                         log_unit_debug(u, "Failed to parse result value: %s", value);
2930                 else if (f != SERVICE_SUCCESS)
2931                         s->result = f;
2932 
2933         } else if (streq(key, "reload-result")) {
2934                 ServiceResult f;
2935 
2936                 f = service_result_from_string(value);
2937                 if (f < 0)
2938                         log_unit_debug(u, "Failed to parse reload result value: %s", value);
2939                 else if (f != SERVICE_SUCCESS)
2940                         s->reload_result = f;
2941 
2942         } else if (streq(key, "control-pid")) {
2943                 pid_t pid;
2944 
2945                 if (parse_pid(value, &pid) < 0)
2946                         log_unit_debug(u, "Failed to parse control-pid value: %s", value);
2947                 else
2948                         s->control_pid = pid;
2949         } else if (streq(key, "main-pid")) {
2950                 pid_t pid;
2951 
2952                 if (parse_pid(value, &pid) < 0)
2953                         log_unit_debug(u, "Failed to parse main-pid value: %s", value);
2954                 else
2955                         (void) service_set_main_pid(s, pid);
2956         } else if (streq(key, "main-pid-known")) {
2957                 int b;
2958 
2959                 b = parse_boolean(value);
2960                 if (b < 0)
2961                         log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
2962                 else
2963                         s->main_pid_known = b;
2964         } else if (streq(key, "bus-name-good")) {
2965                 int b;
2966 
2967                 b = parse_boolean(value);
2968                 if (b < 0)
2969                         log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
2970                 else
2971                         s->bus_name_good = b;
2972         } else if (streq(key, "bus-name-owner")) {
2973                 r = free_and_strdup(&s->bus_name_owner, value);
2974                 if (r < 0)
2975                         log_unit_error_errno(u, r, "Unable to deserialize current bus owner %s: %m", value);
2976         } else if (streq(key, "status-text")) {
2977                 char *t;
2978                 ssize_t l;
2979 
2980                 l = cunescape(value, 0, &t);
2981                 if (l < 0)
2982                         log_unit_debug_errno(u, l, "Failed to unescape status text '%s': %m", value);
2983                 else
2984                         free_and_replace(s->status_text, t);
2985 
2986         } else if (streq(key, "accept-socket")) {
2987                 Unit *socket;
2988 
2989                 r = manager_load_unit(u->manager, value, NULL, NULL, &socket);
2990                 if (r < 0)
2991                         log_unit_debug_errno(u, r, "Failed to load accept-socket unit '%s': %m", value);
2992                 else {
2993                         unit_ref_set(&s->accept_socket, u, socket);
2994                         SOCKET(socket)->n_connections++;
2995                 }
2996 
2997         } else if (streq(key, "socket-fd")) {
2998                 int fd;
2999 
3000                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
3001                         log_unit_debug(u, "Failed to parse socket-fd value: %s", value);
3002                 else {
3003                         asynchronous_close(s->socket_fd);
3004                         s->socket_fd = fdset_remove(fds, fd);
3005                 }
3006         } else if (streq(key, "fd-store-fd")) {
3007                 _cleanup_free_ char *fdv = NULL, *fdn = NULL, *fdp = NULL;
3008                 int fd;
3009                 int do_poll;
3010 
3011                 r = extract_first_word(&value, &fdv, NULL, 0);
3012                 if (r <= 0 || safe_atoi(fdv, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd)) {
3013                         log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
3014                         return 0;
3015                 }
3016 
3017                 r = extract_first_word(&value, &fdn, NULL, EXTRACT_CUNESCAPE | EXTRACT_UNQUOTE);
3018                 if (r <= 0) {
3019                         log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
3020                         return 0;
3021                 }
3022 
3023                 r = extract_first_word(&value, &fdp, NULL, 0);
3024                 if (r == 0) {
3025                         /* If the value is not present, we assume the default */
3026                         do_poll = 1;
3027                 } else if (r < 0 || safe_atoi(fdp, &do_poll) < 0) {
3028                         log_unit_debug_errno(u, r, "Failed to parse fd-store-fd value \"%s\": %m", value);
3029                         return 0;
3030                 }
3031 
3032                 r = service_add_fd_store(s, fd, fdn, do_poll);
3033                 if (r < 0)
3034                         log_unit_error_errno(u, r, "Failed to add fd to store: %m");
3035                 else
3036                         fdset_remove(fds, fd);
3037         } else if (streq(key, "main-exec-status-pid")) {
3038                 pid_t pid;
3039 
3040                 if (parse_pid(value, &pid) < 0)
3041                         log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
3042                 else
3043                         s->main_exec_status.pid = pid;
3044         } else if (streq(key, "main-exec-status-code")) {
3045                 int i;
3046 
3047                 if (safe_atoi(value, &i) < 0)
3048                         log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
3049                 else
3050                         s->main_exec_status.code = i;
3051         } else if (streq(key, "main-exec-status-status")) {
3052                 int i;
3053 
3054                 if (safe_atoi(value, &i) < 0)
3055                         log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
3056                 else
3057                         s->main_exec_status.status = i;
3058         } else if (streq(key, "main-exec-status-start"))
3059                 deserialize_dual_timestamp(value, &s->main_exec_status.start_timestamp);
3060         else if (streq(key, "main-exec-status-exit"))
3061                 deserialize_dual_timestamp(value, &s->main_exec_status.exit_timestamp);
3062         else if (streq(key, "watchdog-timestamp"))
3063                 deserialize_dual_timestamp(value, &s->watchdog_timestamp);
3064         else if (streq(key, "forbid-restart")) {
3065                 int b;
3066 
3067                 b = parse_boolean(value);
3068                 if (b < 0)
3069                         log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
3070                 else
3071                         s->forbid_restart = b;
3072         } else if (streq(key, "stdin-fd")) {
3073                 int fd;
3074 
3075                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
3076                         log_unit_debug(u, "Failed to parse stdin-fd value: %s", value);
3077                 else {
3078                         asynchronous_close(s->stdin_fd);
3079                         s->stdin_fd = fdset_remove(fds, fd);
3080                         s->exec_context.stdio_as_fds = true;
3081                 }
3082         } else if (streq(key, "stdout-fd")) {
3083                 int fd;
3084 
3085                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
3086                         log_unit_debug(u, "Failed to parse stdout-fd value: %s", value);
3087                 else {
3088                         asynchronous_close(s->stdout_fd);
3089                         s->stdout_fd = fdset_remove(fds, fd);
3090                         s->exec_context.stdio_as_fds = true;
3091                 }
3092         } else if (streq(key, "stderr-fd")) {
3093                 int fd;
3094 
3095                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
3096                         log_unit_debug(u, "Failed to parse stderr-fd value: %s", value);
3097                 else {
3098                         asynchronous_close(s->stderr_fd);
3099                         s->stderr_fd = fdset_remove(fds, fd);
3100                         s->exec_context.stdio_as_fds = true;
3101                 }
3102         } else if (streq(key, "exec-fd")) {
3103                 int fd;
3104 
3105                 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
3106                         log_unit_debug(u, "Failed to parse exec-fd value: %s", value);
3107                 else {
3108                         s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
3109 
3110                         fd = fdset_remove(fds, fd);
3111                         if (service_allocate_exec_fd_event_source(s, fd, &s->exec_fd_event_source) < 0)
3112                                 safe_close(fd);
3113                 }
3114         } else if (streq(key, "watchdog-override-usec")) {
3115                 if (deserialize_usec(value, &s->watchdog_override_usec) < 0)
3116                         log_unit_debug(u, "Failed to parse watchdog_override_usec value: %s", value);
3117                 else
3118                         s->watchdog_override_enable = true;
3119 
3120         } else if (streq(key, "watchdog-original-usec")) {
3121                 if (deserialize_usec(value, &s->watchdog_original_usec) < 0)
3122                         log_unit_debug(u, "Failed to parse watchdog_original_usec value: %s", value);
3123 
3124         } else if (STR_IN_SET(key, "main-command", "control-command")) {
3125                 r = service_deserialize_exec_command(u, key, value);
3126                 if (r < 0)
3127                         log_unit_debug_errno(u, r, "Failed to parse serialized command \"%s\": %m", value);
3128 
3129         } else if (streq(key, "n-restarts")) {
3130                 r = safe_atou(value, &s->n_restarts);
3131                 if (r < 0)
3132                         log_unit_debug_errno(u, r, "Failed to parse serialized restart counter '%s': %m", value);
3133 
3134         } else if (streq(key, "flush-n-restarts")) {
3135                 r = parse_boolean(value);
3136                 if (r < 0)
3137                         log_unit_debug_errno(u, r, "Failed to parse serialized flush restart counter setting '%s': %m", value);
3138                 else
3139                         s->flush_n_restarts = r;
3140         } else
3141                 log_unit_debug(u, "Unknown serialization key: %s", key);
3142 
3143         return 0;
3144 }
3145 
service_active_state(Unit * u)3146 _pure_ static UnitActiveState service_active_state(Unit *u) {
3147         const UnitActiveState *table;
3148 
3149         assert(u);
3150 
3151         table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
3152 
3153         return table[SERVICE(u)->state];
3154 }
3155 
service_sub_state_to_string(Unit * u)3156 static const char *service_sub_state_to_string(Unit *u) {
3157         assert(u);
3158 
3159         return service_state_to_string(SERVICE(u)->state);
3160 }
3161 
service_may_gc(Unit * u)3162 static bool service_may_gc(Unit *u) {
3163         Service *s = SERVICE(u);
3164 
3165         assert(s);
3166 
3167         /* Never clean up services that still have a process around, even if the service is formally dead. Note that
3168          * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
3169          * have moved outside of the cgroup. */
3170 
3171         if (main_pid_good(s) > 0 ||
3172             control_pid_good(s) > 0)
3173                 return false;
3174 
3175         return true;
3176 }
3177 
service_retry_pid_file(Service * s)3178 static int service_retry_pid_file(Service *s) {
3179         int r;
3180 
3181         assert(s->pid_file);
3182         assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
3183 
3184         r = service_load_pid_file(s, false);
3185         if (r < 0)
3186                 return r;
3187 
3188         service_unwatch_pid_file(s);
3189 
3190         service_enter_running(s, SERVICE_SUCCESS);
3191         return 0;
3192 }
3193 
service_watch_pid_file(Service * s)3194 static int service_watch_pid_file(Service *s) {
3195         int r;
3196 
3197         log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
3198 
3199         r = path_spec_watch(s->pid_file_pathspec, service_dispatch_inotify_io);
3200         if (r < 0)
3201                 goto fail;
3202 
3203         /* the pidfile might have appeared just before we set the watch */
3204         log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
3205         service_retry_pid_file(s);
3206 
3207         return 0;
3208 fail:
3209         log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
3210         service_unwatch_pid_file(s);
3211         return r;
3212 }
3213 
service_demand_pid_file(Service * s)3214 static int service_demand_pid_file(Service *s) {
3215         PathSpec *ps;
3216 
3217         assert(s->pid_file);
3218         assert(!s->pid_file_pathspec);
3219 
3220         ps = new0(PathSpec, 1);
3221         if (!ps)
3222                 return -ENOMEM;
3223 
3224         ps->unit = UNIT(s);
3225         ps->path = strdup(s->pid_file);
3226         if (!ps->path) {
3227                 free(ps);
3228                 return -ENOMEM;
3229         }
3230 
3231         path_simplify(ps->path);
3232 
3233         /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
3234          * keep their PID file open all the time. */
3235         ps->type = PATH_MODIFIED;
3236         ps->inotify_fd = -1;
3237 
3238         s->pid_file_pathspec = ps;
3239 
3240         return service_watch_pid_file(s);
3241 }
3242 
service_dispatch_inotify_io(sd_event_source * source,int fd,uint32_t events,void * userdata)3243 static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
3244         PathSpec *p = userdata;
3245         Service *s;
3246 
3247         assert(p);
3248 
3249         s = SERVICE(p->unit);
3250 
3251         assert(s);
3252         assert(fd >= 0);
3253         assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
3254         assert(s->pid_file_pathspec);
3255         assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
3256 
3257         log_unit_debug(UNIT(s), "inotify event");
3258 
3259         if (path_spec_fd_event(p, events) < 0)
3260                 goto fail;
3261 
3262         if (service_retry_pid_file(s) == 0)
3263                 return 0;
3264 
3265         if (service_watch_pid_file(s) < 0)
3266                 goto fail;
3267 
3268         return 0;
3269 
3270 fail:
3271         service_unwatch_pid_file(s);
3272         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
3273         return 0;
3274 }
3275 
service_dispatch_exec_io(sd_event_source * source,int fd,uint32_t events,void * userdata)3276 static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
3277         Service *s = SERVICE(userdata);
3278 
3279         assert(s);
3280 
3281         log_unit_debug(UNIT(s), "got exec-fd event");
3282 
3283         /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
3284          * successfully for it. We implement this through a pipe() towards the child, which the kernel automatically
3285          * closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on the pipe in the
3286          * parent. We need to be careful however, as there are other reasons that we might cause the child's side of
3287          * the pipe to be closed (for example, a simple exit()). To deal with that we'll ignore EOFs on the pipe unless
3288          * the child signalled us first that it is about to call the execve(). It does so by sending us a simple
3289          * non-zero byte via the pipe. We also provide the child with a way to inform us in case execve() failed: if it
3290          * sends a zero byte we'll ignore POLLHUP on the fd again. */
3291 
3292         for (;;) {
3293                 uint8_t x;
3294                 ssize_t n;
3295 
3296                 n = read(fd, &x, sizeof(x));
3297                 if (n < 0) {
3298                         if (errno == EAGAIN) /* O_NONBLOCK in effect → everything queued has now been processed. */
3299                                 return 0;
3300 
3301                         return log_unit_error_errno(UNIT(s), errno, "Failed to read from exec_fd: %m");
3302                 }
3303                 if (n == 0) { /* EOF → the event we are waiting for */
3304 
3305                         s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
3306 
3307                         if (s->exec_fd_hot) { /* Did the child tell us to expect EOF now? */
3308                                 log_unit_debug(UNIT(s), "Got EOF on exec-fd");
3309 
3310                                 s->exec_fd_hot = false;
3311 
3312                                 /* Nice! This is what we have been waiting for. Transition to next state. */
3313                                 if (s->type == SERVICE_EXEC && s->state == SERVICE_START)
3314                                         service_enter_start_post(s);
3315                         } else
3316                                 log_unit_debug(UNIT(s), "Got EOF on exec-fd while it was disabled, ignoring.");
3317 
3318                         return 0;
3319                 }
3320 
3321                 /* A byte was read → this turns on/off the exec fd logic */
3322                 assert(n == sizeof(x));
3323                 s->exec_fd_hot = x;
3324         }
3325 
3326         return 0;
3327 }
3328 
service_notify_cgroup_empty_event(Unit * u)3329 static void service_notify_cgroup_empty_event(Unit *u) {
3330         Service *s = SERVICE(u);
3331 
3332         assert(u);
3333 
3334         log_unit_debug(u, "Control group is empty.");
3335 
3336         switch (s->state) {
3337 
3338                 /* Waiting for SIGCHLD is usually more interesting,
3339                  * because it includes return codes/signals. Which is
3340                  * why we ignore the cgroup events for most cases,
3341                  * except when we don't know pid which to expect the
3342                  * SIGCHLD for. */
3343 
3344         case SERVICE_START:
3345                 if (s->type == SERVICE_NOTIFY &&
3346                     main_pid_good(s) == 0 &&
3347                     control_pid_good(s) == 0) {
3348                         /* No chance of getting a ready notification anymore */
3349                         service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
3350                         break;
3351                 }
3352 
3353                 if (s->exit_type == SERVICE_EXIT_CGROUP && main_pid_good(s) <= 0)
3354                         service_enter_start_post(s);
3355 
3356                 _fallthrough_;
3357         case SERVICE_START_POST:
3358                 if (s->pid_file_pathspec &&
3359                     main_pid_good(s) == 0 &&
3360                     control_pid_good(s) == 0) {
3361 
3362                         /* Give up hoping for the daemon to write its PID file */
3363                         log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
3364 
3365                         service_unwatch_pid_file(s);
3366                         if (s->state == SERVICE_START)
3367                                 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
3368                         else
3369                                 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
3370                 }
3371                 break;
3372 
3373         case SERVICE_RUNNING:
3374                 /* service_enter_running() will figure out what to do */
3375                 service_enter_running(s, SERVICE_SUCCESS);
3376                 break;
3377 
3378         case SERVICE_STOP_WATCHDOG:
3379         case SERVICE_STOP_SIGTERM:
3380         case SERVICE_STOP_SIGKILL:
3381 
3382                 if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
3383                         service_enter_stop_post(s, SERVICE_SUCCESS);
3384 
3385                 break;
3386 
3387         case SERVICE_STOP_POST:
3388         case SERVICE_FINAL_WATCHDOG:
3389         case SERVICE_FINAL_SIGTERM:
3390         case SERVICE_FINAL_SIGKILL:
3391                 if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
3392                         service_enter_dead(s, SERVICE_SUCCESS, true);
3393 
3394                 break;
3395 
3396         /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3397          * up the cgroup earlier and should do it now. */
3398         case SERVICE_DEAD:
3399         case SERVICE_FAILED:
3400                 unit_prune_cgroup(u);
3401                 break;
3402 
3403         default:
3404                 ;
3405         }
3406 }
3407 
service_notify_cgroup_oom_event(Unit * u,bool managed_oom)3408 static void service_notify_cgroup_oom_event(Unit *u, bool managed_oom) {
3409         Service *s = SERVICE(u);
3410 
3411         if (managed_oom)
3412                 log_unit_debug(u, "Process(es) of control group were killed by systemd-oomd.");
3413         else
3414                 log_unit_debug(u, "Process of control group was killed by the OOM killer.");
3415 
3416         if (s->oom_policy == OOM_CONTINUE)
3417                 return;
3418 
3419         switch (s->state) {
3420 
3421         case SERVICE_CONDITION:
3422         case SERVICE_START_PRE:
3423         case SERVICE_START:
3424         case SERVICE_START_POST:
3425         case SERVICE_STOP:
3426                 if (s->oom_policy == OOM_STOP)
3427                         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_OOM_KILL);
3428                 else if (s->oom_policy == OOM_KILL)
3429                         service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3430 
3431                 break;
3432 
3433         case SERVICE_EXITED:
3434         case SERVICE_RUNNING:
3435                 if (s->oom_policy == OOM_STOP)
3436                         service_enter_stop(s, SERVICE_FAILURE_OOM_KILL);
3437                 else if (s->oom_policy == OOM_KILL)
3438                         service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3439 
3440                 break;
3441 
3442         case SERVICE_STOP_WATCHDOG:
3443         case SERVICE_STOP_SIGTERM:
3444                 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3445                 break;
3446 
3447         case SERVICE_STOP_SIGKILL:
3448         case SERVICE_FINAL_SIGKILL:
3449                 if (s->result == SERVICE_SUCCESS)
3450                         s->result = SERVICE_FAILURE_OOM_KILL;
3451                 break;
3452 
3453         case SERVICE_STOP_POST:
3454         case SERVICE_FINAL_SIGTERM:
3455                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3456                 break;
3457 
3458         default:
3459                 ;
3460         }
3461 }
3462 
service_sigchld_event(Unit * u,pid_t pid,int code,int status)3463 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
3464         bool notify_dbus = true;
3465         Service *s = SERVICE(u);
3466         ServiceResult f;
3467         ExitClean clean_mode;
3468 
3469         assert(s);
3470         assert(pid >= 0);
3471 
3472         /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3473          * considered daemons as they are typically not long running. */
3474         if (s->type == SERVICE_ONESHOT || (s->control_pid == pid && s->control_command_id != SERVICE_EXEC_START))
3475                 clean_mode = EXIT_CLEAN_COMMAND;
3476         else
3477                 clean_mode = EXIT_CLEAN_DAEMON;
3478 
3479         if (is_clean_exit(code, status, clean_mode, &s->success_status))
3480                 f = SERVICE_SUCCESS;
3481         else if (code == CLD_EXITED)
3482                 f = SERVICE_FAILURE_EXIT_CODE;
3483         else if (code == CLD_KILLED)
3484                 f = SERVICE_FAILURE_SIGNAL;
3485         else if (code == CLD_DUMPED)
3486                 f = SERVICE_FAILURE_CORE_DUMP;
3487         else
3488                 assert_not_reached();
3489 
3490         if (s->main_pid == pid) {
3491                 /* Clean up the exec_fd event source. We want to do this here, not later in
3492                  * service_set_state(), because service_enter_stop_post() calls service_spawn().
3493                  * The source owns its end of the pipe, so this will close that too. */
3494                 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
3495 
3496                 /* Forking services may occasionally move to a new PID.
3497                  * As long as they update the PID file before exiting the old
3498                  * PID, they're fine. */
3499                 if (service_load_pid_file(s, false) > 0)
3500                         return;
3501 
3502                 s->main_pid = 0;
3503                 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
3504 
3505                 if (s->main_command) {
3506                         /* If this is not a forking service than the
3507                          * main process got started and hence we copy
3508                          * the exit status so that it is recorded both
3509                          * as main and as control process exit
3510                          * status */
3511 
3512                         s->main_command->exec_status = s->main_exec_status;
3513 
3514                         if (s->main_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
3515                                 f = SERVICE_SUCCESS;
3516                 } else if (s->exec_command[SERVICE_EXEC_START]) {
3517 
3518                         /* If this is a forked process, then we should
3519                          * ignore the return value if this was
3520                          * configured for the starter process */
3521 
3522                         if (s->exec_command[SERVICE_EXEC_START]->flags & EXEC_COMMAND_IGNORE_FAILURE)
3523                                 f = SERVICE_SUCCESS;
3524                 }
3525 
3526                 unit_log_process_exit(
3527                                 u,
3528                                 "Main process",
3529                                 service_exec_command_to_string(SERVICE_EXEC_START),
3530                                 f == SERVICE_SUCCESS,
3531                                 code, status);
3532 
3533                 if (s->result == SERVICE_SUCCESS)
3534                         s->result = f;
3535 
3536                 if (s->main_command &&
3537                     s->main_command->command_next &&
3538                     s->type == SERVICE_ONESHOT &&
3539                     f == SERVICE_SUCCESS) {
3540 
3541                         /* There is another command to execute, so let's do that. */
3542 
3543                         log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
3544                         service_run_next_main(s);
3545 
3546                 } else {
3547                         s->main_command = NULL;
3548 
3549                         /* Services with ExitType=cgroup do not act on main PID exiting,
3550                          * unless the cgroup is already empty */
3551                         if (s->exit_type == SERVICE_EXIT_MAIN || cgroup_good(s) <= 0) {
3552                                 /* The service exited, so the service is officially gone. */
3553                                 switch (s->state) {
3554 
3555                                 case SERVICE_START_POST:
3556                                 case SERVICE_RELOAD:
3557                                         /* If neither main nor control processes are running then
3558                                          * the current state can never exit cleanly, hence immediately
3559                                          * terminate the service. */
3560                                         if (control_pid_good(s) <= 0)
3561                                                 service_enter_stop(s, f);
3562 
3563                                         /* Otherwise need to wait until the operation is done. */
3564                                         break;
3565 
3566                                 case SERVICE_STOP:
3567                                         /* Need to wait until the operation is done. */
3568                                         break;
3569 
3570                                 case SERVICE_START:
3571                                         if (s->type == SERVICE_ONESHOT) {
3572                                                 /* This was our main goal, so let's go on */
3573                                                 if (f == SERVICE_SUCCESS)
3574                                                         service_enter_start_post(s);
3575                                                 else
3576                                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3577                                                 break;
3578                                         } else if (s->type == SERVICE_NOTIFY) {
3579                                                 /* Only enter running through a notification, so that the
3580                                                  * SERVICE_START state signifies that no ready notification
3581                                                  * has been received */
3582                                                 if (f != SERVICE_SUCCESS)
3583                                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3584                                                 else if (!s->remain_after_exit || s->notify_access == NOTIFY_MAIN)
3585                                                         /* The service has never been and will never be active */
3586                                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3587                                                 break;
3588                                         }
3589 
3590                                         _fallthrough_;
3591                                 case SERVICE_RUNNING:
3592                                         service_enter_running(s, f);
3593                                         break;
3594 
3595                                 case SERVICE_STOP_WATCHDOG:
3596                                 case SERVICE_STOP_SIGTERM:
3597                                 case SERVICE_STOP_SIGKILL:
3598 
3599                                         if (control_pid_good(s) <= 0)
3600                                                 service_enter_stop_post(s, f);
3601 
3602                                         /* If there is still a control process, wait for that first */
3603                                         break;
3604 
3605                                 case SERVICE_STOP_POST:
3606 
3607                                         if (control_pid_good(s) <= 0)
3608                                                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3609 
3610                                         break;
3611 
3612                                 case SERVICE_FINAL_WATCHDOG:
3613                                 case SERVICE_FINAL_SIGTERM:
3614                                 case SERVICE_FINAL_SIGKILL:
3615 
3616                                         if (control_pid_good(s) <= 0)
3617                                                 service_enter_dead(s, f, true);
3618                                         break;
3619 
3620                                 default:
3621                                         assert_not_reached();
3622                                 }
3623                         }
3624                 }
3625 
3626         } else if (s->control_pid == pid) {
3627                 const char *kind;
3628                 bool success;
3629 
3630                 s->control_pid = 0;
3631 
3632                 if (s->control_command) {
3633                         exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
3634 
3635                         if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
3636                                 f = SERVICE_SUCCESS;
3637                 }
3638 
3639                 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
3640                 if (s->state == SERVICE_CONDITION) {
3641                         if (f == SERVICE_FAILURE_EXIT_CODE && status < 255) {
3642                                 UNIT(s)->condition_result = false;
3643                                 f = SERVICE_SKIP_CONDITION;
3644                                 success = true;
3645                         } else if (f == SERVICE_SUCCESS) {
3646                                 UNIT(s)->condition_result = true;
3647                                 success = true;
3648                         } else
3649                                 success = false;
3650 
3651                         kind = "Condition check process";
3652                 } else {
3653                         kind = "Control process";
3654                         success = f == SERVICE_SUCCESS;
3655                 }
3656 
3657                 unit_log_process_exit(
3658                                 u,
3659                                 kind,
3660                                 service_exec_command_to_string(s->control_command_id),
3661                                 success,
3662                                 code, status);
3663 
3664                 if (s->state != SERVICE_RELOAD && s->result == SERVICE_SUCCESS)
3665                         s->result = f;
3666 
3667                 if (s->control_command &&
3668                     s->control_command->command_next &&
3669                     f == SERVICE_SUCCESS) {
3670 
3671                         /* There is another command to *
3672                          * execute, so let's do that. */
3673 
3674                         log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
3675                         service_run_next_control(s);
3676 
3677                 } else {
3678                         /* No further commands for this step, so let's
3679                          * figure out what to do next */
3680 
3681                         s->control_command = NULL;
3682                         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
3683 
3684                         log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
3685 
3686                         switch (s->state) {
3687 
3688                         case SERVICE_CONDITION:
3689                                 if (f == SERVICE_SUCCESS)
3690                                         service_enter_start_pre(s);
3691                                 else
3692                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3693                                 break;
3694 
3695                         case SERVICE_START_PRE:
3696                                 if (f == SERVICE_SUCCESS)
3697                                         service_enter_start(s);
3698                                 else
3699                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3700                                 break;
3701 
3702                         case SERVICE_START:
3703                                 if (s->type != SERVICE_FORKING)
3704                                         /* Maybe spurious event due to a reload that changed the type? */
3705                                         break;
3706 
3707                                 if (f != SERVICE_SUCCESS) {
3708                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3709                                         break;
3710                                 }
3711 
3712                                 if (s->pid_file) {
3713                                         bool has_start_post;
3714                                         int r;
3715 
3716                                         /* Let's try to load the pid file here if we can.
3717                                          * The PID file might actually be created by a START_POST
3718                                          * script. In that case don't worry if the loading fails. */
3719 
3720                                         has_start_post = s->exec_command[SERVICE_EXEC_START_POST];
3721                                         r = service_load_pid_file(s, !has_start_post);
3722                                         if (!has_start_post && r < 0) {
3723                                                 r = service_demand_pid_file(s);
3724                                                 if (r < 0 || cgroup_good(s) == 0)
3725                                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3726                                                 break;
3727                                         }
3728                                 } else
3729                                         service_search_main_pid(s);
3730 
3731                                 service_enter_start_post(s);
3732                                 break;
3733 
3734                         case SERVICE_START_POST:
3735                                 if (f != SERVICE_SUCCESS) {
3736                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3737                                         break;
3738                                 }
3739 
3740                                 if (s->pid_file) {
3741                                         int r;
3742 
3743                                         r = service_load_pid_file(s, true);
3744                                         if (r < 0) {
3745                                                 r = service_demand_pid_file(s);
3746                                                 if (r < 0 || cgroup_good(s) == 0)
3747                                                         service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
3748                                                 break;
3749                                         }
3750                                 } else
3751                                         service_search_main_pid(s);
3752 
3753                                 service_enter_running(s, SERVICE_SUCCESS);
3754                                 break;
3755 
3756                         case SERVICE_RELOAD:
3757                                 if (f == SERVICE_SUCCESS)
3758                                         if (service_load_pid_file(s, true) < 0)
3759                                                 service_search_main_pid(s);
3760 
3761                                 s->reload_result = f;
3762                                 service_enter_running(s, SERVICE_SUCCESS);
3763                                 break;
3764 
3765                         case SERVICE_STOP:
3766                                 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3767                                 break;
3768 
3769                         case SERVICE_STOP_WATCHDOG:
3770                         case SERVICE_STOP_SIGTERM:
3771                         case SERVICE_STOP_SIGKILL:
3772                                 if (main_pid_good(s) <= 0)
3773                                         service_enter_stop_post(s, f);
3774 
3775                                 /* If there is still a service process around, wait until
3776                                  * that one quit, too */
3777                                 break;
3778 
3779                         case SERVICE_STOP_POST:
3780                                 if (main_pid_good(s) <= 0)
3781                                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3782                                 break;
3783 
3784                         case SERVICE_FINAL_WATCHDOG:
3785                         case SERVICE_FINAL_SIGTERM:
3786                         case SERVICE_FINAL_SIGKILL:
3787                                 if (main_pid_good(s) <= 0)
3788                                         service_enter_dead(s, f, true);
3789                                 break;
3790 
3791                         case SERVICE_CLEANING:
3792 
3793                                 if (s->clean_result == SERVICE_SUCCESS)
3794                                         s->clean_result = f;
3795 
3796                                 service_enter_dead(s, SERVICE_SUCCESS, false);
3797                                 break;
3798 
3799                         default:
3800                                 assert_not_reached();
3801                         }
3802                 }
3803         } else /* Neither control nor main PID? If so, don't notify about anything */
3804                 notify_dbus = false;
3805 
3806         /* Notify clients about changed exit status */
3807         if (notify_dbus)
3808                 unit_add_to_dbus_queue(u);
3809 
3810         /* We watch the main/control process otherwise we can't retrieve the unit they
3811          * belong to with cgroupv1. But if they are not our direct child, we won't get a
3812          * SIGCHLD for them. Therefore we need to look for others to watch so we can
3813          * detect when the cgroup becomes empty. Note that the control process is always
3814          * our child so it's pointless to watch all other processes. */
3815         if (!control_pid_good(s))
3816                 if (!s->main_pid_known || s->main_pid_alien)
3817                         (void) unit_enqueue_rewatch_pids(u);
3818 }
3819 
service_dispatch_timer(sd_event_source * source,usec_t usec,void * userdata)3820 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
3821         Service *s = SERVICE(userdata);
3822 
3823         assert(s);
3824         assert(source == s->timer_event_source);
3825 
3826         switch (s->state) {
3827 
3828         case SERVICE_CONDITION:
3829         case SERVICE_START_PRE:
3830         case SERVICE_START:
3831         case SERVICE_START_POST:
3832                 switch (s->timeout_start_failure_mode) {
3833 
3834                 case SERVICE_TIMEOUT_TERMINATE:
3835                         log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", service_state_to_string(s->state));
3836                         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3837                         break;
3838 
3839                 case SERVICE_TIMEOUT_ABORT:
3840                         log_unit_warning(UNIT(s), "%s operation timed out. Aborting.", service_state_to_string(s->state));
3841                         service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
3842                         break;
3843 
3844                 case SERVICE_TIMEOUT_KILL:
3845                         if (s->kill_context.send_sigkill) {
3846                                 log_unit_warning(UNIT(s), "%s operation timed out. Killing.", service_state_to_string(s->state));
3847                                 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3848                         } else {
3849                                 log_unit_warning(UNIT(s), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s->state));
3850                                 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3851                         }
3852                         break;
3853 
3854                 default:
3855                         assert_not_reached();
3856                 }
3857                 break;
3858 
3859         case SERVICE_RUNNING:
3860                 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
3861                 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
3862                 break;
3863 
3864         case SERVICE_RELOAD:
3865                 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
3866                 service_kill_control_process(s);
3867                 s->reload_result = SERVICE_FAILURE_TIMEOUT;
3868                 service_enter_running(s, SERVICE_SUCCESS);
3869                 break;
3870 
3871         case SERVICE_STOP:
3872                 switch (s->timeout_stop_failure_mode) {
3873 
3874                 case SERVICE_TIMEOUT_TERMINATE:
3875                         log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
3876                         service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3877                         break;
3878 
3879                 case SERVICE_TIMEOUT_ABORT:
3880                         log_unit_warning(UNIT(s), "Stopping timed out. Aborting.");
3881                         service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
3882                         break;
3883 
3884                 case SERVICE_TIMEOUT_KILL:
3885                         if (s->kill_context.send_sigkill) {
3886                                 log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
3887                                 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3888                         } else {
3889                                 log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL.");
3890                                 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3891                         }
3892                         break;
3893 
3894                 default:
3895                         assert_not_reached();
3896                 }
3897                 break;
3898 
3899         case SERVICE_STOP_WATCHDOG:
3900                 if (s->kill_context.send_sigkill) {
3901                         log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Killing.");
3902                         service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3903                 } else {
3904                         log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
3905                         service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3906                 }
3907                 break;
3908 
3909         case SERVICE_STOP_SIGTERM:
3910                 if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
3911                         log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Aborting.");
3912                         service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
3913                 } else if (s->kill_context.send_sigkill) {
3914                         log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
3915                         service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3916                 } else {
3917                         log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
3918                         service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3919                 }
3920 
3921                 break;
3922 
3923         case SERVICE_STOP_SIGKILL:
3924                 /* Uh, we sent a SIGKILL and it is still not gone?
3925                  * Must be something we cannot kill, so let's just be
3926                  * weirded out and continue */
3927 
3928                 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
3929                 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
3930                 break;
3931 
3932         case SERVICE_STOP_POST:
3933                 switch (s->timeout_stop_failure_mode) {
3934 
3935                 case SERVICE_TIMEOUT_TERMINATE:
3936                         log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
3937                         service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
3938                         break;
3939 
3940                 case SERVICE_TIMEOUT_ABORT:
3941                         log_unit_warning(UNIT(s), "State 'stop-post' timed out. Aborting.");
3942                         service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
3943                         break;
3944 
3945                 case SERVICE_TIMEOUT_KILL:
3946                         if (s->kill_context.send_sigkill) {
3947                                 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Killing.");
3948                                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3949                         } else {
3950                                 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
3951                                 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3952                         }
3953                         break;
3954 
3955                 default:
3956                         assert_not_reached();
3957                 }
3958                 break;
3959 
3960         case SERVICE_FINAL_WATCHDOG:
3961                 if (s->kill_context.send_sigkill) {
3962                         log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Killing.");
3963                         service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3964                 } else {
3965                         log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
3966                         service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3967                 }
3968                 break;
3969 
3970         case SERVICE_FINAL_SIGTERM:
3971                 if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
3972                         log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Aborting.");
3973                         service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
3974                 } else if (s->kill_context.send_sigkill) {
3975                         log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Killing.");
3976                         service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3977                 } else {
3978                         log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
3979                         service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3980                 }
3981 
3982                 break;
3983 
3984         case SERVICE_FINAL_SIGKILL:
3985                 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
3986                 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
3987                 break;
3988 
3989         case SERVICE_AUTO_RESTART:
3990                 if (s->restart_usec > 0)
3991                         log_unit_debug(UNIT(s),
3992                                        "Service RestartSec=%s expired, scheduling restart.",
3993                                        FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC));
3994                 else
3995                         log_unit_debug(UNIT(s),
3996                                        "Service has no hold-off time (RestartSec=0), scheduling restart.");
3997 
3998                 service_enter_restart(s);
3999                 break;
4000 
4001         case SERVICE_CLEANING:
4002                 log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
4003 
4004                 if (s->clean_result == SERVICE_SUCCESS)
4005                         s->clean_result = SERVICE_FAILURE_TIMEOUT;
4006 
4007                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, 0);
4008                 break;
4009 
4010         default:
4011                 assert_not_reached();
4012         }
4013 
4014         return 0;
4015 }
4016 
service_dispatch_watchdog(sd_event_source * source,usec_t usec,void * userdata)4017 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
4018         Service *s = SERVICE(userdata);
4019         usec_t watchdog_usec;
4020 
4021         assert(s);
4022         assert(source == s->watchdog_event_source);
4023 
4024         watchdog_usec = service_get_watchdog_usec(s);
4025 
4026         if (UNIT(s)->manager->service_watchdogs) {
4027                 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
4028                                FORMAT_TIMESPAN(watchdog_usec, 1));
4029 
4030                 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
4031         } else
4032                 log_unit_warning(UNIT(s), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
4033                                  FORMAT_TIMESPAN(watchdog_usec, 1));
4034 
4035         return 0;
4036 }
4037 
service_notify_message_authorized(Service * s,pid_t pid,FDSet * fds)4038 static bool service_notify_message_authorized(Service *s, pid_t pid, FDSet *fds) {
4039         assert(s);
4040 
4041         if (s->notify_access == NOTIFY_NONE) {
4042                 log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception is disabled.", pid);
4043                 return false;
4044         }
4045 
4046         if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
4047                 if (s->main_pid != 0)
4048                         log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid, s->main_pid);
4049                 else
4050                         log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", pid);
4051 
4052                 return false;
4053         }
4054 
4055         if (s->notify_access == NOTIFY_EXEC && pid != s->main_pid && pid != s->control_pid) {
4056                 if (s->main_pid != 0 && s->control_pid != 0)
4057                         log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT" and control PID "PID_FMT,
4058                                          pid, s->main_pid, s->control_pid);
4059                 else if (s->main_pid != 0)
4060                         log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid, s->main_pid);
4061                 else if (s->control_pid != 0)
4062                         log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for control PID "PID_FMT, pid, s->control_pid);
4063                 else
4064                         log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID and control PID which are currently not known", pid);
4065 
4066                 return false;
4067         }
4068 
4069         return true;
4070 }
4071 
service_force_watchdog(Service * s)4072 static void service_force_watchdog(Service *s) {
4073         if (!UNIT(s)->manager->service_watchdogs)
4074                 return;
4075 
4076         log_unit_error(UNIT(s), "Watchdog request (last status: %s)!",
4077                        s->status_text ? s->status_text : "<unset>");
4078 
4079         service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
4080 }
4081 
service_notify_message(Unit * u,const struct ucred * ucred,char * const * tags,FDSet * fds)4082 static void service_notify_message(
4083                 Unit *u,
4084                 const struct ucred *ucred,
4085                 char * const *tags,
4086                 FDSet *fds) {
4087 
4088         Service *s = SERVICE(u);
4089         bool notify_dbus = false;
4090         const char *e;
4091         int r;
4092 
4093         assert(u);
4094         assert(ucred);
4095 
4096         if (!service_notify_message_authorized(SERVICE(u), ucred->pid, fds))
4097                 return;
4098 
4099         if (DEBUG_LOGGING) {
4100                 _cleanup_free_ char *cc = NULL;
4101 
4102                 cc = strv_join(tags, ", ");
4103                 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", ucred->pid, isempty(cc) ? "n/a" : cc);
4104         }
4105 
4106         /* Interpret MAINPID= */
4107         e = strv_find_startswith(tags, "MAINPID=");
4108         if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
4109                 pid_t new_main_pid;
4110 
4111                 if (parse_pid(e, &new_main_pid) < 0)
4112                         log_unit_warning(u, "Failed to parse MAINPID= field in notification message, ignoring: %s", e);
4113                 else if (!s->main_pid_known || new_main_pid != s->main_pid) {
4114 
4115                         r = service_is_suitable_main_pid(s, new_main_pid, LOG_WARNING);
4116                         if (r == 0) {
4117                                 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
4118 
4119                                 if (ucred->uid == 0) {
4120                                         log_unit_debug(u, "New main PID "PID_FMT" does not belong to service, but we'll accept it as the request to change it came from a privileged process.", new_main_pid);
4121                                         r = 1;
4122                                 } else
4123                                         log_unit_debug(u, "New main PID "PID_FMT" does not belong to service, refusing.", new_main_pid);
4124                         }
4125                         if (r > 0) {
4126                                 service_set_main_pid(s, new_main_pid);
4127 
4128                                 r = unit_watch_pid(UNIT(s), new_main_pid, false);
4129                                 if (r < 0)
4130                                         log_unit_warning_errno(UNIT(s), r, "Failed to watch new main PID "PID_FMT" for service: %m", new_main_pid);
4131 
4132                                 notify_dbus = true;
4133                         }
4134                 }
4135         }
4136 
4137         /* Interpret READY=/STOPPING=/RELOADING=. Last one wins. */
4138         STRV_FOREACH_BACKWARDS(i, tags) {
4139 
4140                 if (streq(*i, "READY=1")) {
4141                         s->notify_state = NOTIFY_READY;
4142 
4143                         /* Type=notify services inform us about completed
4144                          * initialization with READY=1 */
4145                         if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
4146                                 service_enter_start_post(s);
4147 
4148                         /* Sending READY=1 while we are reloading informs us
4149                          * that the reloading is complete */
4150                         if (s->state == SERVICE_RELOAD && s->control_pid == 0)
4151                                 service_enter_running(s, SERVICE_SUCCESS);
4152 
4153                         notify_dbus = true;
4154                         break;
4155 
4156                 } else if (streq(*i, "RELOADING=1")) {
4157                         s->notify_state = NOTIFY_RELOADING;
4158 
4159                         if (s->state == SERVICE_RUNNING)
4160                                 service_enter_reload_by_notify(s);
4161 
4162                         notify_dbus = true;
4163                         break;
4164 
4165                 } else if (streq(*i, "STOPPING=1")) {
4166                         s->notify_state = NOTIFY_STOPPING;
4167 
4168                         if (s->state == SERVICE_RUNNING)
4169                                 service_enter_stop_by_notify(s);
4170 
4171                         notify_dbus = true;
4172                         break;
4173                 }
4174         }
4175 
4176         /* Interpret STATUS= */
4177         e = strv_find_startswith(tags, "STATUS=");
4178         if (e) {
4179                 _cleanup_free_ char *t = NULL;
4180 
4181                 if (!isempty(e)) {
4182                         /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4183                          * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4184                         if (strlen(e) > STATUS_TEXT_MAX)
4185                                 log_unit_warning(u, "Status message overly long (%zu > %u), ignoring.", strlen(e), STATUS_TEXT_MAX);
4186                         else if (!utf8_is_valid(e))
4187                                 log_unit_warning(u, "Status message in notification message is not UTF-8 clean, ignoring.");
4188                         else {
4189                                 t = strdup(e);
4190                                 if (!t)
4191                                         log_oom();
4192                         }
4193                 }
4194 
4195                 if (!streq_ptr(s->status_text, t)) {
4196                         free_and_replace(s->status_text, t);
4197                         notify_dbus = true;
4198                 }
4199         }
4200 
4201         /* Interpret ERRNO= */
4202         e = strv_find_startswith(tags, "ERRNO=");
4203         if (e) {
4204                 int status_errno;
4205 
4206                 status_errno = parse_errno(e);
4207                 if (status_errno < 0)
4208                         log_unit_warning_errno(u, status_errno,
4209                                                "Failed to parse ERRNO= field value '%s' in notification message: %m", e);
4210                 else if (s->status_errno != status_errno) {
4211                         s->status_errno = status_errno;
4212                         notify_dbus = true;
4213                 }
4214         }
4215 
4216         /* Interpret EXTEND_TIMEOUT= */
4217         e = strv_find_startswith(tags, "EXTEND_TIMEOUT_USEC=");
4218         if (e) {
4219                 usec_t extend_timeout_usec;
4220                 if (safe_atou64(e, &extend_timeout_usec) < 0)
4221                         log_unit_warning(u, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e);
4222                 else
4223                         service_extend_timeout(s, extend_timeout_usec);
4224         }
4225 
4226         /* Interpret WATCHDOG= */
4227         e = strv_find_startswith(tags, "WATCHDOG=");
4228         if (e) {
4229                 if (streq(e, "1"))
4230                         service_reset_watchdog(s);
4231                 else if (streq(e, "trigger"))
4232                         service_force_watchdog(s);
4233                 else
4234                         log_unit_warning(u, "Passed WATCHDOG= field is invalid, ignoring.");
4235         }
4236 
4237         e = strv_find_startswith(tags, "WATCHDOG_USEC=");
4238         if (e) {
4239                 usec_t watchdog_override_usec;
4240                 if (safe_atou64(e, &watchdog_override_usec) < 0)
4241                         log_unit_warning(u, "Failed to parse WATCHDOG_USEC=%s", e);
4242                 else
4243                         service_override_watchdog_timeout(s, watchdog_override_usec);
4244         }
4245 
4246         /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4247          * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4248          * fds, but optional when pushing in new fds, for compatibility reasons. */
4249         if (strv_contains(tags, "FDSTOREREMOVE=1")) {
4250                 const char *name;
4251 
4252                 name = strv_find_startswith(tags, "FDNAME=");
4253                 if (!name || !fdname_is_valid(name))
4254                         log_unit_warning(u, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4255                 else
4256                         service_remove_fd_store(s, name);
4257 
4258         } else if (strv_contains(tags, "FDSTORE=1")) {
4259                 const char *name;
4260 
4261                 name = strv_find_startswith(tags, "FDNAME=");
4262                 if (name && !fdname_is_valid(name)) {
4263                         log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
4264                         name = NULL;
4265                 }
4266 
4267                 (void) service_add_fd_store_set(s, fds, name, !strv_contains(tags, "FDPOLL=0"));
4268         }
4269 
4270         /* Notify clients about changed status or main pid */
4271         if (notify_dbus)
4272                 unit_add_to_dbus_queue(u);
4273 }
4274 
service_get_timeout(Unit * u,usec_t * timeout)4275 static int service_get_timeout(Unit *u, usec_t *timeout) {
4276         Service *s = SERVICE(u);
4277         uint64_t t;
4278         int r;
4279 
4280         if (!s->timer_event_source)
4281                 return 0;
4282 
4283         r = sd_event_source_get_time(s->timer_event_source, &t);
4284         if (r < 0)
4285                 return r;
4286         if (t == USEC_INFINITY)
4287                 return 0;
4288 
4289         *timeout = t;
4290         return 1;
4291 }
4292 
pick_up_pid_from_bus_name(Service * s)4293 static bool pick_up_pid_from_bus_name(Service *s) {
4294         assert(s);
4295 
4296         /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4297 
4298         return !pid_is_valid(s->main_pid) &&
4299                 IN_SET(s->state,
4300                        SERVICE_START,
4301                        SERVICE_START_POST,
4302                        SERVICE_RUNNING,
4303                        SERVICE_RELOAD);
4304 }
4305 
bus_name_pid_lookup_callback(sd_bus_message * reply,void * userdata,sd_bus_error * ret_error)4306 static int bus_name_pid_lookup_callback(sd_bus_message *reply, void *userdata, sd_bus_error *ret_error) {
4307         const sd_bus_error *e;
4308         Unit *u = userdata;
4309         uint32_t pid;
4310         Service *s;
4311         int r;
4312 
4313         assert(reply);
4314         assert(u);
4315 
4316         s = SERVICE(u);
4317         s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
4318 
4319         if (!s->bus_name || !pick_up_pid_from_bus_name(s))
4320                 return 1;
4321 
4322         e = sd_bus_message_get_error(reply);
4323         if (e) {
4324                 r = sd_bus_error_get_errno(e);
4325                 log_warning_errno(r, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e, r));
4326                 return 1;
4327         }
4328 
4329         r = sd_bus_message_read(reply, "u", &pid);
4330         if (r < 0) {
4331                 bus_log_parse_error(r);
4332                 return 1;
4333         }
4334 
4335         if (!pid_is_valid(pid)) {
4336                 log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "GetConnectionUnixProcessID() returned invalid PID");
4337                 return 1;
4338         }
4339 
4340         log_unit_debug(u, "D-Bus name %s is now owned by process " PID_FMT, s->bus_name, (pid_t) pid);
4341 
4342         service_set_main_pid(s, pid);
4343         unit_watch_pid(UNIT(s), pid, false);
4344         return 1;
4345 }
4346 
service_bus_name_owner_change(Unit * u,const char * new_owner)4347 static void service_bus_name_owner_change(Unit *u, const char *new_owner) {
4348 
4349         Service *s = SERVICE(u);
4350         int r;
4351 
4352         assert(s);
4353 
4354         if (new_owner)
4355                 log_unit_debug(u, "D-Bus name %s now owned by %s", s->bus_name, new_owner);
4356         else
4357                 log_unit_debug(u, "D-Bus name %s now not owned by anyone.", s->bus_name);
4358 
4359         s->bus_name_good = new_owner;
4360 
4361         /* Track the current owner, so we can reconstruct changes after a daemon reload */
4362         r = free_and_strdup(&s->bus_name_owner, new_owner);
4363         if (r < 0) {
4364                 log_unit_error_errno(u, r, "Unable to set new bus name owner %s: %m", new_owner);
4365                 return;
4366         }
4367 
4368         if (s->type == SERVICE_DBUS) {
4369 
4370                 /* service_enter_running() will figure out what to
4371                  * do */
4372                 if (s->state == SERVICE_RUNNING)
4373                         service_enter_running(s, SERVICE_SUCCESS);
4374                 else if (s->state == SERVICE_START && new_owner)
4375                         service_enter_start_post(s);
4376 
4377         } else if (new_owner && pick_up_pid_from_bus_name(s)) {
4378 
4379                 /* Try to acquire PID from bus service */
4380 
4381                 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
4382 
4383                 r = sd_bus_call_method_async(
4384                                 u->manager->api_bus,
4385                                 &s->bus_name_pid_lookup_slot,
4386                                 "org.freedesktop.DBus",
4387                                 "/org/freedesktop/DBus",
4388                                 "org.freedesktop.DBus",
4389                                 "GetConnectionUnixProcessID",
4390                                 bus_name_pid_lookup_callback,
4391                                 s,
4392                                 "s",
4393                                 s->bus_name);
4394                 if (r < 0)
4395                         log_debug_errno(r, "Failed to request owner PID of service name, ignoring: %m");
4396         }
4397 }
4398 
service_set_socket_fd(Service * s,int fd,Socket * sock,SocketPeer * peer,bool selinux_context_net)4399 int service_set_socket_fd(
4400                 Service *s,
4401                 int fd,
4402                 Socket *sock,
4403                 SocketPeer *peer,
4404                 bool selinux_context_net) {
4405 
4406         _cleanup_free_ char *peer_text = NULL;
4407         int r;
4408 
4409         assert(s);
4410         assert(fd >= 0);
4411 
4412         /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
4413          * to be configured. We take ownership of the passed fd on success. */
4414 
4415         if (UNIT(s)->load_state != UNIT_LOADED)
4416                 return -EINVAL;
4417 
4418         if (s->socket_fd >= 0)
4419                 return -EBUSY;
4420 
4421         assert(!s->socket_peer);
4422 
4423         if (s->state != SERVICE_DEAD)
4424                 return -EAGAIN;
4425 
4426         if (getpeername_pretty(fd, true, &peer_text) >= 0) {
4427 
4428                 if (UNIT(s)->description) {
4429                         _cleanup_free_ char *a = NULL;
4430 
4431                         a = strjoin(UNIT(s)->description, " (", peer_text, ")");
4432                         if (!a)
4433                                 return -ENOMEM;
4434 
4435                         r = unit_set_description(UNIT(s), a);
4436                 }  else
4437                         r = unit_set_description(UNIT(s), peer_text);
4438                 if (r < 0)
4439                         return r;
4440         }
4441 
4442         r = unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false, UNIT_DEPENDENCY_IMPLICIT);
4443         if (r < 0)
4444                 return r;
4445 
4446         s->socket_fd = fd;
4447         s->socket_peer = socket_peer_ref(peer);
4448         s->socket_fd_selinux_context_net = selinux_context_net;
4449 
4450         unit_ref_set(&s->accept_socket, UNIT(s), UNIT(sock));
4451         return 0;
4452 }
4453 
service_reset_failed(Unit * u)4454 static void service_reset_failed(Unit *u) {
4455         Service *s = SERVICE(u);
4456 
4457         assert(s);
4458 
4459         if (s->state == SERVICE_FAILED)
4460                 service_set_state(s, SERVICE_DEAD);
4461 
4462         s->result = SERVICE_SUCCESS;
4463         s->reload_result = SERVICE_SUCCESS;
4464         s->clean_result = SERVICE_SUCCESS;
4465         s->n_restarts = 0;
4466         s->flush_n_restarts = false;
4467 }
4468 
service_kill(Unit * u,KillWho who,int signo,sd_bus_error * error)4469 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
4470         Service *s = SERVICE(u);
4471 
4472         assert(s);
4473 
4474         return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
4475 }
4476 
service_main_pid(Unit * u)4477 static int service_main_pid(Unit *u) {
4478         Service *s = SERVICE(u);
4479 
4480         assert(s);
4481 
4482         return s->main_pid;
4483 }
4484 
service_control_pid(Unit * u)4485 static int service_control_pid(Unit *u) {
4486         Service *s = SERVICE(u);
4487 
4488         assert(s);
4489 
4490         return s->control_pid;
4491 }
4492 
service_needs_console(Unit * u)4493 static bool service_needs_console(Unit *u) {
4494         Service *s = SERVICE(u);
4495 
4496         assert(s);
4497 
4498         /* We provide our own implementation of this here, instead of relying of the generic implementation
4499          * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
4500 
4501         if (!exec_context_may_touch_console(&s->exec_context))
4502                 return false;
4503 
4504         return IN_SET(s->state,
4505                       SERVICE_CONDITION,
4506                       SERVICE_START_PRE,
4507                       SERVICE_START,
4508                       SERVICE_START_POST,
4509                       SERVICE_RUNNING,
4510                       SERVICE_RELOAD,
4511                       SERVICE_STOP,
4512                       SERVICE_STOP_WATCHDOG,
4513                       SERVICE_STOP_SIGTERM,
4514                       SERVICE_STOP_SIGKILL,
4515                       SERVICE_STOP_POST,
4516                       SERVICE_FINAL_WATCHDOG,
4517                       SERVICE_FINAL_SIGTERM,
4518                       SERVICE_FINAL_SIGKILL);
4519 }
4520 
service_exit_status(Unit * u)4521 static int service_exit_status(Unit *u) {
4522         Service *s = SERVICE(u);
4523 
4524         assert(u);
4525 
4526         if (s->main_exec_status.pid <= 0 ||
4527             !dual_timestamp_is_set(&s->main_exec_status.exit_timestamp))
4528                 return -ENODATA;
4529 
4530         if (s->main_exec_status.code != CLD_EXITED)
4531                 return -EBADE;
4532 
4533         return s->main_exec_status.status;
4534 }
4535 
service_status_text(Unit * u)4536 static const char* service_status_text(Unit *u) {
4537         Service *s = SERVICE(u);
4538 
4539         assert(s);
4540 
4541         return s->status_text;
4542 }
4543 
service_clean(Unit * u,ExecCleanMask mask)4544 static int service_clean(Unit *u, ExecCleanMask mask) {
4545         _cleanup_strv_free_ char **l = NULL;
4546         Service *s = SERVICE(u);
4547         int r;
4548 
4549         assert(s);
4550         assert(mask != 0);
4551 
4552         if (s->state != SERVICE_DEAD)
4553                 return -EBUSY;
4554 
4555         r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
4556         if (r < 0)
4557                 return r;
4558 
4559         if (strv_isempty(l))
4560                 return -EUNATCH;
4561 
4562         service_unwatch_control_pid(s);
4563         s->clean_result = SERVICE_SUCCESS;
4564         s->control_command = NULL;
4565         s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
4566 
4567         r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->exec_context.timeout_clean_usec));
4568         if (r < 0)
4569                 goto fail;
4570 
4571         r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
4572         if (r < 0)
4573                 goto fail;
4574 
4575         service_set_state(s, SERVICE_CLEANING);
4576 
4577         return 0;
4578 
4579 fail:
4580         log_unit_warning_errno(u, r, "Failed to initiate cleaning: %m");
4581         s->clean_result = SERVICE_FAILURE_RESOURCES;
4582         s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
4583         return r;
4584 }
4585 
service_can_clean(Unit * u,ExecCleanMask * ret)4586 static int service_can_clean(Unit *u, ExecCleanMask *ret) {
4587         Service *s = SERVICE(u);
4588 
4589         assert(s);
4590 
4591         return exec_context_get_clean_mask(&s->exec_context, ret);
4592 }
4593 
service_finished_job(Unit * u,JobType t,JobResult result)4594 static const char *service_finished_job(Unit *u, JobType t, JobResult result) {
4595         if (t == JOB_START &&
4596             result == JOB_DONE &&
4597             SERVICE(u)->type == SERVICE_ONESHOT)
4598                 return "Finished %s.";
4599 
4600         /* Fall back to generic */
4601         return NULL;
4602 }
4603 
service_can_start(Unit * u)4604 static int service_can_start(Unit *u) {
4605         Service *s = SERVICE(u);
4606         int r;
4607 
4608         assert(s);
4609 
4610         /* Make sure we don't enter a busy loop of some kind. */
4611         r = unit_test_start_limit(u);
4612         if (r < 0) {
4613                 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT_HIT, false);
4614                 return r;
4615         }
4616 
4617         return 1;
4618 }
4619 
4620 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
4621         [SERVICE_RESTART_NO]          = "no",
4622         [SERVICE_RESTART_ON_SUCCESS]  = "on-success",
4623         [SERVICE_RESTART_ON_FAILURE]  = "on-failure",
4624         [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
4625         [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
4626         [SERVICE_RESTART_ON_ABORT]    = "on-abort",
4627         [SERVICE_RESTART_ALWAYS]      = "always",
4628 };
4629 
4630 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
4631 
4632 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
4633         [SERVICE_SIMPLE]  = "simple",
4634         [SERVICE_FORKING] = "forking",
4635         [SERVICE_ONESHOT] = "oneshot",
4636         [SERVICE_DBUS]    = "dbus",
4637         [SERVICE_NOTIFY]  = "notify",
4638         [SERVICE_IDLE]    = "idle",
4639         [SERVICE_EXEC]    = "exec",
4640 };
4641 
4642 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
4643 
4644 static const char* const service_exit_type_table[_SERVICE_EXIT_TYPE_MAX] = {
4645         [SERVICE_EXIT_MAIN]   = "main",
4646         [SERVICE_EXIT_CGROUP] = "cgroup",
4647 };
4648 
4649 DEFINE_STRING_TABLE_LOOKUP(service_exit_type, ServiceExitType);
4650 
4651 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
4652         [SERVICE_EXEC_CONDITION]  = "ExecCondition",
4653         [SERVICE_EXEC_START_PRE]  = "ExecStartPre",
4654         [SERVICE_EXEC_START]      = "ExecStart",
4655         [SERVICE_EXEC_START_POST] = "ExecStartPost",
4656         [SERVICE_EXEC_RELOAD]     = "ExecReload",
4657         [SERVICE_EXEC_STOP]       = "ExecStop",
4658         [SERVICE_EXEC_STOP_POST]  = "ExecStopPost",
4659 };
4660 
4661 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
4662 
4663 static const char* const service_exec_ex_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
4664         [SERVICE_EXEC_CONDITION]  = "ExecConditionEx",
4665         [SERVICE_EXEC_START_PRE]  = "ExecStartPreEx",
4666         [SERVICE_EXEC_START]      = "ExecStartEx",
4667         [SERVICE_EXEC_START_POST] = "ExecStartPostEx",
4668         [SERVICE_EXEC_RELOAD]     = "ExecReloadEx",
4669         [SERVICE_EXEC_STOP]       = "ExecStopEx",
4670         [SERVICE_EXEC_STOP_POST]  = "ExecStopPostEx",
4671 };
4672 
4673 DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command, ServiceExecCommand);
4674 
4675 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
4676         [NOTIFY_UNKNOWN]   = "unknown",
4677         [NOTIFY_READY]     = "ready",
4678         [NOTIFY_RELOADING] = "reloading",
4679         [NOTIFY_STOPPING]  = "stopping",
4680 };
4681 
4682 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
4683 
4684 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
4685         [SERVICE_SUCCESS]                 = "success",
4686         [SERVICE_FAILURE_RESOURCES]       = "resources",
4687         [SERVICE_FAILURE_PROTOCOL]        = "protocol",
4688         [SERVICE_FAILURE_TIMEOUT]         = "timeout",
4689         [SERVICE_FAILURE_EXIT_CODE]       = "exit-code",
4690         [SERVICE_FAILURE_SIGNAL]          = "signal",
4691         [SERVICE_FAILURE_CORE_DUMP]       = "core-dump",
4692         [SERVICE_FAILURE_WATCHDOG]        = "watchdog",
4693         [SERVICE_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
4694         [SERVICE_FAILURE_OOM_KILL]        = "oom-kill",
4695         [SERVICE_SKIP_CONDITION]          = "exec-condition",
4696 };
4697 
4698 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
4699 
4700 static const char* const service_timeout_failure_mode_table[_SERVICE_TIMEOUT_FAILURE_MODE_MAX] = {
4701         [SERVICE_TIMEOUT_TERMINATE] = "terminate",
4702         [SERVICE_TIMEOUT_ABORT]     = "abort",
4703         [SERVICE_TIMEOUT_KILL]      = "kill",
4704 };
4705 
4706 DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode, ServiceTimeoutFailureMode);
4707 
4708 const UnitVTable service_vtable = {
4709         .object_size = sizeof(Service),
4710         .exec_context_offset = offsetof(Service, exec_context),
4711         .cgroup_context_offset = offsetof(Service, cgroup_context),
4712         .kill_context_offset = offsetof(Service, kill_context),
4713         .exec_runtime_offset = offsetof(Service, exec_runtime),
4714         .dynamic_creds_offset = offsetof(Service, dynamic_creds),
4715 
4716         .sections =
4717                 "Unit\0"
4718                 "Service\0"
4719                 "Install\0",
4720         .private_section = "Service",
4721 
4722         .can_transient = true,
4723         .can_delegate = true,
4724         .can_fail = true,
4725         .can_set_managed_oom = true,
4726 
4727         .init = service_init,
4728         .done = service_done,
4729         .load = service_load,
4730         .release_resources = service_release_resources,
4731 
4732         .coldplug = service_coldplug,
4733 
4734         .dump = service_dump,
4735 
4736         .start = service_start,
4737         .stop = service_stop,
4738         .reload = service_reload,
4739 
4740         .can_reload = service_can_reload,
4741 
4742         .kill = service_kill,
4743         .clean = service_clean,
4744         .can_clean = service_can_clean,
4745 
4746         .freeze = unit_freeze_vtable_common,
4747         .thaw = unit_thaw_vtable_common,
4748 
4749         .serialize = service_serialize,
4750         .deserialize_item = service_deserialize_item,
4751 
4752         .active_state = service_active_state,
4753         .sub_state_to_string = service_sub_state_to_string,
4754 
4755         .will_restart = service_will_restart,
4756 
4757         .may_gc = service_may_gc,
4758 
4759         .sigchld_event = service_sigchld_event,
4760 
4761         .reset_failed = service_reset_failed,
4762 
4763         .notify_cgroup_empty = service_notify_cgroup_empty_event,
4764         .notify_cgroup_oom = service_notify_cgroup_oom_event,
4765         .notify_message = service_notify_message,
4766 
4767         .main_pid = service_main_pid,
4768         .control_pid = service_control_pid,
4769 
4770         .bus_name_owner_change = service_bus_name_owner_change,
4771 
4772         .bus_set_property = bus_service_set_property,
4773         .bus_commit_properties = bus_service_commit_properties,
4774 
4775         .get_timeout = service_get_timeout,
4776         .needs_console = service_needs_console,
4777         .exit_status = service_exit_status,
4778         .status_text = service_status_text,
4779 
4780         .status_message_formats = {
4781                 .finished_start_job = {
4782                         [JOB_FAILED]     = "Failed to start %s.",
4783                 },
4784                 .finished_stop_job = {
4785                         [JOB_DONE]       = "Stopped %s.",
4786                         [JOB_FAILED]     = "Stopped (with error) %s.",
4787                 },
4788                 .finished_job = service_finished_job,
4789         },
4790 
4791         .can_start = service_can_start,
4792 };
4793