1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3
4 #include <stdbool.h>
5 #include <stdlib.h>
6 #include <sys/socket.h>
7 #include <unistd.h>
8
9 #include "sd-id128.h"
10
11 #include "bpf-program.h"
12 #include "condition.h"
13 #include "emergency-action.h"
14 #include "list.h"
15 #include "show-status.h"
16 #include "set.h"
17 #include "unit-file.h"
18 #include "cgroup.h"
19
20 typedef struct UnitRef UnitRef;
21
22 typedef enum KillOperation {
23 KILL_TERMINATE,
24 KILL_TERMINATE_AND_LOG,
25 KILL_RESTART,
26 KILL_KILL,
27 KILL_WATCHDOG,
28 _KILL_OPERATION_MAX,
29 _KILL_OPERATION_INVALID = -EINVAL,
30 } KillOperation;
31
32 typedef enum CollectMode {
33 COLLECT_INACTIVE,
34 COLLECT_INACTIVE_OR_FAILED,
35 _COLLECT_MODE_MAX,
36 _COLLECT_MODE_INVALID = -EINVAL,
37 } CollectMode;
38
UNIT_IS_ACTIVE_OR_RELOADING(UnitActiveState t)39 static inline bool UNIT_IS_ACTIVE_OR_RELOADING(UnitActiveState t) {
40 return IN_SET(t, UNIT_ACTIVE, UNIT_RELOADING);
41 }
42
UNIT_IS_ACTIVE_OR_ACTIVATING(UnitActiveState t)43 static inline bool UNIT_IS_ACTIVE_OR_ACTIVATING(UnitActiveState t) {
44 return IN_SET(t, UNIT_ACTIVE, UNIT_ACTIVATING, UNIT_RELOADING);
45 }
46
UNIT_IS_INACTIVE_OR_DEACTIVATING(UnitActiveState t)47 static inline bool UNIT_IS_INACTIVE_OR_DEACTIVATING(UnitActiveState t) {
48 return IN_SET(t, UNIT_INACTIVE, UNIT_FAILED, UNIT_DEACTIVATING);
49 }
50
UNIT_IS_INACTIVE_OR_FAILED(UnitActiveState t)51 static inline bool UNIT_IS_INACTIVE_OR_FAILED(UnitActiveState t) {
52 return IN_SET(t, UNIT_INACTIVE, UNIT_FAILED);
53 }
54
UNIT_IS_LOAD_COMPLETE(UnitLoadState t)55 static inline bool UNIT_IS_LOAD_COMPLETE(UnitLoadState t) {
56 return t >= 0 && t < _UNIT_LOAD_STATE_MAX && t != UNIT_STUB && t != UNIT_MERGED;
57 }
58
59 /* Stores the 'reason' a dependency was created as a bit mask, i.e. due to which configuration source it came to be. We
60 * use this so that we can selectively flush out parts of dependencies again. Note that the same dependency might be
61 * created as a result of multiple "reasons", hence the bitmask. */
62 typedef enum UnitDependencyMask {
63 /* Configured directly by the unit file, .wants/.requires symlink or drop-in, or as an immediate result of a
64 * non-dependency option configured that way. */
65 UNIT_DEPENDENCY_FILE = 1 << 0,
66
67 /* As unconditional implicit dependency (not affected by unit configuration — except by the unit name and
68 * type) */
69 UNIT_DEPENDENCY_IMPLICIT = 1 << 1,
70
71 /* A dependency effected by DefaultDependencies=yes. Note that dependencies marked this way are conceptually
72 * just a subset of UNIT_DEPENDENCY_FILE, as DefaultDependencies= is itself a unit file setting that can only
73 * be set in unit files. We make this two separate bits only to help debugging how dependencies came to be. */
74 UNIT_DEPENDENCY_DEFAULT = 1 << 2,
75
76 /* A dependency created from udev rules */
77 UNIT_DEPENDENCY_UDEV = 1 << 3,
78
79 /* A dependency created because of some unit's RequiresMountsFor= setting */
80 UNIT_DEPENDENCY_PATH = 1 << 4,
81
82 /* A dependency created because of data read from /proc/self/mountinfo and no other configuration source */
83 UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT = 1 << 5,
84
85 /* A dependency created because of data read from /proc/self/mountinfo, but conditionalized by
86 * DefaultDependencies= and thus also involving configuration from UNIT_DEPENDENCY_FILE sources */
87 UNIT_DEPENDENCY_MOUNTINFO_DEFAULT = 1 << 6,
88
89 /* A dependency created because of data read from /proc/swaps and no other configuration source */
90 UNIT_DEPENDENCY_PROC_SWAP = 1 << 7,
91
92 /* A dependency for units in slices assigned by directly setting Slice= */
93 UNIT_DEPENDENCY_SLICE_PROPERTY = 1 << 8,
94
95 _UNIT_DEPENDENCY_MASK_FULL = (1 << 9) - 1,
96 } UnitDependencyMask;
97
98 /* The Unit's dependencies[] hashmaps use this structure as value. It has the same size as a void pointer, and thus can
99 * be stored directly as hashmap value, without any indirection. Note that this stores two masks, as both the origin
100 * and the destination of a dependency might have created it. */
101 typedef union UnitDependencyInfo {
102 void *data;
103 struct {
104 UnitDependencyMask origin_mask:16;
105 UnitDependencyMask destination_mask:16;
106 } _packed_;
107 } UnitDependencyInfo;
108
109 /* Newer LLVM versions don't like implicit casts from large pointer types to smaller enums, hence let's add
110 * explicit type-safe helpers for that. */
UNIT_DEPENDENCY_FROM_PTR(const void * p)111 static inline UnitDependency UNIT_DEPENDENCY_FROM_PTR(const void *p) {
112 return PTR_TO_INT(p);
113 }
114
UNIT_DEPENDENCY_TO_PTR(UnitDependency d)115 static inline void* UNIT_DEPENDENCY_TO_PTR(UnitDependency d) {
116 return INT_TO_PTR(d);
117 }
118
119 #include "job.h"
120
121 struct UnitRef {
122 /* Keeps tracks of references to a unit. This is useful so
123 * that we can merge two units if necessary and correct all
124 * references to them */
125
126 Unit *source, *target;
127 LIST_FIELDS(UnitRef, refs_by_target);
128 };
129
130 typedef struct Unit {
131 Manager *manager;
132
133 UnitType type;
134 UnitLoadState load_state;
135 Unit *merged_into;
136
137 char *id; /* The one special name that we use for identification */
138 char *instance;
139
140 Set *aliases; /* All the other names. */
141
142 /* For each dependency type we can look up another Hashmap with this, whose key is a Unit* object,
143 * and whose value encodes why the dependency exists, using the UnitDependencyInfo type. i.e. a
144 * Hashmap(UnitDependency → Hashmap(Unit* → UnitDependencyInfo)) */
145 Hashmap *dependencies;
146
147 /* Similar, for RequiresMountsFor= path dependencies. The key is the path, the value the
148 * UnitDependencyInfo type */
149 Hashmap *requires_mounts_for;
150
151 char *description;
152 char **documentation;
153
154 char *fragment_path; /* if loaded from a config file this is the primary path to it */
155 char *source_path; /* if converted, the source file */
156 char **dropin_paths;
157
158 usec_t fragment_not_found_timestamp_hash;
159 usec_t fragment_mtime;
160 usec_t source_mtime;
161 usec_t dropin_mtime;
162
163 /* If this is a transient unit we are currently writing, this is where we are writing it to */
164 FILE *transient_file;
165
166 /* Freezer state */
167 sd_bus_message *pending_freezer_message;
168 FreezerState freezer_state;
169
170 /* Job timeout and action to take */
171 EmergencyAction job_timeout_action;
172 usec_t job_timeout;
173 usec_t job_running_timeout;
174 char *job_timeout_reboot_arg;
175
176 /* If there is something to do with this unit, then this is the installed job for it */
177 Job *job;
178
179 /* JOB_NOP jobs are special and can be installed without disturbing the real job. */
180 Job *nop_job;
181
182 /* The slot used for watching NameOwnerChanged signals */
183 sd_bus_slot *match_bus_slot;
184 sd_bus_slot *get_name_owner_slot;
185
186 /* References to this unit from clients */
187 sd_bus_track *bus_track;
188 char **deserialized_refs;
189
190 /* References to this */
191 LIST_HEAD(UnitRef, refs_by_target);
192
193 /* Conditions to check */
194 LIST_HEAD(Condition, conditions);
195 LIST_HEAD(Condition, asserts);
196
197 dual_timestamp condition_timestamp;
198 dual_timestamp assert_timestamp;
199
200 /* Updated whenever the low-level state changes */
201 dual_timestamp state_change_timestamp;
202
203 /* Updated whenever the (high-level) active state enters or leaves the active or inactive states */
204 dual_timestamp inactive_exit_timestamp;
205 dual_timestamp active_enter_timestamp;
206 dual_timestamp active_exit_timestamp;
207 dual_timestamp inactive_enter_timestamp;
208
209 /* Per type list */
210 LIST_FIELDS(Unit, units_by_type);
211
212 /* Load queue */
213 LIST_FIELDS(Unit, load_queue);
214
215 /* D-Bus queue */
216 LIST_FIELDS(Unit, dbus_queue);
217
218 /* Cleanup queue */
219 LIST_FIELDS(Unit, cleanup_queue);
220
221 /* GC queue */
222 LIST_FIELDS(Unit, gc_queue);
223
224 /* CGroup realize members queue */
225 LIST_FIELDS(Unit, cgroup_realize_queue);
226
227 /* cgroup empty queue */
228 LIST_FIELDS(Unit, cgroup_empty_queue);
229
230 /* cgroup OOM queue */
231 LIST_FIELDS(Unit, cgroup_oom_queue);
232
233 /* Target dependencies queue */
234 LIST_FIELDS(Unit, target_deps_queue);
235
236 /* Queue of units with StopWhenUnneeded= set that shall be checked for clean-up. */
237 LIST_FIELDS(Unit, stop_when_unneeded_queue);
238
239 /* Queue of units that have an Uphold= dependency from some other unit, and should be checked for starting */
240 LIST_FIELDS(Unit, start_when_upheld_queue);
241
242 /* Queue of units that have a BindTo= dependency on some other unit, and should possibly be shut down */
243 LIST_FIELDS(Unit, stop_when_bound_queue);
244
245 /* PIDs we keep an eye on. Note that a unit might have many
246 * more, but these are the ones we care enough about to
247 * process SIGCHLD for */
248 Set *pids;
249
250 /* Used in SIGCHLD and sd_notify() message event invocation logic to avoid that we dispatch the same event
251 * multiple times on the same unit. */
252 unsigned sigchldgen;
253 unsigned notifygen;
254
255 /* Used during GC sweeps */
256 unsigned gc_marker;
257
258 /* Error code when we didn't manage to load the unit (negative) */
259 int load_error;
260
261 /* Put a ratelimit on unit starting */
262 RateLimit start_ratelimit;
263 EmergencyAction start_limit_action;
264
265 /* The unit has been marked for reload, restart, etc. Stored as 1u << marker1 | 1u << marker2. */
266 unsigned markers;
267
268 /* What to do on failure or success */
269 EmergencyAction success_action, failure_action;
270 int success_action_exit_status, failure_action_exit_status;
271 char *reboot_arg;
272
273 /* Make sure we never enter endless loops with the StopWhenUnneeded=, BindsTo=, Uphold= logic */
274 RateLimit auto_start_stop_ratelimit;
275
276 /* Reference to a specific UID/GID */
277 uid_t ref_uid;
278 gid_t ref_gid;
279
280 /* Cached unit file state and preset */
281 UnitFileState unit_file_state;
282 int unit_file_preset;
283
284 /* Where the cpu.stat or cpuacct.usage was at the time the unit was started */
285 nsec_t cpu_usage_base;
286 nsec_t cpu_usage_last; /* the most recently read value */
287
288 /* The current counter of OOM kills initiated by systemd-oomd */
289 uint64_t managed_oom_kill_last;
290
291 /* The current counter of the oom_kill field in the memory.events cgroup attribute */
292 uint64_t oom_kill_last;
293
294 /* Where the io.stat data was at the time the unit was started */
295 uint64_t io_accounting_base[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
296 uint64_t io_accounting_last[_CGROUP_IO_ACCOUNTING_METRIC_MAX]; /* the most recently read value */
297
298 /* Counterparts in the cgroup filesystem */
299 char *cgroup_path;
300 uint64_t cgroup_id;
301 CGroupMask cgroup_realized_mask; /* In which hierarchies does this unit's cgroup exist? (only relevant on cgroup v1) */
302 CGroupMask cgroup_enabled_mask; /* Which controllers are enabled (or more correctly: enabled for the children) for this unit's cgroup? (only relevant on cgroup v2) */
303 CGroupMask cgroup_invalidated_mask; /* A mask specifying controllers which shall be considered invalidated, and require re-realization */
304 CGroupMask cgroup_members_mask; /* A cache for the controllers required by all children of this cgroup (only relevant for slice units) */
305
306 /* Inotify watch descriptors for watching cgroup.events and memory.events on cgroupv2 */
307 int cgroup_control_inotify_wd;
308 int cgroup_memory_inotify_wd;
309
310 /* Device Controller BPF program */
311 BPFProgram *bpf_device_control_installed;
312
313 /* IP BPF Firewalling/accounting */
314 int ip_accounting_ingress_map_fd;
315 int ip_accounting_egress_map_fd;
316 uint64_t ip_accounting_extra[_CGROUP_IP_ACCOUNTING_METRIC_MAX];
317
318 int ipv4_allow_map_fd;
319 int ipv6_allow_map_fd;
320 int ipv4_deny_map_fd;
321 int ipv6_deny_map_fd;
322 BPFProgram *ip_bpf_ingress, *ip_bpf_ingress_installed;
323 BPFProgram *ip_bpf_egress, *ip_bpf_egress_installed;
324
325 Set *ip_bpf_custom_ingress;
326 Set *ip_bpf_custom_ingress_installed;
327 Set *ip_bpf_custom_egress;
328 Set *ip_bpf_custom_egress_installed;
329
330 /* BPF programs managed (e.g. loaded to kernel) by an entity external to systemd,
331 * attached to unit cgroup by provided program fd and attach type. */
332 Hashmap *bpf_foreign_by_key;
333
334 FDSet *initial_socket_bind_link_fds;
335 #if BPF_FRAMEWORK
336 /* BPF links to BPF programs attached to cgroup/bind{4|6} hooks and
337 * responsible for allowing or denying a unit to bind(2) to a socket
338 * address. */
339 struct bpf_link *ipv4_socket_bind_link;
340 struct bpf_link *ipv6_socket_bind_link;
341 #endif
342
343 FDSet *initial_restric_ifaces_link_fds;
344 #if BPF_FRAMEWORK
345 struct bpf_link *restrict_ifaces_ingress_bpf_link;
346 struct bpf_link *restrict_ifaces_egress_bpf_link;
347 #endif
348
349 /* Low-priority event source which is used to remove watched PIDs that have gone away, and subscribe to any new
350 * ones which might have appeared. */
351 sd_event_source *rewatch_pids_event_source;
352
353 /* How to start OnSuccess=/OnFailure= units */
354 JobMode on_success_job_mode;
355 JobMode on_failure_job_mode;
356
357 /* Tweaking the GC logic */
358 CollectMode collect_mode;
359
360 /* The current invocation ID */
361 sd_id128_t invocation_id;
362 char invocation_id_string[SD_ID128_STRING_MAX]; /* useful when logging */
363
364 /* Garbage collect us we nobody wants or requires us anymore */
365 bool stop_when_unneeded;
366
367 /* Create default dependencies */
368 bool default_dependencies;
369
370 /* Refuse manual starting, allow starting only indirectly via dependency. */
371 bool refuse_manual_start;
372
373 /* Don't allow the user to stop this unit manually, allow stopping only indirectly via dependency. */
374 bool refuse_manual_stop;
375
376 /* Allow isolation requests */
377 bool allow_isolate;
378
379 /* Ignore this unit when isolating */
380 bool ignore_on_isolate;
381
382 /* Did the last condition check succeed? */
383 bool condition_result;
384 bool assert_result;
385
386 /* Is this a transient unit? */
387 bool transient;
388
389 /* Is this a unit that is always running and cannot be stopped? */
390 bool perpetual;
391
392 /* Booleans indicating membership of this unit in the various queues */
393 bool in_load_queue:1;
394 bool in_dbus_queue:1;
395 bool in_cleanup_queue:1;
396 bool in_gc_queue:1;
397 bool in_cgroup_realize_queue:1;
398 bool in_cgroup_empty_queue:1;
399 bool in_cgroup_oom_queue:1;
400 bool in_target_deps_queue:1;
401 bool in_stop_when_unneeded_queue:1;
402 bool in_start_when_upheld_queue:1;
403 bool in_stop_when_bound_queue:1;
404
405 bool sent_dbus_new_signal:1;
406
407 bool job_running_timeout_set:1;
408
409 bool in_audit:1;
410 bool on_console:1;
411
412 bool cgroup_realized:1;
413 bool cgroup_members_mask_valid:1;
414
415 /* Reset cgroup accounting next time we fork something off */
416 bool reset_accounting:1;
417
418 bool start_limit_hit:1;
419
420 /* Did we already invoke unit_coldplug() for this unit? */
421 bool coldplugged:1;
422
423 /* For transient units: whether to add a bus track reference after creating the unit */
424 bool bus_track_add:1;
425
426 /* Remember which unit state files we created */
427 bool exported_invocation_id:1;
428 bool exported_log_level_max:1;
429 bool exported_log_extra_fields:1;
430 bool exported_log_ratelimit_interval:1;
431 bool exported_log_ratelimit_burst:1;
432
433 /* Whether we warned about clamping the CPU quota period */
434 bool warned_clamping_cpu_quota_period:1;
435
436 /* When writing transient unit files, stores which section we stored last. If < 0, we didn't write any yet. If
437 * == 0 we are in the [Unit] section, if > 0 we are in the unit type-specific section. */
438 signed int last_section_private:2;
439 } Unit;
440
441 typedef struct UnitStatusMessageFormats {
442 const char *starting_stopping[2];
443 const char *finished_start_job[_JOB_RESULT_MAX];
444 const char *finished_stop_job[_JOB_RESULT_MAX];
445 /* If this entry is present, it'll be called to provide a context-dependent format string,
446 * or NULL to fall back to finished_{start,stop}_job; if those are NULL too, fall back to generic. */
447 const char *(*finished_job)(Unit *u, JobType t, JobResult result);
448 } UnitStatusMessageFormats;
449
450 /* Flags used when writing drop-in files or transient unit files */
451 typedef enum UnitWriteFlags {
452 /* Write a runtime unit file or drop-in (i.e. one below /run) */
453 UNIT_RUNTIME = 1 << 0,
454
455 /* Write a persistent drop-in (i.e. one below /etc) */
456 UNIT_PERSISTENT = 1 << 1,
457
458 /* Place this item in the per-unit-type private section, instead of [Unit] */
459 UNIT_PRIVATE = 1 << 2,
460
461 /* Apply specifier escaping before writing */
462 UNIT_ESCAPE_SPECIFIERS = 1 << 3,
463
464 /* Apply C escaping before writing */
465 UNIT_ESCAPE_C = 1 << 4,
466 } UnitWriteFlags;
467
468 /* Returns true if neither persistent, nor runtime storage is requested, i.e. this is a check invocation only */
UNIT_WRITE_FLAGS_NOOP(UnitWriteFlags flags)469 static inline bool UNIT_WRITE_FLAGS_NOOP(UnitWriteFlags flags) {
470 return (flags & (UNIT_RUNTIME|UNIT_PERSISTENT)) == 0;
471 }
472
473 #include "kill.h"
474
475 typedef struct UnitVTable {
476 /* How much memory does an object of this unit type need */
477 size_t object_size;
478
479 /* If greater than 0, the offset into the object where
480 * ExecContext is found, if the unit type has that */
481 size_t exec_context_offset;
482
483 /* If greater than 0, the offset into the object where
484 * CGroupContext is found, if the unit type has that */
485 size_t cgroup_context_offset;
486
487 /* If greater than 0, the offset into the object where
488 * KillContext is found, if the unit type has that */
489 size_t kill_context_offset;
490
491 /* If greater than 0, the offset into the object where the
492 * pointer to ExecRuntime is found, if the unit type has
493 * that */
494 size_t exec_runtime_offset;
495
496 /* If greater than 0, the offset into the object where the pointer to DynamicCreds is found, if the unit type
497 * has that. */
498 size_t dynamic_creds_offset;
499
500 /* The name of the configuration file section with the private settings of this unit */
501 const char *private_section;
502
503 /* Config file sections this unit type understands, separated
504 * by NUL chars */
505 const char *sections;
506
507 /* This should reset all type-specific variables. This should
508 * not allocate memory, and is called with zero-initialized
509 * data. It should hence only initialize variables that need
510 * to be set != 0. */
511 void (*init)(Unit *u);
512
513 /* This should free all type-specific variables. It should be
514 * idempotent. */
515 void (*done)(Unit *u);
516
517 /* Actually load data from disk. This may fail, and should set
518 * load_state to UNIT_LOADED, UNIT_MERGED or leave it at
519 * UNIT_STUB if no configuration could be found. */
520 int (*load)(Unit *u);
521
522 /* During deserialization we only record the intended state to return to. With coldplug() we actually put the
523 * deserialized state in effect. This is where unit_notify() should be called to start things up. Note that
524 * this callback is invoked *before* we leave the reloading state of the manager, i.e. *before* we consider the
525 * reloading to be complete. Thus, this callback should just restore the exact same state for any unit that was
526 * in effect before the reload, i.e. units should not catch up with changes happened during the reload. That's
527 * what catchup() below is for. */
528 int (*coldplug)(Unit *u);
529
530 /* This is called shortly after all units' coldplug() call was invoked, and *after* the manager left the
531 * reloading state. It's supposed to catch up with state changes due to external events we missed so far (for
532 * example because they took place while we were reloading/reexecing) */
533 void (*catchup)(Unit *u);
534
535 void (*dump)(Unit *u, FILE *f, const char *prefix);
536
537 int (*start)(Unit *u);
538 int (*stop)(Unit *u);
539 int (*reload)(Unit *u);
540
541 int (*kill)(Unit *u, KillWho w, int signo, sd_bus_error *error);
542
543 /* Clear out the various runtime/state/cache/logs/configuration data */
544 int (*clean)(Unit *u, ExecCleanMask m);
545
546 /* Freeze the unit */
547 int (*freeze)(Unit *u);
548 int (*thaw)(Unit *u);
549 bool (*can_freeze)(Unit *u);
550
551 /* Return which kind of data can be cleaned */
552 int (*can_clean)(Unit *u, ExecCleanMask *ret);
553
554 bool (*can_reload)(Unit *u);
555
556 /* Serialize state and file descriptors that should be carried over into the new
557 * instance after reexecution. */
558 int (*serialize)(Unit *u, FILE *f, FDSet *fds);
559
560 /* Restore one item from the serialization */
561 int (*deserialize_item)(Unit *u, const char *key, const char *data, FDSet *fds);
562
563 /* Try to match up fds with what we need for this unit */
564 void (*distribute_fds)(Unit *u, FDSet *fds);
565
566 /* Boils down the more complex internal state of this unit to
567 * a simpler one that the engine can understand */
568 UnitActiveState (*active_state)(Unit *u);
569
570 /* Returns the substate specific to this unit type as
571 * string. This is purely information so that we can give the
572 * user a more fine grained explanation in which actual state a
573 * unit is in. */
574 const char* (*sub_state_to_string)(Unit *u);
575
576 /* Additionally to UnitActiveState determine whether unit is to be restarted. */
577 bool (*will_restart)(Unit *u);
578
579 /* Return false when there is a reason to prevent this unit from being gc'ed
580 * even though nothing references it and it isn't active in any way. */
581 bool (*may_gc)(Unit *u);
582
583 /* Return true when the unit is not controlled by the manager (e.g. extrinsic mounts). */
584 bool (*is_extrinsic)(Unit *u);
585
586 /* When the unit is not running and no job for it queued we shall release its runtime resources */
587 void (*release_resources)(Unit *u);
588
589 /* Invoked on every child that died */
590 void (*sigchld_event)(Unit *u, pid_t pid, int code, int status);
591
592 /* Reset failed state if we are in failed state */
593 void (*reset_failed)(Unit *u);
594
595 /* Called whenever any of the cgroups this unit watches for ran empty */
596 void (*notify_cgroup_empty)(Unit *u);
597
598 /* Called whenever an OOM kill event on this unit was seen */
599 void (*notify_cgroup_oom)(Unit *u, bool managed_oom);
600
601 /* Called whenever a process of this unit sends us a message */
602 void (*notify_message)(Unit *u, const struct ucred *ucred, char * const *tags, FDSet *fds);
603
604 /* Called whenever a name this Unit registered for comes or goes away. */
605 void (*bus_name_owner_change)(Unit *u, const char *new_owner);
606
607 /* Called for each property that is being set */
608 int (*bus_set_property)(Unit *u, const char *name, sd_bus_message *message, UnitWriteFlags flags, sd_bus_error *error);
609
610 /* Called after at least one property got changed to apply the necessary change */
611 int (*bus_commit_properties)(Unit *u);
612
613 /* Return the unit this unit is following */
614 Unit *(*following)(Unit *u);
615
616 /* Return the set of units that are following each other */
617 int (*following_set)(Unit *u, Set **s);
618
619 /* Invoked each time a unit this unit is triggering changes
620 * state or gains/loses a job */
621 void (*trigger_notify)(Unit *u, Unit *trigger);
622
623 /* Called whenever CLOCK_REALTIME made a jump */
624 void (*time_change)(Unit *u);
625
626 /* Called whenever /etc/localtime was modified */
627 void (*timezone_change)(Unit *u);
628
629 /* Returns the next timeout of a unit */
630 int (*get_timeout)(Unit *u, usec_t *timeout);
631
632 /* Returns the main PID if there is any defined, or 0. */
633 pid_t (*main_pid)(Unit *u);
634
635 /* Returns the main PID if there is any defined, or 0. */
636 pid_t (*control_pid)(Unit *u);
637
638 /* Returns true if the unit currently needs access to the console */
639 bool (*needs_console)(Unit *u);
640
641 /* Returns the exit status to propagate in case of FailureAction=exit/SuccessAction=exit; usually returns the
642 * exit code of the "main" process of the service or similar. */
643 int (*exit_status)(Unit *u);
644
645 /* Return a copy of the status string pointer. */
646 const char* (*status_text)(Unit *u);
647
648 /* Like the enumerate() callback further down, but only enumerates the perpetual units, i.e. all units that
649 * unconditionally exist and are always active. The main reason to keep both enumeration functions separate is
650 * philosophical: the state of perpetual units should be put in place by coldplug(), while the state of those
651 * discovered through regular enumeration should be put in place by catchup(), see below. */
652 void (*enumerate_perpetual)(Manager *m);
653
654 /* This is called for each unit type and should be used to enumerate units already existing in the system
655 * internally and load them. However, everything that is loaded here should still stay in inactive state. It is
656 * the job of the catchup() call above to put the units into the discovered state. */
657 void (*enumerate)(Manager *m);
658
659 /* Type specific cleanups. */
660 void (*shutdown)(Manager *m);
661
662 /* If this function is set and returns false all jobs for units
663 * of this type will immediately fail. */
664 bool (*supported)(void);
665
666 /* If this function is set, it's invoked first as part of starting a unit to allow start rate
667 * limiting checks to occur before we do anything else. */
668 int (*can_start)(Unit *u);
669
670 /* The strings to print in status messages */
671 UnitStatusMessageFormats status_message_formats;
672
673 /* True if transient units of this type are OK */
674 bool can_transient;
675
676 /* True if cgroup delegation is permissible */
677 bool can_delegate;
678
679 /* True if the unit type triggers other units, i.e. can have a UNIT_TRIGGERS dependency */
680 bool can_trigger;
681
682 /* True if the unit type knows a failure state, and thus can be source of an OnFailure= dependency */
683 bool can_fail;
684
685 /* True if units of this type shall be startable only once and then never again */
686 bool once_only;
687
688 /* Do not serialize this unit when preparing for root switch */
689 bool exclude_from_switch_root_serialization;
690
691 /* True if queued jobs of this type should be GC'ed if no other job needs them anymore */
692 bool gc_jobs;
693
694 /* True if systemd-oomd can monitor and act on this unit's recursive children's cgroup(s) */
695 bool can_set_managed_oom;
696 } UnitVTable;
697
698 extern const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX];
699
UNIT_VTABLE(const Unit * u)700 static inline const UnitVTable* UNIT_VTABLE(const Unit *u) {
701 return unit_vtable[u->type];
702 }
703
704 /* For casting a unit into the various unit types */
705 #define DEFINE_CAST(UPPERCASE, MixedCase) \
706 static inline MixedCase* UPPERCASE(Unit *u) { \
707 if (_unlikely_(!u || u->type != UNIT_##UPPERCASE)) \
708 return NULL; \
709 \
710 return (MixedCase*) u; \
711 }
712
713 /* For casting the various unit types into a unit */
714 #define UNIT(u) \
715 ({ \
716 typeof(u) _u_ = (u); \
717 Unit *_w_ = _u_ ? &(_u_)->meta : NULL; \
718 _w_; \
719 })
720
721 #define UNIT_HAS_EXEC_CONTEXT(u) (UNIT_VTABLE(u)->exec_context_offset > 0)
722 #define UNIT_HAS_CGROUP_CONTEXT(u) (UNIT_VTABLE(u)->cgroup_context_offset > 0)
723 #define UNIT_HAS_KILL_CONTEXT(u) (UNIT_VTABLE(u)->kill_context_offset > 0)
724
725 Unit* unit_has_dependency(const Unit *u, UnitDependencyAtom atom, Unit *other);
726 int unit_get_dependency_array(const Unit *u, UnitDependencyAtom atom, Unit ***ret_array);
727
unit_get_dependencies(Unit * u,UnitDependency d)728 static inline Hashmap* unit_get_dependencies(Unit *u, UnitDependency d) {
729 return hashmap_get(u->dependencies, UNIT_DEPENDENCY_TO_PTR(d));
730 }
731
UNIT_TRIGGER(Unit * u)732 static inline Unit* UNIT_TRIGGER(Unit *u) {
733 return unit_has_dependency(u, UNIT_ATOM_TRIGGERS, NULL);
734 }
735
UNIT_GET_SLICE(const Unit * u)736 static inline Unit* UNIT_GET_SLICE(const Unit *u) {
737 return unit_has_dependency(u, UNIT_ATOM_IN_SLICE, NULL);
738 }
739
740 Unit* unit_new(Manager *m, size_t size);
741 Unit* unit_free(Unit *u);
742 DEFINE_TRIVIAL_CLEANUP_FUNC(Unit *, unit_free);
743
744 int unit_new_for_name(Manager *m, size_t size, const char *name, Unit **ret);
745 int unit_add_name(Unit *u, const char *name);
746
747 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference, UnitDependencyMask mask);
748 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference, UnitDependencyMask mask);
749
750 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, bool add_reference, UnitDependencyMask mask);
751 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, bool add_reference, UnitDependencyMask mask);
752
753 int unit_add_exec_dependencies(Unit *u, ExecContext *c);
754
755 int unit_choose_id(Unit *u, const char *name);
756 int unit_set_description(Unit *u, const char *description);
757
758 bool unit_may_gc(Unit *u);
759
unit_is_extrinsic(Unit * u)760 static inline bool unit_is_extrinsic(Unit *u) {
761 return u->perpetual ||
762 (UNIT_VTABLE(u)->is_extrinsic && UNIT_VTABLE(u)->is_extrinsic(u));
763 }
764
unit_status_text(Unit * u)765 static inline const char* unit_status_text(Unit *u) {
766 if (u && UNIT_VTABLE(u)->status_text)
767 return UNIT_VTABLE(u)->status_text(u);
768 return NULL;
769 }
770
771 void unit_add_to_load_queue(Unit *u);
772 void unit_add_to_dbus_queue(Unit *u);
773 void unit_add_to_cleanup_queue(Unit *u);
774 void unit_add_to_gc_queue(Unit *u);
775 void unit_add_to_target_deps_queue(Unit *u);
776 void unit_submit_to_stop_when_unneeded_queue(Unit *u);
777 void unit_submit_to_start_when_upheld_queue(Unit *u);
778 void unit_submit_to_stop_when_bound_queue(Unit *u);
779
780 int unit_merge(Unit *u, Unit *other);
781 int unit_merge_by_name(Unit *u, const char *other);
782
783 Unit *unit_follow_merge(Unit *u) _pure_;
784
785 int unit_load_fragment_and_dropin(Unit *u, bool fragment_required);
786 int unit_load(Unit *unit);
787
788 int unit_set_slice(Unit *u, Unit *slice);
789 int unit_set_default_slice(Unit *u);
790
791 const char *unit_description(Unit *u) _pure_;
792 const char *unit_status_string(Unit *u, char **combined);
793
794 bool unit_has_name(const Unit *u, const char *name);
795
796 UnitActiveState unit_active_state(Unit *u);
797 FreezerState unit_freezer_state(Unit *u);
798 int unit_freezer_state_kernel(Unit *u, FreezerState *ret);
799
800 const char* unit_sub_state_to_string(Unit *u);
801
802 bool unit_can_reload(Unit *u) _pure_;
803 bool unit_can_start(Unit *u) _pure_;
804 bool unit_can_stop(Unit *u) _pure_;
805 bool unit_can_isolate(Unit *u) _pure_;
806
807 int unit_start(Unit *u);
808 int unit_stop(Unit *u);
809 int unit_reload(Unit *u);
810
811 int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error);
812 int unit_kill_common(Unit *u, KillWho who, int signo, pid_t main_pid, pid_t control_pid, sd_bus_error *error);
813
814 void unit_notify_cgroup_oom(Unit *u, bool managed_oom);
815
816 typedef enum UnitNotifyFlags {
817 UNIT_NOTIFY_RELOAD_FAILURE = 1 << 0,
818 UNIT_NOTIFY_WILL_AUTO_RESTART = 1 << 1,
819 } UnitNotifyFlags;
820
821 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, UnitNotifyFlags flags);
822
823 int unit_watch_pid(Unit *u, pid_t pid, bool exclusive);
824 void unit_unwatch_pid(Unit *u, pid_t pid);
825 void unit_unwatch_all_pids(Unit *u);
826
827 int unit_enqueue_rewatch_pids(Unit *u);
828 void unit_dequeue_rewatch_pids(Unit *u);
829
830 int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name);
831 int unit_watch_bus_name(Unit *u, const char *name);
832 void unit_unwatch_bus_name(Unit *u, const char *name);
833
834 bool unit_job_is_applicable(Unit *u, JobType j);
835
836 int set_unit_path(const char *p);
837
838 char *unit_dbus_path(Unit *u);
839 char *unit_dbus_path_invocation_id(Unit *u);
840
841 int unit_load_related_unit(Unit *u, const char *type, Unit **_found);
842
843 int unit_add_node_dependency(Unit *u, const char *what, UnitDependency d, UnitDependencyMask mask);
844 int unit_add_blockdev_dependency(Unit *u, const char *what, UnitDependencyMask mask);
845
846 int unit_coldplug(Unit *u);
847 void unit_catchup(Unit *u);
848
849 void unit_status_printf(Unit *u, StatusType status_type, const char *status, const char *format, const char *ident) _printf_(4, 0);
850
851 bool unit_need_daemon_reload(Unit *u);
852
853 void unit_reset_failed(Unit *u);
854
855 Unit *unit_following(Unit *u);
856 int unit_following_set(Unit *u, Set **s);
857
858 const char *unit_slice_name(Unit *u);
859
860 bool unit_stop_pending(Unit *u) _pure_;
861 bool unit_inactive_or_pending(Unit *u) _pure_;
862 bool unit_active_or_pending(Unit *u);
863 bool unit_will_restart_default(Unit *u);
864 bool unit_will_restart(Unit *u);
865
866 int unit_add_default_target_dependency(Unit *u, Unit *target);
867
868 void unit_start_on_failure(Unit *u, const char *dependency_name, UnitDependencyAtom atom, JobMode job_mode);
869 void unit_trigger_notify(Unit *u);
870
871 UnitFileState unit_get_unit_file_state(Unit *u);
872 int unit_get_unit_file_preset(Unit *u);
873
874 Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target);
875 void unit_ref_unset(UnitRef *ref);
876
877 #define UNIT_DEREF(ref) ((ref).target)
878 #define UNIT_ISSET(ref) (!!(ref).target)
879
880 int unit_patch_contexts(Unit *u);
881
882 ExecContext *unit_get_exec_context(const Unit *u) _pure_;
883 KillContext *unit_get_kill_context(Unit *u) _pure_;
884 CGroupContext *unit_get_cgroup_context(Unit *u) _pure_;
885
886 ExecRuntime *unit_get_exec_runtime(Unit *u) _pure_;
887
888 int unit_setup_exec_runtime(Unit *u);
889 int unit_setup_dynamic_creds(Unit *u);
890
891 char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf);
892 char* unit_concat_strv(char **l, UnitWriteFlags flags);
893
894 int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data);
895 int unit_write_settingf(Unit *u, UnitWriteFlags mode, const char *name, const char *format, ...) _printf_(4,5);
896
897 int unit_kill_context(Unit *u, KillContext *c, KillOperation k, pid_t main_pid, pid_t control_pid, bool main_pid_alien);
898
899 int unit_make_transient(Unit *u);
900
901 int unit_require_mounts_for(Unit *u, const char *path, UnitDependencyMask mask);
902
903 bool unit_type_supported(UnitType t);
904
905 bool unit_is_pristine(Unit *u);
906
907 bool unit_is_unneeded(Unit *u);
908 bool unit_is_upheld_by_active(Unit *u, Unit **ret_culprit);
909 bool unit_is_bound_by_inactive(Unit *u, Unit **ret_culprit);
910
911 pid_t unit_control_pid(Unit *u);
912 pid_t unit_main_pid(Unit *u);
913
914 void unit_warn_if_dir_nonempty(Unit *u, const char* where);
915 int unit_fail_if_noncanonical(Unit *u, const char* where);
916
917 int unit_test_start_limit(Unit *u);
918
919 int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid);
920 void unit_unref_uid_gid(Unit *u, bool destroy_now);
921
922 void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid);
923
924 int unit_set_invocation_id(Unit *u, sd_id128_t id);
925 int unit_acquire_invocation_id(Unit *u);
926
927 bool unit_shall_confirm_spawn(Unit *u);
928
929 int unit_set_exec_params(Unit *s, ExecParameters *p);
930
931 int unit_fork_helper_process(Unit *u, const char *name, pid_t *ret);
932 int unit_fork_and_watch_rm_rf(Unit *u, char **paths, pid_t *ret_pid);
933
934 void unit_remove_dependencies(Unit *u, UnitDependencyMask mask);
935
936 void unit_export_state_files(Unit *u);
937 void unit_unlink_state_files(Unit *u);
938
939 int unit_prepare_exec(Unit *u);
940
941 int unit_log_leftover_process_start(pid_t pid, int sig, void *userdata);
942 int unit_log_leftover_process_stop(pid_t pid, int sig, void *userdata);
943 int unit_warn_leftover_processes(Unit *u, cg_kill_log_func_t log_func);
944
945 bool unit_needs_console(Unit *u);
946
947 const char *unit_label_path(const Unit *u);
948
949 int unit_pid_attachable(Unit *unit, pid_t pid, sd_bus_error *error);
950
unit_has_job_type(Unit * u,JobType type)951 static inline bool unit_has_job_type(Unit *u, JobType type) {
952 return u && u->job && u->job->type == type;
953 }
954
unit_log_level_test(const Unit * u,int level)955 static inline bool unit_log_level_test(const Unit *u, int level) {
956 ExecContext *ec = unit_get_exec_context(u);
957 return !ec || ec->log_level_max < 0 || ec->log_level_max >= LOG_PRI(level);
958 }
959
960 /* unit_log_skip is for cases like ExecCondition= where a unit is considered "done"
961 * after some execution, rather than succeeded or failed. */
962 void unit_log_skip(Unit *u, const char *result);
963 void unit_log_success(Unit *u);
964 void unit_log_failure(Unit *u, const char *result);
unit_log_result(Unit * u,bool success,const char * result)965 static inline void unit_log_result(Unit *u, bool success, const char *result) {
966 if (success)
967 unit_log_success(u);
968 else
969 unit_log_failure(u, result);
970 }
971
972 void unit_log_process_exit(Unit *u, const char *kind, const char *command, bool success, int code, int status);
973
974 int unit_exit_status(Unit *u);
975 int unit_success_action_exit_status(Unit *u);
976 int unit_failure_action_exit_status(Unit *u);
977
978 int unit_test_trigger_loaded(Unit *u);
979
980 void unit_destroy_runtime_data(Unit *u, const ExecContext *context);
981 int unit_clean(Unit *u, ExecCleanMask mask);
982 int unit_can_clean(Unit *u, ExecCleanMask *ret_mask);
983
984 bool unit_can_freeze(Unit *u);
985 int unit_freeze(Unit *u);
986 void unit_frozen(Unit *u);
987
988 int unit_thaw(Unit *u);
989 void unit_thawed(Unit *u);
990
991 int unit_freeze_vtable_common(Unit *u);
992 int unit_thaw_vtable_common(Unit *u);
993
994 Condition *unit_find_failed_condition(Unit *u);
995
996 /* Macros which append UNIT= or USER_UNIT= to the message */
997
998 #define log_unit_full_errno_zerook(unit, level, error, ...) \
999 ({ \
1000 const Unit *_u = (unit); \
1001 const int _l = (level); \
1002 (log_get_max_level() < LOG_PRI(_l) || (_u && !unit_log_level_test(_u, _l))) ? -ERRNO_VALUE(error) : \
1003 _u ? log_object_internal(_l, error, PROJECT_FILE, __LINE__, __func__, _u->manager->unit_log_field, _u->id, _u->manager->invocation_log_field, _u->invocation_id_string, ##__VA_ARGS__) : \
1004 log_internal(_l, error, PROJECT_FILE, __LINE__, __func__, ##__VA_ARGS__); \
1005 })
1006
1007 #define log_unit_full_errno(unit, level, error, ...) \
1008 ({ \
1009 int _error = (error); \
1010 ASSERT_NON_ZERO(_error); \
1011 log_unit_full_errno_zerook(unit, level, _error, ##__VA_ARGS__); \
1012 })
1013
1014 #define log_unit_full(unit, level, ...) (void) log_unit_full_errno_zerook(unit, level, 0, __VA_ARGS__)
1015
1016 #define log_unit_debug(unit, ...) log_unit_full(unit, LOG_DEBUG, __VA_ARGS__)
1017 #define log_unit_info(unit, ...) log_unit_full(unit, LOG_INFO, __VA_ARGS__)
1018 #define log_unit_notice(unit, ...) log_unit_full(unit, LOG_NOTICE, __VA_ARGS__)
1019 #define log_unit_warning(unit, ...) log_unit_full(unit, LOG_WARNING, __VA_ARGS__)
1020 #define log_unit_error(unit, ...) log_unit_full(unit, LOG_ERR, __VA_ARGS__)
1021
1022 #define log_unit_debug_errno(unit, error, ...) log_unit_full_errno(unit, LOG_DEBUG, error, __VA_ARGS__)
1023 #define log_unit_info_errno(unit, error, ...) log_unit_full_errno(unit, LOG_INFO, error, __VA_ARGS__)
1024 #define log_unit_notice_errno(unit, error, ...) log_unit_full_errno(unit, LOG_NOTICE, error, __VA_ARGS__)
1025 #define log_unit_warning_errno(unit, error, ...) log_unit_full_errno(unit, LOG_WARNING, error, __VA_ARGS__)
1026 #define log_unit_error_errno(unit, error, ...) log_unit_full_errno(unit, LOG_ERR, error, __VA_ARGS__)
1027
1028 #define log_unit_struct_errno(unit, level, error, ...) \
1029 ({ \
1030 const Unit *_u = (unit); \
1031 const int _l = (level); \
1032 unit_log_level_test(_u, _l) ? \
1033 log_struct_errno(_l, error, __VA_ARGS__, LOG_UNIT_ID(_u)) : \
1034 -ERRNO_VALUE(error); \
1035 })
1036
1037 #define log_unit_struct(unit, level, ...) log_unit_struct_errno(unit, level, 0, __VA_ARGS__)
1038
1039 #define log_unit_struct_iovec_errno(unit, level, error, iovec, n_iovec) \
1040 ({ \
1041 const int _l = (level); \
1042 unit_log_level_test(unit, _l) ? \
1043 log_struct_iovec_errno(_l, error, iovec, n_iovec) : \
1044 -ERRNO_VALUE(error); \
1045 })
1046
1047 #define log_unit_struct_iovec(unit, level, iovec, n_iovec) log_unit_struct_iovec_errno(unit, level, 0, iovec, n_iovec)
1048
1049 /* Like LOG_MESSAGE(), but with the unit name prefixed. */
1050 #define LOG_UNIT_MESSAGE(unit, fmt, ...) LOG_MESSAGE("%s: " fmt, (unit)->id, ##__VA_ARGS__)
1051 #define LOG_UNIT_ID(unit) (unit)->manager->unit_log_format_string, (unit)->id
1052 #define LOG_UNIT_INVOCATION_ID(unit) (unit)->manager->invocation_log_format_string, (unit)->invocation_id_string
1053
1054 const char* collect_mode_to_string(CollectMode m) _const_;
1055 CollectMode collect_mode_from_string(const char *s) _pure_;
1056
1057 typedef struct UnitForEachDependencyData {
1058 /* Stores state for the FOREACH macro below for iterating through all deps that have any of the
1059 * specified dependency atom bits set */
1060 UnitDependencyAtom match_atom;
1061 Hashmap *by_type, *by_unit;
1062 void *current_type;
1063 Iterator by_type_iterator, by_unit_iterator;
1064 Unit **current_unit;
1065 } UnitForEachDependencyData;
1066
1067 /* Iterates through all dependencies that have a specific atom in the dependency type set. This tries to be
1068 * smart: if the atom is unique, we'll directly go to right entry. Otherwise we'll iterate through the
1069 * per-dependency type hashmap and match all dep that have the right atom set. */
1070 #define _UNIT_FOREACH_DEPENDENCY(other, u, ma, data) \
1071 for (UnitForEachDependencyData data = { \
1072 .match_atom = (ma), \
1073 .by_type = (u)->dependencies, \
1074 .by_type_iterator = ITERATOR_FIRST, \
1075 .current_unit = &(other), \
1076 }; \
1077 ({ \
1078 UnitDependency _dt = _UNIT_DEPENDENCY_INVALID; \
1079 bool _found; \
1080 \
1081 if (data.by_type && ITERATOR_IS_FIRST(data.by_type_iterator)) { \
1082 _dt = unit_dependency_from_unique_atom(data.match_atom); \
1083 if (_dt >= 0) { \
1084 data.by_unit = hashmap_get(data.by_type, UNIT_DEPENDENCY_TO_PTR(_dt)); \
1085 data.current_type = UNIT_DEPENDENCY_TO_PTR(_dt); \
1086 data.by_type = NULL; \
1087 _found = !!data.by_unit; \
1088 } \
1089 } \
1090 if (_dt < 0) \
1091 _found = hashmap_iterate(data.by_type, \
1092 &data.by_type_iterator, \
1093 (void**)&(data.by_unit), \
1094 (const void**) &(data.current_type)); \
1095 _found; \
1096 }); ) \
1097 if ((unit_dependency_to_atom(UNIT_DEPENDENCY_FROM_PTR(data.current_type)) & data.match_atom) != 0) \
1098 for (data.by_unit_iterator = ITERATOR_FIRST; \
1099 hashmap_iterate(data.by_unit, \
1100 &data.by_unit_iterator, \
1101 NULL, \
1102 (const void**) data.current_unit); )
1103
1104 /* Note: this matches deps that have *any* of the atoms specified in match_atom set */
1105 #define UNIT_FOREACH_DEPENDENCY(other, u, match_atom) \
1106 _UNIT_FOREACH_DEPENDENCY(other, u, match_atom, UNIQ_T(data, UNIQ))
1107