repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
null |
systemd-main/src/boot/efi/vmm.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#if defined(__i386__) || defined(__x86_64__)
# include <cpuid.h>
#endif
#include "confidential-virt-fundamental.h"
#include "device-path-util.h"
#include "drivers.h"
#include "efi-string.h"
#include "proto/device-path.h"
#include "string-util-fundamental.h"
#include "util.h"
#include "vmm.h"
#define QEMU_KERNEL_LOADER_FS_MEDIA_GUID \
{ 0x1428f772, 0xb64a, 0x441e, { 0xb8, 0xc3, 0x9e, 0xbd, 0xd7, 0xf8, 0x93, 0xc7 } }
#define VMM_BOOT_ORDER_GUID \
{ 0x668f4529, 0x63d0, 0x4bb5, { 0xb6, 0x5d, 0x6f, 0xbb, 0x9d, 0x36, 0xa4, 0x4a } }
/* detect direct boot */
bool is_direct_boot(EFI_HANDLE device) {
EFI_STATUS err;
VENDOR_DEVICE_PATH *dp;
err = BS->HandleProtocol(device, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), (void **) &dp);
if (err != EFI_SUCCESS)
return false;
/* 'qemu -kernel systemd-bootx64.efi' */
if (dp->Header.Type == MEDIA_DEVICE_PATH &&
dp->Header.SubType == MEDIA_VENDOR_DP &&
memcmp(&dp->Guid, MAKE_GUID_PTR(QEMU_KERNEL_LOADER_FS_MEDIA), sizeof(EFI_GUID)) == 0)
return true;
/* loaded from firmware volume (sd-boot added to ovmf) */
if (dp->Header.Type == MEDIA_DEVICE_PATH &&
dp->Header.SubType == MEDIA_PIWG_FW_VOL_DP)
return true;
return false;
}
/*
* Try find ESP when not loaded from ESP
*
* Inspect all filesystems known to the firmware, try find the ESP. In case VMMBootOrderNNNN variables are
* present they are used to inspect the filesystems in the specified order. When nothing was found or the
* variables are not present the function will do one final search pass over all filesystems.
*
* Recent OVMF builds store the qemu boot order (as specified using the bootindex property on the qemu
* command line) in VMMBootOrderNNNN. The variables contain a device path.
*
* Example qemu command line:
* qemu -virtio-scsi-pci,addr=14.0 -device scsi-cd,scsi-id=4,bootindex=1
*
* Resulting variable:
* VMMBootOrder0000 = PciRoot(0x0)/Pci(0x14,0x0)/Scsi(0x4,0x0)
*/
EFI_STATUS vmm_open(EFI_HANDLE *ret_vmm_dev, EFI_FILE **ret_vmm_dir) {
_cleanup_free_ EFI_HANDLE *handles = NULL;
size_t n_handles;
EFI_STATUS err, dp_err;
assert(ret_vmm_dev);
assert(ret_vmm_dir);
/* Make sure all file systems have been initialized. Only do this in VMs as this is slow
* on some real firmwares. */
(void) reconnect_all_drivers();
/* find all file system handles */
err = BS->LocateHandleBuffer(
ByProtocol, MAKE_GUID_PTR(EFI_SIMPLE_FILE_SYSTEM_PROTOCOL), NULL, &n_handles, &handles);
if (err != EFI_SUCCESS)
return err;
for (size_t order = 0;; order++) {
_cleanup_free_ EFI_DEVICE_PATH *dp = NULL;
_cleanup_free_ char16_t *order_str = xasprintf("VMMBootOrder%04zx", order);
dp_err = efivar_get_raw(MAKE_GUID_PTR(VMM_BOOT_ORDER), order_str, (char **) &dp, NULL);
for (size_t i = 0; i < n_handles; i++) {
_cleanup_(file_closep) EFI_FILE *root_dir = NULL, *efi_dir = NULL;
EFI_DEVICE_PATH *fs;
err = BS->HandleProtocol(
handles[i], MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), (void **) &fs);
if (err != EFI_SUCCESS)
return err;
/* check against VMMBootOrderNNNN (if set) */
if (dp_err == EFI_SUCCESS && !device_path_startswith(fs, dp))
continue;
err = open_volume(handles[i], &root_dir);
if (err != EFI_SUCCESS)
continue;
/* simple ESP check */
err = root_dir->Open(root_dir, &efi_dir, (char16_t*) u"\\EFI",
EFI_FILE_MODE_READ,
EFI_FILE_READ_ONLY | EFI_FILE_DIRECTORY);
if (err != EFI_SUCCESS)
continue;
*ret_vmm_dev = handles[i];
*ret_vmm_dir = TAKE_PTR(root_dir);
return EFI_SUCCESS;
}
if (dp_err != EFI_SUCCESS)
return EFI_NOT_FOUND;
}
assert_not_reached();
}
static bool cpuid_in_hypervisor(void) {
#if defined(__i386__) || defined(__x86_64__)
unsigned eax, ebx, ecx, edx;
/* This is a dumbed down version of src/basic/virt.c's detect_vm() that safely works in the UEFI
* environment. */
if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0)
return false;
if (FLAGS_SET(ecx, 0x80000000U))
return true;
#endif
return false;
}
#define SMBIOS_TABLE_GUID \
GUID_DEF(0xeb9d2d31, 0x2d88, 0x11d3, 0x9a, 0x16, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d)
#define SMBIOS3_TABLE_GUID \
GUID_DEF(0xf2fd1544, 0x9794, 0x4a2c, 0x99, 0x2e, 0xe5, 0xbb, 0xcf, 0x20, 0xe3, 0x94)
typedef struct {
uint8_t anchor_string[4];
uint8_t entry_point_structure_checksum;
uint8_t entry_point_length;
uint8_t major_version;
uint8_t minor_version;
uint16_t max_structure_size;
uint8_t entry_point_revision;
uint8_t formatted_area[5];
uint8_t intermediate_anchor_string[5];
uint8_t intermediate_checksum;
uint16_t table_length;
uint32_t table_address;
uint16_t number_of_smbios_structures;
uint8_t smbios_bcd_revision;
} _packed_ SmbiosEntryPoint;
typedef struct {
uint8_t anchor_string[5];
uint8_t entry_point_structure_checksum;
uint8_t entry_point_length;
uint8_t major_version;
uint8_t minor_version;
uint8_t docrev;
uint8_t entry_point_revision;
uint8_t reserved;
uint32_t table_maximum_size;
uint64_t table_address;
} _packed_ Smbios3EntryPoint;
typedef struct {
uint8_t type;
uint8_t length;
uint8_t handle[2];
} _packed_ SmbiosHeader;
typedef struct {
SmbiosHeader header;
uint8_t vendor;
uint8_t bios_version;
uint16_t bios_segment;
uint8_t bios_release_date;
uint8_t bios_size;
uint64_t bios_characteristics;
uint8_t bios_characteristics_ext[2];
} _packed_ SmbiosTableType0;
typedef struct {
SmbiosHeader header;
uint8_t count;
char contents[];
} _packed_ SmbiosTableType11;
static const void *find_smbios_configuration_table(uint64_t *ret_size) {
assert(ret_size);
const Smbios3EntryPoint *entry3 = find_configuration_table(MAKE_GUID_PTR(SMBIOS3_TABLE));
if (entry3 && memcmp(entry3->anchor_string, "_SM3_", 5) == 0 &&
entry3->entry_point_length <= sizeof(*entry3)) {
*ret_size = entry3->table_maximum_size;
return PHYSICAL_ADDRESS_TO_POINTER(entry3->table_address);
}
const SmbiosEntryPoint *entry = find_configuration_table(MAKE_GUID_PTR(SMBIOS_TABLE));
if (entry && memcmp(entry->anchor_string, "_SM_", 4) == 0 &&
entry->entry_point_length <= sizeof(*entry)) {
*ret_size = entry->table_length;
return PHYSICAL_ADDRESS_TO_POINTER(entry->table_address);
}
return NULL;
}
static const SmbiosHeader *get_smbios_table(uint8_t type, uint64_t *ret_size_left) {
uint64_t size = 0;
const uint8_t *p = find_smbios_configuration_table(&size);
if (!p)
return NULL;
for (;;) {
if (size < sizeof(SmbiosHeader))
return NULL;
const SmbiosHeader *header = (const SmbiosHeader *) p;
/* End of table. */
if (header->type == 127)
return NULL;
if (size < header->length)
return NULL;
if (header->type == type) {
if (ret_size_left)
*ret_size_left = size;
return header; /* Yay! */
}
/* Skip over formatted area. */
size -= header->length;
p += header->length;
/* Skip over string table. */
for (;;) {
const uint8_t *e = memchr(p, 0, size);
if (!e)
return NULL;
if (e == p) {/* Double NUL byte means we've reached the end of the string table. */
p++;
size--;
break;
}
size -= e + 1 - p;
p = e + 1;
}
}
return NULL;
}
static bool smbios_in_hypervisor(void) {
/* Look up BIOS Information (Type 0). */
const SmbiosTableType0 *type0 = (const SmbiosTableType0 *) get_smbios_table(0, NULL);
if (!type0 || type0->header.length < sizeof(SmbiosTableType0))
return false;
/* Bit 4 of 2nd BIOS characteristics extension bytes indicates virtualization. */
return FLAGS_SET(type0->bios_characteristics_ext[1], 1 << 4);
}
bool in_hypervisor(void) {
static int cache = -1;
if (cache >= 0)
return cache;
cache = cpuid_in_hypervisor() || smbios_in_hypervisor();
return cache;
}
const char* smbios_find_oem_string(const char *name) {
uint64_t left;
assert(name);
const SmbiosTableType11 *type11 = (const SmbiosTableType11 *) get_smbios_table(11, &left);
if (!type11 || type11->header.length < sizeof(SmbiosTableType11))
return NULL;
assert(left >= type11->header.length);
const char *s = type11->contents;
left -= type11->header.length;
for (const char *p = s; p < s + left; ) {
const char *e = memchr(p, 0, s + left - p);
if (!e || e == p) /* Double NUL byte means we've reached the end of the OEM strings. */
break;
const char *eq = startswith8(p, name);
if (eq && *eq == '=')
return eq + 1;
p = e + 1;
}
return NULL;
}
#if defined(__i386__) || defined(__x86_64__)
static uint32_t cpuid_leaf(uint32_t eax, char ret_sig[static 13], bool swapped) {
/* zero-init as some queries explicitly require subleaf == 0 */
uint32_t sig[3] = {};
if (swapped)
__cpuid_count(eax, 0, eax, sig[0], sig[2], sig[1]);
else
__cpuid_count(eax, 0, eax, sig[0], sig[1], sig[2]);
memcpy(ret_sig, sig, sizeof(sig));
ret_sig[12] = 0; /* \0-terminate the string to make string comparison possible */
return eax;
}
static uint64_t msr(uint32_t index) {
uint64_t val;
#ifdef __x86_64__
uint32_t low, high;
asm volatile ("rdmsr" : "=a"(low), "=d"(high) : "c"(index) : "memory");
val = ((uint64_t)high << 32) | low;
#else
asm volatile ("rdmsr" : "=A"(val) : "c"(index) : "memory");
#endif
return val;
}
static bool detect_hyperv_sev(void) {
uint32_t eax, ebx, ecx, edx, feat;
char sig[13] = {};
feat = cpuid_leaf(CPUID_HYPERV_VENDOR_AND_MAX_FUNCTIONS, sig, false);
if (feat < CPUID_HYPERV_MIN || feat > CPUID_HYPERV_MAX)
return false;
if (memcmp(sig, CPUID_SIG_HYPERV, sizeof(sig)) != 0)
return false;
__cpuid(CPUID_HYPERV_FEATURES, eax, ebx, ecx, edx);
if (ebx & CPUID_HYPERV_ISOLATION && !(ebx & CPUID_HYPERV_CPU_MANAGEMENT)) {
__cpuid(CPUID_HYPERV_ISOLATION_CONFIG, eax, ebx, ecx, edx);
if ((ebx & CPUID_HYPERV_ISOLATION_TYPE_MASK) == CPUID_HYPERV_ISOLATION_TYPE_SNP)
return true;
}
return false;
}
static bool detect_sev(void) {
uint32_t eax, ebx, ecx, edx;
uint64_t msrval;
__cpuid(CPUID_GET_HIGHEST_FUNCTION, eax, ebx, ecx, edx);
if (eax < CPUID_AMD_GET_ENCRYPTED_MEMORY_CAPABILITIES)
return false;
__cpuid(CPUID_AMD_GET_ENCRYPTED_MEMORY_CAPABILITIES, eax, ebx, ecx, edx);
/* bit 1 == CPU supports SEV feature
*
* Note, Azure blocks this CPUID leaf from its SEV-SNP
* guests, so we must fallback to trying some HyperV
* specific CPUID checks.
*/
if (!(eax & EAX_SEV))
return detect_hyperv_sev();
msrval = msr(MSR_AMD64_SEV);
if (msrval & (MSR_SEV_SNP | MSR_SEV_ES | MSR_SEV))
return true;
return false;
}
static bool detect_tdx(void) {
uint32_t eax, ebx, ecx, edx;
char sig[13] = {};
__cpuid(CPUID_GET_HIGHEST_FUNCTION, eax, ebx, ecx, edx);
if (eax < CPUID_INTEL_TDX_ENUMERATION)
return false;
cpuid_leaf(CPUID_INTEL_TDX_ENUMERATION, sig, true);
if (memcmp(sig, CPUID_SIG_INTEL_TDX, sizeof(sig)) == 0)
return true;
return false;
}
#endif /* ! __i386__ && ! __x86_64__ */
bool is_confidential_vm(void) {
#if defined(__i386__) || defined(__x86_64__)
char sig[13] = {};
if (!cpuid_in_hypervisor())
return false;
cpuid_leaf(0, sig, true);
if (memcmp(sig, CPUID_SIG_AMD, sizeof(sig)) == 0)
return detect_sev();
if (memcmp(sig, CPUID_SIG_INTEL, sizeof(sig)) == 0)
return detect_tdx();
#endif /* ! __i386__ && ! __x86_64__ */
return false;
}
| 14,078 | 31.971897 | 112 |
c
|
null |
systemd-main/src/boot/efi/proto/block-io.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_BLOCK_IO_PROTOCOL_GUID \
GUID_DEF(0x0964e5b21, 0x6459, 0x11d2, 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b)
typedef struct EFI_BLOCK_IO_PROTOCOL EFI_BLOCK_IO_PROTOCOL;
struct EFI_BLOCK_IO_PROTOCOL {
uint64_t Revision;
struct {
uint32_t MediaId;
bool RemovableMedia;
bool MediaPresent;
bool LogicalPartition;
bool ReadOnly;
bool WriteCaching;
uint32_t BlockSize;
uint32_t IoAlign;
EFI_LBA LastBlock;
EFI_LBA LowestAlignedLba;
uint32_t LogicalBlocksPerPhysicalBlock;
uint32_t OptimalTransferLengthGranularity;
} *Media;
EFI_STATUS (EFIAPI *Reset)(
EFI_BLOCK_IO_PROTOCOL *This,
bool ExtendedVerification);
EFI_STATUS (EFIAPI *ReadBlocks)(
EFI_BLOCK_IO_PROTOCOL *This,
uint32_t MediaId,
EFI_LBA LBA,
size_t BufferSize,
void *Buffer);
EFI_STATUS (EFIAPI *WriteBlocks)(
EFI_BLOCK_IO_PROTOCOL *This,
uint32_t MediaId,
EFI_LBA LBA,
size_t BufferSize,
void *Buffer);
EFI_STATUS (EFIAPI *FlushBlocks)(EFI_BLOCK_IO_PROTOCOL *This);
};
| 1,566 | 34.613636 | 93 |
h
|
null |
systemd-main/src/boot/efi/proto/console-control.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_CONSOLE_CONTROL_PROTOCOL_GUID \
GUID_DEF(0xf42f7782, 0x12e, 0x4c12, 0x99, 0x56, 0x49, 0xf9, 0x43, 0x4, 0xf7, 0x21)
typedef enum {
EfiConsoleControlScreenText,
EfiConsoleControlScreenGraphics,
EfiConsoleControlScreenMaxValue,
} EFI_CONSOLE_CONTROL_SCREEN_MODE;
typedef struct EFI_CONSOLE_CONTROL_PROTOCOL EFI_CONSOLE_CONTROL_PROTOCOL;
struct EFI_CONSOLE_CONTROL_PROTOCOL {
EFI_STATUS (EFIAPI *GetMode)(
EFI_CONSOLE_CONTROL_PROTOCOL *This,
EFI_CONSOLE_CONTROL_SCREEN_MODE *Mode,
bool *UgaExists,
bool *StdInLocked);
EFI_STATUS (EFIAPI *SetMode)(
EFI_CONSOLE_CONTROL_PROTOCOL *This,
EFI_CONSOLE_CONTROL_SCREEN_MODE Mode);
EFI_STATUS(EFIAPI *LockStdIn)(
EFI_CONSOLE_CONTROL_PROTOCOL *This,
char16_t *Password);
};
| 1,053 | 35.344828 | 90 |
h
|
null |
systemd-main/src/boot/efi/proto/device-path.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_DEVICE_PATH_PROTOCOL_GUID \
GUID_DEF(0x09576e91, 0x6d3f, 0x11d2, 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b)
#define EFI_DEVICE_PATH_TO_TEXT_PROTOCOL_GUID \
GUID_DEF(0x8b843e20, 0x8132, 0x4852, 0x90, 0xcc, 0x55, 0x1a, 0x4e, 0x4a, 0x7f, 0x1c)
#define EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL_GUID \
GUID_DEF(0x05c99a21, 0xc70f, 0x4ad2, 0x8a, 0x5f, 0x35, 0xdf, 0x33, 0x43, 0xf5, 0x1e)
/* Device path types. */
enum {
HARDWARE_DEVICE_PATH = 0x01,
ACPI_DEVICE_PATH = 0x02,
MESSAGING_DEVICE_PATH = 0x03,
MEDIA_DEVICE_PATH = 0x04,
BBS_DEVICE_PATH = 0x05,
END_DEVICE_PATH_TYPE = 0x7f,
};
/* Device path sub-types. */
enum {
END_INSTANCE_DEVICE_PATH_SUBTYPE = 0x01,
END_ENTIRE_DEVICE_PATH_SUBTYPE = 0xff,
MEDIA_HARDDRIVE_DP = 0x01,
MEDIA_VENDOR_DP = 0x03,
MEDIA_FILEPATH_DP = 0x04,
MEDIA_PIWG_FW_FILE_DP = 0x06,
MEDIA_PIWG_FW_VOL_DP = 0x07,
};
struct _packed_ EFI_DEVICE_PATH_PROTOCOL {
uint8_t Type;
uint8_t SubType;
uint16_t Length;
};
typedef struct {
EFI_DEVICE_PATH Header;
EFI_GUID Guid;
} _packed_ VENDOR_DEVICE_PATH;
#define MBR_TYPE_PCAT 0x01U
#define MBR_TYPE_EFI_PARTITION_TABLE_HEADER 0x02U
#define NO_DISK_SIGNATURE 0x00U
#define SIGNATURE_TYPE_MBR 0x01U
#define SIGNATURE_TYPE_GUID 0x02U
typedef struct {
EFI_DEVICE_PATH Header;
uint32_t PartitionNumber;
uint64_t PartitionStart;
uint64_t PartitionSize;
union {
uint8_t Signature[16];
EFI_GUID SignatureGuid;
};
uint8_t MBRType;
uint8_t SignatureType;
} _packed_ HARDDRIVE_DEVICE_PATH;
typedef struct {
EFI_DEVICE_PATH Header;
char16_t PathName[];
} _packed_ FILEPATH_DEVICE_PATH;
typedef struct {
char16_t* (EFIAPI *ConvertDeviceNodeToText)(
const EFI_DEVICE_PATH *DeviceNode,
bool DisplayOnly,
bool AllowShortcuts);
char16_t* (EFIAPI *ConvertDevicePathToText)(
const EFI_DEVICE_PATH *DevicePath,
bool DisplayOnly,
bool AllowShortcuts);
} EFI_DEVICE_PATH_TO_TEXT_PROTOCOL;
typedef struct {
EFI_DEVICE_PATH* (EFIAPI *ConvertTextToDevicNode)(
const char16_t *TextDeviceNode);
EFI_DEVICE_PATH* (EFIAPI *ConvertTextToDevicPath)(
const char16_t *ConvertTextToDevicPath);
} EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL;
| 2,784 | 31.011494 | 92 |
h
|
null |
systemd-main/src/boot/efi/proto/dt-fixup.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_DTB_TABLE_GUID \
GUID_DEF(0xb1b621d5, 0xf19c, 0x41a5, 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0)
#define EFI_DT_FIXUP_PROTOCOL_GUID \
GUID_DEF(0xe617d64c, 0xfe08, 0x46da, 0xf4, 0xdc, 0xbb, 0xd5, 0x87, 0x0c, 0x73, 0x00)
#define EFI_DT_FIXUP_PROTOCOL_REVISION 0x00010000
/* Add nodes and update properties */
#define EFI_DT_APPLY_FIXUPS 0x00000001
/*
* Reserve memory according to the /reserved-memory node
* and the memory reservation block
*/
#define EFI_DT_RESERVE_MEMORY 0x00000002
typedef struct EFI_DT_FIXUP_PROTOCOL EFI_DT_FIXUP_PROTOCOL;
struct EFI_DT_FIXUP_PROTOCOL {
uint64_t Revision;
EFI_STATUS (EFIAPI *Fixup)(
EFI_DT_FIXUP_PROTOCOL *This,
void *Fdt,
size_t *BufferSize,
uint32_t Flags);
};
| 903 | 28.16129 | 92 |
h
|
null |
systemd-main/src/boot/efi/proto/file-io.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID \
GUID_DEF(0x0964e5b22, 0x6459, 0x11d2, 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b)
#define EFI_FILE_INFO_ID \
GUID_DEF(0x009576e92, 0x6d3f, 0x11d2, 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b)
#define EFI_FILE_MODE_READ 0x0000000000000001U
#define EFI_FILE_MODE_WRITE 0x0000000000000002U
#define EFI_FILE_MODE_CREATE 0x8000000000000000U
#define EFI_FILE_READ_ONLY 0x01U
#define EFI_FILE_HIDDEN 0x02U
#define EFI_FILE_SYSTEM 0x04U
#define EFI_FILE_RESERVED 0x08U
#define EFI_FILE_DIRECTORY 0x10U
#define EFI_FILE_ARCHIVE 0x20U
#define EFI_FILE_VALID_ATTR 0x37U
typedef struct {
uint64_t Size;
uint64_t FileSize;
uint64_t PhysicalSize;
EFI_TIME CreateTime;
EFI_TIME LastAccessTime;
EFI_TIME ModificationTime;
uint64_t Attribute;
char16_t FileName[];
} EFI_FILE_INFO;
typedef struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL EFI_SIMPLE_FILE_SYSTEM_PROTOCOL;
struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL {
uint64_t Revision;
EFI_STATUS (EFIAPI *OpenVolume)(
EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *This,
EFI_FILE **Root);
};
struct EFI_FILE_PROTOCOL {
uint64_t Revision;
EFI_STATUS (EFIAPI *Open)(
EFI_FILE *This,
EFI_FILE **NewHandle,
char16_t *FileName,
uint64_t OpenMode,
uint64_t Attributes);
EFI_STATUS (EFIAPI *Close)(EFI_FILE *This);
EFI_STATUS (EFIAPI *Delete)(EFI_FILE *This);
EFI_STATUS (EFIAPI *Read)(
EFI_FILE *This,
size_t *BufferSize,
void *Buffer);
EFI_STATUS (EFIAPI *Write)(
EFI_FILE *This,
size_t *BufferSize,
void *Buffer);
EFI_STATUS (EFIAPI *GetPosition)(EFI_FILE *This, uint64_t *Position);
EFI_STATUS (EFIAPI *SetPosition)(EFI_FILE *This, uint64_t Position);
EFI_STATUS (EFIAPI *GetInfo)(
EFI_FILE *This,
EFI_GUID *InformationType,
size_t *BufferSize,
void *Buffer);
EFI_STATUS (EFIAPI *SetInfo)(
EFI_FILE *This,
EFI_GUID *InformationType,
size_t BufferSize,
void *Buffer);
EFI_STATUS (EFIAPI *Flush)(EFI_FILE *This);
void *OpenEx;
void *ReadEx;
void *WriteEx;
void *FlushEx;
};
| 2,752 | 34.294872 | 93 |
h
|
null |
systemd-main/src/boot/efi/proto/graphics-output.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID \
GUID_DEF(0x9042a9de, 0x23dc, 0x4a38, 0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a)
typedef enum {
PixelRedGreenBlueReserved8BitPerColor,
PixelBlueGreenRedReserved8BitPerColor,
PixelBitMask,
PixelBltOnly,
PixelFormatMax,
} EFI_GRAPHICS_PIXEL_FORMAT;
typedef enum {
EfiBltVideoFill,
EfiBltVideoToBltBuffer,
EfiBltBufferToVideo,
EfiBltVideoToVideo,
EfiGraphicsOutputBltOperationMax,
} EFI_GRAPHICS_OUTPUT_BLT_OPERATION;
typedef struct {
uint32_t RedMask;
uint32_t GreenMask;
uint32_t BlueMask;
uint32_t ReservedMask;
} EFI_PIXEL_BITMASK;
typedef struct {
uint8_t Blue;
uint8_t Green;
uint8_t Red;
uint8_t Reserved;
} EFI_GRAPHICS_OUTPUT_BLT_PIXEL;
typedef struct {
uint32_t Version;
uint32_t HorizontalResolution;
uint32_t VerticalResolution;
EFI_GRAPHICS_PIXEL_FORMAT PixelFormat;
EFI_PIXEL_BITMASK PixelInformation;
uint32_t PixelsPerScanLine;
} EFI_GRAPHICS_OUTPUT_MODE_INFORMATION;
typedef struct EFI_GRAPHICS_OUTPUT_PROTOCOL EFI_GRAPHICS_OUTPUT_PROTOCOL;
struct EFI_GRAPHICS_OUTPUT_PROTOCOL {
EFI_STATUS (EFIAPI *QueryMode)(
EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
uint32_t ModeNumber,
size_t *SizeOfInfo,
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info);
EFI_STATUS(EFIAPI *SetMode)(
EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
uint32_t ModeNumber);
EFI_STATUS (EFIAPI *Blt)(
EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer,
EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
size_t SourceX,
size_t SourceY,
size_t DestinationX,
size_t DestinationY,
size_t Width,
size_t Height,
size_t Delta);
struct {
uint32_t MaxMode;
uint32_t Mode;
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;
size_t SizeOfInfo;
EFI_PHYSICAL_ADDRESS FrameBufferBase;
size_t FrameBufferSize;
} *Mode;
};
| 2,540 | 31.164557 | 92 |
h
|
null |
systemd-main/src/boot/efi/proto/load-file.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_LOAD_FILE_PROTOCOL_GUID \
GUID_DEF(0x56EC3091, 0x954C, 0x11d2, 0x8e, 0x3f, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b)
#define EFI_LOAD_FILE2_PROTOCOL_GUID \
GUID_DEF(0x4006c0c1, 0xfcb3, 0x403e, 0x99, 0x6d, 0x4a, 0x6c, 0x87, 0x24, 0xe0, 0x6d)
typedef struct EFI_LOAD_FILE_PROTOCOL EFI_LOAD_FILE_PROTOCOL;
typedef EFI_LOAD_FILE_PROTOCOL EFI_LOAD_FILE2_PROTOCOL;
struct EFI_LOAD_FILE_PROTOCOL {
EFI_STATUS (EFIAPI *LoadFile)(
EFI_LOAD_FILE_PROTOCOL *This,
EFI_DEVICE_PATH *FilePath,
bool BootPolicy,
size_t *BufferSize,
void *Buffer);
};
| 767 | 33.909091 | 92 |
h
|
null |
systemd-main/src/boot/efi/proto/loaded-image.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_LOADED_IMAGE_PROTOCOL_GUID \
GUID_DEF(0x5B1B31A1, 0x9562, 0x11d2, 0x8E, 0x3F, 0x00, 0xA0, 0xC9, 0x69, 0x72, 0x3B)
#define EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID \
GUID_DEF(0xbc62157e, 0x3e33, 0x4fec, 0x99, 0x20, 0x2d, 0x3b, 0x36, 0xd7, 0x50, 0xdf)
typedef EFI_STATUS (EFIAPI *EFI_IMAGE_ENTRY_POINT)(
EFI_HANDLE ImageHandle,
EFI_SYSTEM_TABLE *SystemTable);
typedef struct {
uint32_t Revision;
EFI_HANDLE ParentHandle;
EFI_SYSTEM_TABLE *SystemTable;
EFI_HANDLE DeviceHandle;
EFI_DEVICE_PATH *FilePath;
void *Reserved;
uint32_t LoadOptionsSize;
void *LoadOptions;
void *ImageBase;
uint64_t ImageSize;
EFI_MEMORY_TYPE ImageCodeType;
EFI_MEMORY_TYPE ImageDataType;
EFI_STATUS (EFIAPI *Unload)(EFI_HANDLE ImageHandle);
} EFI_LOADED_IMAGE_PROTOCOL;
| 977 | 31.6 | 92 |
h
|
null |
systemd-main/src/boot/efi/proto/rng.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_RNG_PROTOCOL_GUID \
GUID_DEF(0x3152bca5, 0xeade, 0x433d, 0x86, 0x2e, 0xc0, 0x1c, 0xdc, 0x29, 0x1f, 0x44)
typedef struct EFI_RNG_PROTOCOL EFI_RNG_PROTOCOL;
struct EFI_RNG_PROTOCOL {
EFI_STATUS (EFIAPI *GetInfo)(
EFI_RNG_PROTOCOL *This,
size_t *RNGAlgorithmListSize,
EFI_GUID *RNGAlgorithmList);
EFI_STATUS (EFIAPI *GetRNG)(
EFI_RNG_PROTOCOL *This,
EFI_GUID *RNGAlgorithm,
size_t RNGValueLength,
uint8_t *RNGValue);
};
| 703 | 32.52381 | 92 |
h
|
null |
systemd-main/src/boot/efi/proto/security-arch.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_SECURITY_ARCH_PROTOCOL_GUID \
GUID_DEF(0xA46423E3, 0x4617, 0x49f1, 0xB9, 0xFF, 0xD1, 0xBF, 0xA9, 0x11, 0x58, 0x39)
#define EFI_SECURITY2_ARCH_PROTOCOL_GUID \
GUID_DEF(0x94ab2f58, 0x1438, 0x4ef1, 0x91, 0x52, 0x18, 0x94, 0x1a, 0x3a, 0x0e, 0x68)
typedef struct EFI_SECURITY_ARCH_PROTOCOL EFI_SECURITY_ARCH_PROTOCOL;
typedef struct EFI_SECURITY2_ARCH_PROTOCOL EFI_SECURITY2_ARCH_PROTOCOL;
typedef EFI_STATUS (EFIAPI *EFI_SECURITY_FILE_AUTHENTICATION_STATE)(
const EFI_SECURITY_ARCH_PROTOCOL *This,
uint32_t AuthenticationStatus,
const EFI_DEVICE_PATH *File);
typedef EFI_STATUS (EFIAPI *EFI_SECURITY2_FILE_AUTHENTICATION)(
const EFI_SECURITY2_ARCH_PROTOCOL *This,
const EFI_DEVICE_PATH *DevicePath,
void *FileBuffer,
size_t FileSize,
bool BootPolicy);
struct EFI_SECURITY_ARCH_PROTOCOL {
EFI_SECURITY_FILE_AUTHENTICATION_STATE FileAuthenticationState;
};
struct EFI_SECURITY2_ARCH_PROTOCOL {
EFI_SECURITY2_FILE_AUTHENTICATION FileAuthentication;
};
| 1,203 | 35.484848 | 92 |
h
|
null |
systemd-main/src/boot/efi/proto/simple-text-io.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_SIMPLE_TEXT_INPUT_PROTOCOL_GUID \
GUID_DEF(0x387477c1, 0x69c7, 0x11d2, 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b)
#define EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL_GUID \
GUID_DEF(0xdd9e7534, 0x7762, 0x4698, 0x8c, 0x14, 0xf5, 0x85, 0x17, 0xa6, 0x25, 0xaa)
#define EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL_GUID \
GUID_DEF(0x387477c2, 0x69c7, 0x11d2, 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b)
#define EFI_SHIFT_STATE_VALID 0x80000000U
#define EFI_RIGHT_SHIFT_PRESSED 0x00000001U
#define EFI_LEFT_SHIFT_PRESSED 0x00000002U
#define EFI_RIGHT_CONTROL_PRESSED 0x00000004U
#define EFI_LEFT_CONTROL_PRESSED 0x00000008U
#define EFI_RIGHT_ALT_PRESSED 0x00000010U
#define EFI_LEFT_ALT_PRESSED 0x00000020U
#define EFI_RIGHT_LOGO_PRESSED 0x00000040U
#define EFI_LEFT_LOGO_PRESSED 0x00000080U
#define EFI_MENU_KEY_PRESSED 0x00000100U
#define EFI_SYS_REQ_PRESSED 0x00000200U
#define EFI_TOGGLE_STATE_VALID 0x80U
#define EFI_KEY_STATE_EXPOSED 0x40U
#define EFI_SCROLL_LOCK_ACTIVE 0x01U
#define EFI_NUM_LOCK_ACTIVE 0x02U
#define EFI_CAPS_LOCK_ACTIVE 0x04U
enum {
EFI_BLACK = 0x00,
EFI_BLUE = 0x01,
EFI_GREEN = 0x02,
EFI_CYAN = EFI_BLUE | EFI_GREEN,
EFI_RED = 0x04,
EFI_MAGENTA = EFI_BLUE | EFI_RED,
EFI_BROWN = EFI_GREEN | EFI_RED,
EFI_LIGHTGRAY = EFI_BLUE | EFI_GREEN | EFI_RED,
EFI_BRIGHT = 0x08,
EFI_DARKGRAY = EFI_BLACK | EFI_BRIGHT,
EFI_LIGHTBLUE = EFI_BLUE | EFI_BRIGHT,
EFI_LIGHTGREEN = EFI_GREEN | EFI_BRIGHT,
EFI_LIGHTCYAN = EFI_CYAN | EFI_BRIGHT,
EFI_LIGHTRED = EFI_RED | EFI_BRIGHT,
EFI_LIGHTMAGENTA = EFI_MAGENTA | EFI_BRIGHT,
EFI_YELLOW = EFI_BROWN | EFI_BRIGHT,
EFI_WHITE = EFI_BLUE | EFI_GREEN | EFI_RED | EFI_BRIGHT,
};
#define EFI_TEXT_ATTR(fg, bg) ((fg) | ((bg) << 4))
#define EFI_TEXT_ATTR_SWAP(c) EFI_TEXT_ATTR(((c) & 0xF0U) >> 4, (c) & 0xFU)
enum {
SCAN_NULL = 0x000,
SCAN_UP = 0x001,
SCAN_DOWN = 0x002,
SCAN_RIGHT = 0x003,
SCAN_LEFT = 0x004,
SCAN_HOME = 0x005,
SCAN_END = 0x006,
SCAN_INSERT = 0x007,
SCAN_DELETE = 0x008,
SCAN_PAGE_UP = 0x009,
SCAN_PAGE_DOWN = 0x00A,
SCAN_F1 = 0x00B,
SCAN_F2 = 0x00C,
SCAN_F3 = 0x00D,
SCAN_F4 = 0x00E,
SCAN_F5 = 0x00F,
SCAN_F6 = 0x010,
SCAN_F7 = 0x011,
SCAN_F8 = 0x012,
SCAN_F9 = 0x013,
SCAN_F10 = 0x014,
SCAN_F11 = 0x015,
SCAN_F12 = 0x016,
SCAN_ESC = 0x017,
SCAN_PAUSE = 0x048,
SCAN_F13 = 0x068,
SCAN_F14 = 0x069,
SCAN_F15 = 0x06A,
SCAN_F16 = 0x06B,
SCAN_F17 = 0x06C,
SCAN_F18 = 0x06D,
SCAN_F19 = 0x06E,
SCAN_F20 = 0x06F,
SCAN_F21 = 0x070,
SCAN_F22 = 0x071,
SCAN_F23 = 0x072,
SCAN_F24 = 0x073,
SCAN_MUTE = 0x07F,
SCAN_VOLUME_UP = 0x080,
SCAN_VOLUME_DOWN = 0x081,
SCAN_BRIGHTNESS_UP = 0x100,
SCAN_BRIGHTNESS_DOWN = 0x101,
SCAN_SUSPEND = 0x102,
SCAN_HIBERNATE = 0x103,
SCAN_TOGGLE_DISPLAY = 0x104,
SCAN_RECOVERY = 0x105,
SCAN_EJECT = 0x106,
};
typedef struct {
uint16_t ScanCode;
char16_t UnicodeChar;
} EFI_INPUT_KEY;
typedef struct {
uint32_t KeyShiftState;
uint8_t KeyToggleState;
} EFI_KEY_STATE;
typedef struct {
EFI_INPUT_KEY Key;
EFI_KEY_STATE KeyState;
} EFI_KEY_DATA;
struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL {
EFI_STATUS (EFIAPI *Reset)(
EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This,
bool ExtendedVerification);
EFI_STATUS (EFIAPI *ReadKeyStroke)(
EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This,
EFI_INPUT_KEY *Key);
EFI_EVENT WaitForKey;
};
typedef struct EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL;
struct EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL {
EFI_STATUS (EFIAPI *Reset)(
EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
bool ExtendedVerification);
EFI_STATUS (EFIAPI *ReadKeyStrokeEx)(
EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
EFI_KEY_DATA *KeyData);
EFI_EVENT WaitForKeyEx;
void *SetState;
void *RegisterKeyNotify;
void *UnregisterKeyNotify;
};
typedef struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL;
struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL {
EFI_STATUS (EFIAPI *Reset)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
bool ExtendedVerification);
EFI_STATUS (EFIAPI *OutputString)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
char16_t *String);
EFI_STATUS (EFIAPI *TestString)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
char16_t *String);
EFI_STATUS (EFIAPI *QueryMode)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
size_t ModeNumber,
size_t *Columns,
size_t *Rows);
EFI_STATUS (EFIAPI *SetMode)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
size_t ModeNumber);
EFI_STATUS (EFIAPI *SetAttribute)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
size_t Attribute);
EFI_STATUS (EFIAPI *ClearScreen)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This);
EFI_STATUS (EFIAPI *SetCursorPosition)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
size_t Column,
size_t Row);
EFI_STATUS (EFIAPI *EnableCursor)(
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
bool Visible);
struct {
int32_t MaxMode;
int32_t Mode;
int32_t Attribute;
int32_t CursorColumn;
int32_t CursorRow;
bool CursorVisible;
} *Mode;
};
| 6,923 | 36.836066 | 92 |
h
|
null |
systemd-main/src/boot/efi/proto/tcg.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "efi.h"
#define EFI_TCG_PROTOCOL_GUID \
GUID_DEF(0xf541796d, 0xa62e, 0x4954, 0xa7, 0x75, 0x95, 0x84, 0xf6, 0x1b, 0x9c, 0xdd)
#define EFI_TCG2_PROTOCOL_GUID \
GUID_DEF(0x607f766c, 0x7455, 0x42be, 0x93, 0x0b, 0xe4, 0xd7, 0x6d, 0xb2, 0x72, 0x0f)
#define TCG_ALG_SHA 0x4
#define EFI_TCG2_EVENT_HEADER_VERSION 1
#define EV_IPL 13
typedef struct {
uint8_t Major;
uint8_t Minor;
uint8_t RevMajor;
uint8_t RevMinor;
} TCG_VERSION;
typedef struct {
uint8_t Major;
uint8_t Minor;
} EFI_TCG2_VERSION;
typedef struct {
uint8_t Size;
TCG_VERSION StructureVersion;
TCG_VERSION ProtocolSpecVersion;
uint8_t HashAlgorithmBitmap;
bool TPMPresentFlag;
bool TPMDeactivatedFlag;
} EFI_TCG_BOOT_SERVICE_CAPABILITY;
typedef struct {
uint8_t Size;
EFI_TCG2_VERSION StructureVersion;
EFI_TCG2_VERSION ProtocolVersion;
uint32_t HashAlgorithmBitmap;
uint32_t SupportedEventLogs;
bool TPMPresentFlag;
uint16_t MaxCommandSize;
uint16_t MaxResponseSize;
uint32_t ManufacturerID;
uint32_t NumberOfPCRBanks;
uint32_t ActivePcrBanks;
} EFI_TCG2_BOOT_SERVICE_CAPABILITY;
typedef struct {
uint32_t PCRIndex;
uint32_t EventType;
struct {
uint8_t Digest[20];
} Digest;
uint32_t EventSize;
uint8_t Event[];
} _packed_ TCG_PCR_EVENT;
typedef struct {
uint32_t HeaderSize;
uint16_t HeaderVersion;
uint32_t PCRIndex;
uint32_t EventType;
} _packed_ EFI_TCG2_EVENT_HEADER;
typedef struct {
uint32_t Size;
EFI_TCG2_EVENT_HEADER Header;
uint8_t Event[];
} _packed_ EFI_TCG2_EVENT;
typedef struct EFI_TCG_PROTOCOL EFI_TCG_PROTOCOL;
struct EFI_TCG_PROTOCOL {
EFI_STATUS (EFIAPI *StatusCheck)(
EFI_TCG_PROTOCOL *This,
EFI_TCG_BOOT_SERVICE_CAPABILITY *ProtocolCapability,
uint32_t *TCGFeatureFlags,
EFI_PHYSICAL_ADDRESS *EventLogLocation,
EFI_PHYSICAL_ADDRESS *EventLogLastEntry);
void *HashAll;
void *LogEvent;
void *PassThroughToTpm;
EFI_STATUS (EFIAPI *HashLogExtendEvent)(
EFI_TCG_PROTOCOL *This,
EFI_PHYSICAL_ADDRESS HashData,
uint64_t HashDataLen,
uint32_t AlgorithmId,
TCG_PCR_EVENT *TCGLogData,
uint32_t *EventNumber,
EFI_PHYSICAL_ADDRESS *EventLogLastEntry);
};
typedef struct EFI_TCG2_PROTOCOL EFI_TCG2_PROTOCOL;
struct EFI_TCG2_PROTOCOL {
EFI_STATUS (EFIAPI *GetCapability)(
EFI_TCG2_PROTOCOL *This,
EFI_TCG2_BOOT_SERVICE_CAPABILITY *ProtocolCapability);
void *GetEventLog;
EFI_STATUS (EFIAPI *HashLogExtendEvent)(
EFI_TCG2_PROTOCOL *This,
uint64_t Flags,
EFI_PHYSICAL_ADDRESS DataToHash,
uint64_t DataToHashLen,
EFI_TCG2_EVENT *EfiTcgEvent);
void *SubmitCommand;
void *GetActivePcrBanks;
void *SetActivePcrBanks;
void *GetResultOfSetActivePcrBanks;
};
| 3,471 | 30.279279 | 92 |
h
|
null |
systemd-main/src/cgls/cgls.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <unistd.h>
#include "sd-bus.h"
#include "alloc-util.h"
#include "build.h"
#include "bus-util.h"
#include "cgroup-show.h"
#include "cgroup-util.h"
#include "fileio.h"
#include "log.h"
#include "main-func.h"
#include "output-mode.h"
#include "pager.h"
#include "parse-util.h"
#include "path-util.h"
#include "pretty-print.h"
#include "strv.h"
#include "unit-name.h"
static PagerFlags arg_pager_flags = 0;
static OutputFlags arg_output_flags = 0;
static enum {
SHOW_UNIT_NONE,
SHOW_UNIT_SYSTEM,
SHOW_UNIT_USER,
} arg_show_unit = SHOW_UNIT_NONE;
static char **arg_names = NULL;
static int arg_full = -1;
static const char* arg_machine = NULL;
STATIC_DESTRUCTOR_REGISTER(arg_names, freep); /* don't free the strings */
static int help(void) {
_cleanup_free_ char *link = NULL;
int r;
r = terminal_urlify_man("systemd-cgls", "1", &link);
if (r < 0)
return log_oom();
printf("%s [OPTIONS...] [CGROUP...]\n\n"
"Recursively show control group contents.\n\n"
" -h --help Show this help\n"
" --version Show package version\n"
" --no-pager Do not pipe output into a pager\n"
" -a --all Show all groups, including empty\n"
" -u --unit Show the subtrees of specified system units\n"
" --user-unit Show the subtrees of specified user units\n"
" -x --xattr=BOOL Show cgroup extended attributes\n"
" -c --cgroup-id=BOOL Show cgroup ID\n"
" -l --full Do not ellipsize output\n"
" -k Include kernel threads in output\n"
" -M --machine=NAME Show container NAME\n"
"\nSee the %s for details.\n",
program_invocation_short_name,
link);
return 0;
}
static int parse_argv(int argc, char *argv[]) {
enum {
ARG_NO_PAGER = 0x100,
ARG_VERSION,
ARG_USER_UNIT,
};
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, ARG_VERSION },
{ "no-pager", no_argument, NULL, ARG_NO_PAGER },
{ "all", no_argument, NULL, 'a' },
{ "full", no_argument, NULL, 'l' },
{ "machine", required_argument, NULL, 'M' },
{ "unit", optional_argument, NULL, 'u' },
{ "user-unit", optional_argument, NULL, ARG_USER_UNIT },
{ "xattr", required_argument, NULL, 'x' },
{ "cgroup-id", required_argument, NULL, 'c' },
{}
};
int c, r;
assert(argc >= 1);
assert(argv);
/* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
* that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
optind = 0;
while ((c = getopt_long(argc, argv, "-hkalM:u::xc", options, NULL)) >= 0)
switch (c) {
case 'h':
return help();
case ARG_VERSION:
return version();
case ARG_NO_PAGER:
arg_pager_flags |= PAGER_DISABLE;
break;
case 'a':
arg_output_flags |= OUTPUT_SHOW_ALL;
break;
case 'u':
arg_show_unit = SHOW_UNIT_SYSTEM;
if (strv_push(&arg_names, optarg) < 0) /* push optarg if not empty */
return log_oom();
break;
case ARG_USER_UNIT:
arg_show_unit = SHOW_UNIT_USER;
if (strv_push(&arg_names, optarg) < 0) /* push optarg if not empty */
return log_oom();
break;
case 1:
/* positional argument */
if (strv_push(&arg_names, optarg) < 0)
return log_oom();
break;
case 'l':
arg_full = true;
break;
case 'k':
arg_output_flags |= OUTPUT_KERNEL_THREADS;
break;
case 'M':
arg_machine = optarg;
break;
case 'x':
if (optarg) {
r = parse_boolean(optarg);
if (r < 0)
return log_error_errno(r, "Failed to parse --xattr= value: %s", optarg);
} else
r = true;
SET_FLAG(arg_output_flags, OUTPUT_CGROUP_XATTRS, r);
break;
case 'c':
if (optarg) {
r = parse_boolean(optarg);
if (r < 0)
return log_error_errno(r, "Failed to parse --cgroup-id= value: %s", optarg);
} else
r = true;
SET_FLAG(arg_output_flags, OUTPUT_CGROUP_ID, r);
break;
case '?':
return -EINVAL;
default:
assert_not_reached();
}
if (arg_machine && arg_show_unit != SHOW_UNIT_NONE)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Cannot combine --unit or --user-unit with --machine=.");
return 1;
}
static void show_cg_info(const char *controller, const char *path) {
if (cg_all_unified() == 0 && controller && !streq(controller, SYSTEMD_CGROUP_CONTROLLER))
printf("Controller %s; ", controller);
printf("CGroup %s:\n", empty_to_root(path));
fflush(stdout);
}
static int run(int argc, char *argv[]) {
int r;
log_setup();
r = parse_argv(argc, argv);
if (r <= 0)
return r;
pager_open(arg_pager_flags);
if (arg_full < 0 && pager_have())
arg_full = true;
if (arg_full > 0)
arg_output_flags |= OUTPUT_FULL_WIDTH;
if (arg_names) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
_cleanup_free_ char *root = NULL;
STRV_FOREACH(name, arg_names) {
int q;
if (arg_show_unit != SHOW_UNIT_NONE) {
/* Command line arguments are unit names */
_cleanup_free_ char *cgroup = NULL, *unit_name = NULL;
r = unit_name_mangle(*name, UNIT_NAME_MANGLE_WARN, &unit_name);
if (r < 0)
return log_error_errno(r, "Failed to mangle unit name: %m");
if (!bus) {
/* Connect to the bus only if necessary */
r = bus_connect_transport_systemd(
BUS_TRANSPORT_LOCAL, NULL,
arg_show_unit == SHOW_UNIT_USER ? RUNTIME_SCOPE_USER : RUNTIME_SCOPE_SYSTEM,
&bus);
if (r < 0)
return bus_log_connect_error(r, BUS_TRANSPORT_LOCAL);
}
q = show_cgroup_get_unit_path_and_warn(bus, unit_name, &cgroup);
if (q < 0)
goto failed;
if (isempty(cgroup)) {
q = log_warning_errno(SYNTHETIC_ERRNO(ENOENT), "Unit %s not found.", unit_name);
goto failed;
}
printf("Unit %s (%s):\n", unit_name, cgroup);
fflush(stdout);
q = show_cgroup_by_path(cgroup, NULL, 0, arg_output_flags);
} else if (path_startswith(*name, "/sys/fs/cgroup")) {
printf("Directory %s:\n", *name);
fflush(stdout);
q = show_cgroup_by_path(*name, NULL, 0, arg_output_flags);
} else {
_cleanup_free_ char *c = NULL, *p = NULL, *j = NULL;
const char *controller, *path;
if (!root) {
/* Query root only if needed, treat error as fatal */
r = show_cgroup_get_path_and_warn(arg_machine, NULL, &root);
if (r < 0)
return log_error_errno(r, "Failed to list cgroup tree: %m");
}
q = cg_split_spec(*name, &c, &p);
if (q < 0) {
log_error_errno(q, "Failed to split argument %s: %m", *name);
goto failed;
}
controller = c ?: SYSTEMD_CGROUP_CONTROLLER;
if (p) {
j = path_join(root, p);
if (!j)
return log_oom();
path_simplify(j);
path = j;
} else
path = root;
show_cg_info(controller, path);
q = show_cgroup(controller, path, NULL, 0, arg_output_flags);
}
failed:
if (q < 0 && r >= 0)
r = q;
}
} else {
bool done = false;
if (!arg_machine) {
_cleanup_free_ char *cwd = NULL;
r = safe_getcwd(&cwd);
if (r < 0)
return log_error_errno(r, "Cannot determine current working directory: %m");
if (path_startswith(cwd, "/sys/fs/cgroup")) {
printf("Working directory %s:\n", cwd);
fflush(stdout);
r = show_cgroup_by_path(cwd, NULL, 0, arg_output_flags);
done = true;
}
}
if (!done) {
_cleanup_free_ char *root = NULL;
r = show_cgroup_get_path_and_warn(arg_machine, NULL, &root);
if (r < 0)
return log_error_errno(r, "Failed to list cgroup tree: %m");
show_cg_info(SYSTEMD_CGROUP_CONTROLLER, root);
printf("-.slice\n");
r = show_cgroup(SYSTEMD_CGROUP_CONTROLLER, root, NULL, 0, arg_output_flags);
}
}
if (r < 0)
return log_error_errno(r, "Failed to list cgroup tree: %m");
return 0;
}
DEFINE_MAIN_FUNCTION(run);
| 12,355 | 36.442424 | 132 |
c
|
null |
systemd-main/src/cgroups-agent/cgroups-agent.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdlib.h>
#include "fd-util.h"
#include "log.h"
#include "socket-util.h"
int main(int argc, char *argv[]) {
static const union sockaddr_union sa = {
.un.sun_family = AF_UNIX,
.un.sun_path = "/run/systemd/cgroups-agent",
};
_cleanup_close_ int fd = -EBADF;
ssize_t n;
size_t l;
int r;
r = make_null_stdio();
if (r < 0) {
log_error_errno(r, "Failed to connect stdin/stdout/stderr with /dev/null: %m");
return EXIT_FAILURE;
}
if (argc != 2) {
log_error("Incorrect number of arguments.");
return EXIT_FAILURE;
}
log_setup();
fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
if (fd < 0) {
log_debug_errno(errno, "Failed to allocate socket: %m");
return EXIT_FAILURE;
}
l = strlen(argv[1]);
n = sendto(fd, argv[1], l, 0, &sa.sa, SOCKADDR_UN_LEN(sa.un));
if (n < 0) {
log_debug_errno(errno, "Failed to send cgroups agent message: %m");
return EXIT_FAILURE;
}
if ((size_t) n != l) {
log_debug("Datagram size mismatch");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 1,399 | 24.454545 | 95 |
c
|
null |
systemd-main/src/core/automount.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct Automount Automount;
#include "unit.h"
typedef enum AutomountResult {
AUTOMOUNT_SUCCESS,
AUTOMOUNT_FAILURE_RESOURCES,
AUTOMOUNT_FAILURE_UNMOUNTED,
AUTOMOUNT_FAILURE_START_LIMIT_HIT,
AUTOMOUNT_FAILURE_MOUNT_START_LIMIT_HIT,
_AUTOMOUNT_RESULT_MAX,
_AUTOMOUNT_RESULT_INVALID = -EINVAL,
} AutomountResult;
struct Automount {
Unit meta;
AutomountState state, deserialized_state;
char *where;
char *extra_options;
usec_t timeout_idle_usec;
int pipe_fd;
sd_event_source *pipe_event_source;
mode_t directory_mode;
dev_t dev_id;
Set *tokens;
Set *expire_tokens;
sd_event_source *expire_event_source;
AutomountResult result;
};
extern const UnitVTable automount_vtable;
const char* automount_result_to_string(AutomountResult i) _const_;
AutomountResult automount_result_from_string(const char *s) _pure_;
DEFINE_CAST(AUTOMOUNT, Automount);
| 1,080 | 22.5 | 67 |
h
|
null |
systemd-main/src/core/bpf-devices.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include "cgroup.h"
typedef struct BPFProgram BPFProgram;
int bpf_devices_cgroup_init(BPFProgram **ret, CGroupDevicePolicy policy, bool allow_list);
int bpf_devices_apply_policy(
BPFProgram **prog,
CGroupDevicePolicy policy,
bool allow_list,
const char *cgroup_path,
BPFProgram **prog_installed);
int bpf_devices_supported(void);
int bpf_devices_allow_list_device(BPFProgram *prog, const char *path, const char *node, const char *acc);
int bpf_devices_allow_list_major(BPFProgram *prog, const char *path, const char *name, char type, const char *acc);
int bpf_devices_allow_list_static(BPFProgram *prog, const char *path);
| 792 | 35.045455 | 115 |
h
|
null |
systemd-main/src/core/bpf-firewall.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include "unit.h"
enum {
BPF_FIREWALL_UNSUPPORTED = 0,
BPF_FIREWALL_SUPPORTED = 1,
BPF_FIREWALL_SUPPORTED_WITH_MULTI = 2,
};
int bpf_firewall_supported(void);
int bpf_firewall_compile(Unit *u);
int bpf_firewall_install(Unit *u);
int bpf_firewall_load_custom(Unit *u);
int bpf_firewall_read_accounting(int map_fd, uint64_t *ret_bytes, uint64_t *ret_packets);
int bpf_firewall_reset_accounting(int map_fd);
void emit_bpf_firewall_warning(Unit *u);
void bpf_firewall_close(Unit *u);
| 616 | 22.730769 | 89 |
h
|
null |
systemd-main/src/core/bpf-foreign.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bpf-foreign.h"
#include "bpf-program.h"
#include "cgroup.h"
#include "memory-util.h"
#include "missing_magic.h"
#include "mountpoint-util.h"
#include "set.h"
#include "stat-util.h"
typedef struct BPFForeignKey BPFForeignKey;
struct BPFForeignKey {
uint32_t prog_id;
uint32_t attach_type;
};
static int bpf_foreign_key_new(uint32_t prog_id,
enum bpf_attach_type attach_type,
BPFForeignKey **ret) {
_cleanup_free_ BPFForeignKey *p = NULL;
assert(ret);
p = new(BPFForeignKey, 1);
if (!p)
return -ENOMEM;
*p = (BPFForeignKey) {
.prog_id = prog_id,
.attach_type = attach_type,
};
*ret = TAKE_PTR(p);
return 0;
}
static int bpf_foreign_key_compare_func(const BPFForeignKey *a, const BPFForeignKey *b) {
int r = CMP(a->prog_id, b->prog_id);
if (r != 0)
return r;
return CMP(a->attach_type, b->attach_type);
}
static void bpf_foreign_key_hash_func(const BPFForeignKey *p, struct siphash *h) {
siphash24_compress(&p->prog_id, sizeof(p->prog_id), h);
siphash24_compress(&p->attach_type, sizeof(p->attach_type), h);
}
DEFINE_PRIVATE_HASH_OPS_FULL(bpf_foreign_by_key_hash_ops,
BPFForeignKey, bpf_foreign_key_hash_func, bpf_foreign_key_compare_func, free,
BPFProgram, bpf_program_free);
static int attach_programs(Unit *u, const char *path, Hashmap* foreign_by_key, uint32_t attach_flags) {
const BPFForeignKey *key;
BPFProgram *prog;
int r, ret = 0;
assert(u);
HASHMAP_FOREACH_KEY(prog, key, foreign_by_key) {
r = bpf_program_cgroup_attach(prog, key->attach_type, path, attach_flags);
if (r < 0) {
log_unit_error_errno(u, r, "bpf-foreign: Attaching foreign BPF program to cgroup %s failed: %m", path);
if (ret >= 0)
ret = r;
}
}
return ret;
}
/*
* Prepare foreign BPF program for installation:
* - Load the program from BPF filesystem to the kernel;
* - Store program FD identified by program ID and attach type in the unit.
*/
static int bpf_foreign_prepare(
Unit *u,
enum bpf_attach_type attach_type,
const char *bpffs_path) {
_cleanup_(bpf_program_freep) BPFProgram *prog = NULL;
_cleanup_free_ BPFForeignKey *key = NULL;
uint32_t prog_id;
int r;
assert(u);
assert(bpffs_path);
r = path_is_fs_type(bpffs_path, BPF_FS_MAGIC);
if (r == -ENOENT) {
log_unit_warning_errno(u, r, "bpf-foreign: foreign program %s does not exist, skipping.", bpffs_path);
return 0;
}
if (r < 0)
return log_unit_error_errno(u, r,
"bpf-foreign: Failed to determine filesystem type of %s: %m", bpffs_path);
if (r == 0)
return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
"bpf-foreign: Path in BPF filesystem is expected.");
r = bpf_program_new_from_bpffs_path(bpffs_path, &prog);
if (r < 0)
return log_unit_error_errno(u, r, "bpf-foreign: Failed to create foreign BPF program: %m");
r = bpf_program_get_id_by_fd(prog->kernel_fd, &prog_id);
if (r < 0)
return log_unit_error_errno(u, r, "bpf-foreign: Failed to get BPF program id from fd: %m");
r = bpf_foreign_key_new(prog_id, attach_type, &key);
if (r < 0)
return log_unit_error_errno(u, r,
"bpf-foreign: Failed to create foreign BPF program key from path '%s': %m", bpffs_path);
r = hashmap_ensure_put(&u->bpf_foreign_by_key, &bpf_foreign_by_key_hash_ops, key, prog);
if (r == -EEXIST) {
log_unit_warning_errno(u, r, "bpf-foreign: Foreign BPF program already exists, ignoring: %m");
return 0;
}
if (r < 0)
return log_unit_error_errno(u, r, "bpf-foreign: Failed to put foreign BPF program into map: %m");
TAKE_PTR(key);
TAKE_PTR(prog);
return 0;
}
int bpf_foreign_install(Unit *u) {
_cleanup_free_ char *cgroup_path = NULL;
CGroupContext *cc;
int r, ret = 0;
assert(u);
cc = unit_get_cgroup_context(u);
if (!cc)
return 0;
r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, NULL, &cgroup_path);
if (r < 0)
return log_unit_error_errno(u, r, "bpf-foreign: Failed to get cgroup path: %m");
LIST_FOREACH(programs, p, cc->bpf_foreign_programs) {
r = bpf_foreign_prepare(u, p->attach_type, p->bpffs_path);
if (r < 0 && ret >= 0)
ret = r;
}
r = attach_programs(u, cgroup_path, u->bpf_foreign_by_key, BPF_F_ALLOW_MULTI);
return ret < 0 ? ret : r;
}
| 5,172 | 32.374194 | 127 |
c
|
null |
systemd-main/src/core/bpf-lsm.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <linux/types.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "alloc-util.h"
#include "bpf-lsm.h"
#include "cgroup-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "filesystems.h"
#include "log.h"
#include "lsm-util.h"
#include "manager.h"
#include "mkdir.h"
#include "nulstr-util.h"
#include "stat-util.h"
#include "strv.h"
#if BPF_FRAMEWORK
/* libbpf, clang and llc compile time dependencies are satisfied */
#include "bpf-dlopen.h"
#include "bpf-link.h"
#include "bpf-util.h"
#include "bpf/restrict_fs/restrict-fs-skel.h"
#define CGROUP_HASH_SIZE_MAX 2048
static struct restrict_fs_bpf *restrict_fs_bpf_free(struct restrict_fs_bpf *obj) {
/* restrict_fs_bpf__destroy handles object == NULL case */
(void) restrict_fs_bpf__destroy(obj);
return NULL;
}
DEFINE_TRIVIAL_CLEANUP_FUNC(struct restrict_fs_bpf *, restrict_fs_bpf_free);
static bool bpf_can_link_lsm_program(struct bpf_program *prog) {
_cleanup_(bpf_link_freep) struct bpf_link *link = NULL;
assert(prog);
link = sym_bpf_program__attach_lsm(prog);
/* If bpf_program__attach_lsm fails the resulting value stores libbpf error code instead of memory
* pointer. That is the case when the helper is called on architectures where BPF trampoline (hence
* BPF_LSM_MAC attach type) is not supported. */
return sym_libbpf_get_error(link) == 0;
}
static int prepare_restrict_fs_bpf(struct restrict_fs_bpf **ret_obj) {
_cleanup_(restrict_fs_bpf_freep) struct restrict_fs_bpf *obj = NULL;
_cleanup_close_ int inner_map_fd = -EBADF;
int r;
assert(ret_obj);
obj = restrict_fs_bpf__open();
if (!obj)
return log_error_errno(errno, "bpf-lsm: Failed to open BPF object: %m");
/* TODO Maybe choose a number based on runtime information? */
r = sym_bpf_map__set_max_entries(obj->maps.cgroup_hash, CGROUP_HASH_SIZE_MAX);
assert(r <= 0);
if (r < 0)
return log_error_errno(r, "bpf-lsm: Failed to resize BPF map '%s': %m",
sym_bpf_map__name(obj->maps.cgroup_hash));
/* Dummy map to satisfy the verifier */
inner_map_fd = compat_bpf_map_create(BPF_MAP_TYPE_HASH, NULL, sizeof(uint32_t), sizeof(uint32_t), 128U, NULL);
if (inner_map_fd < 0)
return log_error_errno(errno, "bpf-lsm: Failed to create BPF map: %m");
r = sym_bpf_map__set_inner_map_fd(obj->maps.cgroup_hash, inner_map_fd);
assert(r <= 0);
if (r < 0)
return log_error_errno(r, "bpf-lsm: Failed to set inner map fd: %m");
r = restrict_fs_bpf__load(obj);
assert(r <= 0);
if (r < 0)
return log_error_errno(r, "bpf-lsm: Failed to load BPF object: %m");
*ret_obj = TAKE_PTR(obj);
return 0;
}
bool lsm_bpf_supported(bool initialize) {
_cleanup_(restrict_fs_bpf_freep) struct restrict_fs_bpf *obj = NULL;
static int supported = -1;
int r;
if (supported >= 0)
return supported;
if (!initialize)
return false;
if (!cgroup_bpf_supported())
return (supported = false);
r = lsm_supported("bpf");
if (r < 0) {
log_warning_errno(r, "bpf-lsm: Can't determine whether the BPF LSM module is used: %m");
return (supported = false);
}
if (r == 0) {
log_info_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"bpf-lsm: BPF LSM hook not enabled in the kernel, BPF LSM not supported");
return (supported = false);
}
r = prepare_restrict_fs_bpf(&obj);
if (r < 0)
return (supported = false);
if (!bpf_can_link_lsm_program(obj->progs.restrict_filesystems)) {
log_warning_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"bpf-lsm: Failed to link program; assuming BPF LSM is not available");
return (supported = false);
}
return (supported = true);
}
int lsm_bpf_setup(Manager *m) {
_cleanup_(restrict_fs_bpf_freep) struct restrict_fs_bpf *obj = NULL;
_cleanup_(bpf_link_freep) struct bpf_link *link = NULL;
int r;
assert(m);
r = prepare_restrict_fs_bpf(&obj);
if (r < 0)
return r;
link = sym_bpf_program__attach_lsm(obj->progs.restrict_filesystems);
r = sym_libbpf_get_error(link);
if (r != 0)
return log_error_errno(r, "bpf-lsm: Failed to link '%s' LSM BPF program: %m",
sym_bpf_program__name(obj->progs.restrict_filesystems));
log_info("bpf-lsm: LSM BPF program attached");
obj->links.restrict_filesystems = TAKE_PTR(link);
m->restrict_fs = TAKE_PTR(obj);
return 0;
}
int lsm_bpf_unit_restrict_filesystems(Unit *u, const Set *filesystems, bool allow_list) {
uint32_t dummy_value = 1, zero = 0;
const char *fs;
const statfs_f_type_t *magic;
int r;
assert(filesystems);
assert(u);
if (!u->manager->restrict_fs)
return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
"bpf-lsm: BPF LSM object is not installed, has setup failed?");
int inner_map_fd = compat_bpf_map_create(
BPF_MAP_TYPE_HASH,
NULL,
sizeof(uint32_t),
sizeof(uint32_t),
128U, /* Should be enough for all filesystem types */
NULL);
if (inner_map_fd < 0)
return log_unit_error_errno(u, errno, "bpf-lsm: Failed to create inner BPF map: %m");
int outer_map_fd = sym_bpf_map__fd(u->manager->restrict_fs->maps.cgroup_hash);
if (outer_map_fd < 0)
return log_unit_error_errno(u, errno, "bpf-lsm: Failed to get BPF map fd: %m");
if (sym_bpf_map_update_elem(outer_map_fd, &u->cgroup_id, &inner_map_fd, BPF_ANY) != 0)
return log_unit_error_errno(u, errno, "bpf-lsm: Error populating BPF map: %m");
uint32_t allow = allow_list;
/* Use key 0 to store whether this is an allow list or a deny list */
if (sym_bpf_map_update_elem(inner_map_fd, &zero, &allow, BPF_ANY) != 0)
return log_unit_error_errno(u, errno, "bpf-lsm: Error initializing map: %m");
SET_FOREACH(fs, filesystems) {
r = fs_type_from_string(fs, &magic);
if (r < 0) {
log_unit_warning(u, "bpf-lsm: Invalid filesystem name '%s', ignoring.", fs);
continue;
}
log_unit_debug(u, "bpf-lsm: Restricting filesystem access to '%s'", fs);
for (int i = 0; i < FILESYSTEM_MAGIC_MAX; i++) {
if (magic[i] == 0)
break;
if (sym_bpf_map_update_elem(inner_map_fd, &magic[i], &dummy_value, BPF_ANY) != 0) {
r = log_unit_error_errno(u, errno, "bpf-lsm: Failed to update BPF map: %m");
if (sym_bpf_map_delete_elem(outer_map_fd, &u->cgroup_id) != 0)
log_unit_debug_errno(u, errno, "bpf-lsm: Failed to delete cgroup entry from BPF map: %m");
return r;
}
}
}
return 0;
}
int lsm_bpf_cleanup(const Unit *u) {
assert(u);
assert(u->manager);
/* If we never successfully detected support, there is nothing to clean up. */
if (!lsm_bpf_supported(/* initialize = */ false))
return 0;
if (!u->manager->restrict_fs)
return 0;
int fd = sym_bpf_map__fd(u->manager->restrict_fs->maps.cgroup_hash);
if (fd < 0)
return log_unit_error_errno(u, errno, "bpf-lsm: Failed to get BPF map fd: %m");
if (sym_bpf_map_delete_elem(fd, &u->cgroup_id) != 0)
return log_unit_debug_errno(u, errno, "bpf-lsm: Failed to delete cgroup entry from LSM BPF map: %m");
return 0;
}
int lsm_bpf_map_restrict_fs_fd(Unit *unit) {
assert(unit);
assert(unit->manager);
if (!unit->manager->restrict_fs)
return -ENOMEDIUM;
return sym_bpf_map__fd(unit->manager->restrict_fs->maps.cgroup_hash);
}
void lsm_bpf_destroy(struct restrict_fs_bpf *prog) {
restrict_fs_bpf__destroy(prog);
}
#else /* ! BPF_FRAMEWORK */
bool lsm_bpf_supported(bool initialize) {
return false;
}
int lsm_bpf_setup(Manager *m) {
return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "bpf-lsm: Failed to set up LSM BPF: %m");
}
int lsm_bpf_unit_restrict_filesystems(Unit *u, const Set *filesystems, const bool allow_list) {
return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EOPNOTSUPP), "bpf-lsm: Failed to restrict filesystems using LSM BPF: %m");
}
int lsm_bpf_cleanup(const Unit *u) {
return 0;
}
int lsm_bpf_map_restrict_fs_fd(Unit *unit) {
return -ENOMEDIUM;
}
void lsm_bpf_destroy(struct restrict_fs_bpf *prog) {
return;
}
#endif
int lsm_bpf_parse_filesystem(
const char *name,
Set **filesystems,
FilesystemParseFlags flags,
const char *unit,
const char *filename,
unsigned line) {
int r;
assert(name);
assert(filesystems);
if (name[0] == '@') {
const FilesystemSet *set;
set = filesystem_set_find(name);
if (!set) {
log_syntax(unit, flags & FILESYSTEM_PARSE_LOG ? LOG_WARNING : LOG_DEBUG, filename, line, 0,
"bpf-lsm: Unknown filesystem group, ignoring: %s", name);
return 0;
}
NULSTR_FOREACH(i, set->value) {
/* Call ourselves again, for the group to parse. Note that we downgrade logging here
* (i.e. take away the FILESYSTEM_PARSE_LOG flag) since any issues in the group table
* are our own problem, not a problem in user configuration data and we shouldn't
* pretend otherwise by complaining about them. */
r = lsm_bpf_parse_filesystem(i, filesystems, flags &~ FILESYSTEM_PARSE_LOG, unit, filename, line);
if (r < 0)
return r;
}
} else {
/* If we previously wanted to forbid access to a filesystem and now
* we want to allow it, then remove it from the list. */
if (!(flags & FILESYSTEM_PARSE_INVERT) == !!(flags & FILESYSTEM_PARSE_ALLOW_LIST)) {
r = set_put_strdup(filesystems, name);
if (r == -ENOMEM)
return flags & FILESYSTEM_PARSE_LOG ? log_oom() : -ENOMEM;
if (r < 0 && r != -EEXIST) /* When already in set, ignore */
return r;
} else
free(set_remove(*filesystems, name));
}
return 0;
}
| 11,676 | 34.819018 | 130 |
c
|
null |
systemd-main/src/core/bpf-lsm.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "hashmap.h"
typedef enum FilesystemParseFlags {
FILESYSTEM_PARSE_INVERT = 1 << 0,
FILESYSTEM_PARSE_ALLOW_LIST = 1 << 1,
FILESYSTEM_PARSE_LOG = 1 << 2,
} FilesystemParseFlags;
typedef struct Unit Unit;
typedef struct Manager Manager;
typedef struct restrict_fs_bpf restrict_fs_bpf;
bool lsm_bpf_supported(bool initialize);
int lsm_bpf_setup(Manager *m);
int lsm_bpf_unit_restrict_filesystems(Unit *u, const Set *filesystems, bool allow_list);
int lsm_bpf_cleanup(const Unit *u);
int lsm_bpf_map_restrict_fs_fd(Unit *u);
void lsm_bpf_destroy(struct restrict_fs_bpf *prog);
int lsm_bpf_parse_filesystem(const char *name,
Set **filesystems,
FilesystemParseFlags flags,
const char *unit,
const char *filename,
unsigned line);
| 977 | 32.724138 | 88 |
h
|
null |
systemd-main/src/core/bpf-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bpf-dlopen.h"
#include "bpf-util.h"
#include "cgroup-util.h"
#include "initrd-util.h"
#include "log.h"
bool cgroup_bpf_supported(void) {
static int supported = -1;
int r;
if (supported >= 0)
return supported;
r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
if (r < 0) {
log_warning_errno(r, "Can't determine whether the unified hierarchy is used: %m");
return (supported = false);
}
if (r == 0) {
log_info_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Not running with unified cgroup hierarchy, disabling cgroup BPF features.");
return (supported = false);
}
r = dlopen_bpf();
if (r < 0) {
log_full_errno(in_initrd() ? LOG_DEBUG : LOG_INFO,
r, "Failed to open libbpf, cgroup BPF features disabled: %m");
return (supported = false);
}
return (supported = true);
}
| 1,095 | 28.621622 | 108 |
c
|
null |
systemd-main/src/core/core-varlink.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "manager.h"
int manager_varlink_init(Manager *m);
void manager_varlink_done(Manager *m);
/* Creates a new VarlinkServer and binds methods. Does not set up sockets or attach events.
* Used for manager serialize/deserialize. */
int manager_setup_varlink_server(Manager *m, VarlinkServer **ret_s);
/* The manager is expected to send an update to systemd-oomd if one of the following occurs:
* - The value of ManagedOOM*= properties change
* - A unit with ManagedOOM*= properties changes unit active state */
int manager_varlink_send_managed_oom_update(Unit *u);
| 637 | 36.529412 | 92 |
h
|
null |
systemd-main/src/core/crash-handler.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/reboot.h>
#include "crash-handler.h"
#include "exit-status.h"
#include "macro.h"
#include "main.h"
#include "missing_syscall.h"
#include "process-util.h"
#include "raw-clone.h"
#include "rlimit-util.h"
#include "signal-util.h"
#include "terminal-util.h"
#include "virt.h"
_noreturn_ void freeze_or_exit_or_reboot(void) {
/* If we are running in a container, let's prefer exiting, after all we can propagate an exit code to
* the container manager, and thus inform it that something went wrong. */
if (detect_container() > 0) {
log_emergency("Exiting PID 1...");
_exit(EXIT_EXCEPTION);
}
if (arg_crash_reboot) {
log_notice("Rebooting in 10s...");
(void) sleep(10);
log_notice("Rebooting now...");
(void) reboot(RB_AUTOBOOT);
log_emergency_errno(errno, "Failed to reboot: %m");
}
log_emergency("Freezing execution.");
sync();
freeze();
}
_noreturn_ static void crash(int sig, siginfo_t *siginfo, void *context) {
struct sigaction sa;
pid_t pid;
/* NB: 💣 💣 💣 This is a signal handler, most likely executed in a situation where we have corrupted
* memory. Thus: please avoid any libc memory allocation here, or any functions that internally use
* memory allocation, as we cannot rely on memory allocation still working at this point! (Note that
* memory allocation is not async-signal-safe anyway — see signal-safety(7) for details —, and thus
* is not permissible in signal handlers.) */
if (getpid_cached() != 1)
/* Pass this on immediately, if this is not PID 1 */
propagate_signal(sig, siginfo);
else if (!arg_dump_core)
log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig));
else {
sa = (struct sigaction) {
.sa_handler = nop_signal_handler,
.sa_flags = SA_NOCLDSTOP|SA_RESTART,
};
/* We want to wait for the core process, hence let's enable SIGCHLD */
(void) sigaction(SIGCHLD, &sa, NULL);
pid = raw_clone(SIGCHLD);
if (pid < 0)
log_emergency_errno(errno, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig));
else if (pid == 0) {
/* Enable default signal handler for core dump */
sa = (struct sigaction) {
.sa_handler = SIG_DFL,
};
(void) sigaction(sig, &sa, NULL);
/* Don't limit the coredump size */
(void) setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY));
/* Just to be sure... */
(void) chdir("/");
/* Raise the signal again */
propagate_signal(sig, siginfo);
assert_not_reached();
_exit(EXIT_EXCEPTION);
} else {
siginfo_t status;
int r;
if (siginfo) {
if (siginfo->si_pid == 0)
log_emergency("Caught <%s> from unknown sender process.", signal_to_string(sig));
else if (siginfo->si_pid == 1)
log_emergency("Caught <%s> from our own process.", signal_to_string(sig));
else
log_emergency("Caught <%s> from PID "PID_FMT".", signal_to_string(sig), siginfo->si_pid);
}
/* Order things nicely. */
r = wait_for_terminate(pid, &status);
if (r < 0)
log_emergency_errno(r, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig));
else if (status.si_code != CLD_DUMPED) {
const char *s = status.si_code == CLD_EXITED
? exit_status_to_string(status.si_status, EXIT_STATUS_LIBC)
: signal_to_string(status.si_status);
log_emergency("Caught <%s>, core dump failed (child "PID_FMT", code=%s, status=%i/%s).",
signal_to_string(sig),
pid,
sigchld_code_to_string(status.si_code),
status.si_status, strna(s));
} else
log_emergency("Caught <%s>, dumped core as pid "PID_FMT".",
signal_to_string(sig), pid);
}
}
if (arg_crash_chvt >= 0)
(void) chvt(arg_crash_chvt);
sa = (struct sigaction) {
.sa_handler = SIG_IGN,
.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
};
/* Let the kernel reap children for us */
(void) sigaction(SIGCHLD, &sa, NULL);
if (arg_crash_shell) {
log_notice("Executing crash shell in 10s...");
(void) sleep(10);
pid = raw_clone(SIGCHLD);
if (pid < 0)
log_emergency_errno(errno, "Failed to fork off crash shell: %m");
else if (pid == 0) {
(void) setsid();
(void) make_console_stdio();
(void) rlimit_nofile_safe();
(void) execle("/bin/sh", "/bin/sh", NULL, environ);
log_emergency_errno(errno, "execle() failed: %m");
_exit(EXIT_EXCEPTION);
} else {
log_info("Spawned crash shell as PID "PID_FMT".", pid);
(void) wait_for_terminate(pid, NULL);
}
}
freeze_or_exit_or_reboot();
}
void install_crash_handler(void) {
static const struct sigaction sa = {
.sa_sigaction = crash,
.sa_flags = SA_NODEFER | SA_SIGINFO, /* So that we can raise the signal again from the signal handler */
};
int r;
/* We ignore the return value here, since, we don't mind if we cannot set up a crash handler */
r = sigaction_many(&sa, SIGNALS_CRASH_HANDLER);
if (r < 0)
log_debug_errno(r, "I had trouble setting up the crash handler, ignoring: %m");
}
| 6,937 | 41.048485 | 129 |
c
|
null |
systemd-main/src/core/dbus-job.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "unit.h"
#include "bus-object.h"
extern const sd_bus_vtable bus_job_vtable[];
extern const BusObjectImplementation job_object;
int bus_job_method_cancel(sd_bus_message *message, void *job, sd_bus_error *error);
int bus_job_method_get_waiting_jobs(sd_bus_message *message, void *userdata, sd_bus_error *error);
void bus_job_send_change_signal(Job *j);
void bus_job_send_pending_change_signal(Job *j, bool including_new);
void bus_job_send_removed_signal(Job *j);
int bus_job_coldplug_bus_track(Job *j);
int bus_job_track_sender(Job *j, sd_bus_message *m);
| 652 | 30.095238 | 98 |
h
|
null |
systemd-main/src/core/dbus-scope.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "sd-bus-vtable.h"
#include "scope.h"
#include "unit.h"
extern const sd_bus_vtable bus_scope_vtable[];
int bus_scope_set_property(Unit *u, const char *name, sd_bus_message *i, UnitWriteFlags flags, sd_bus_error *error);
int bus_scope_commit_properties(Unit *u);
int bus_scope_send_request_stop(Scope *s);
int bus_scope_method_abandon(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_scope_track_controller(Scope *s);
| 536 | 25.85 | 116 |
h
|
null |
systemd-main/src/core/dbus-service.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "sd-bus-vtable.h"
#include "unit.h"
extern const sd_bus_vtable bus_service_vtable[];
int bus_service_set_property(Unit *u, const char *name, sd_bus_message *i, UnitWriteFlags flags, sd_bus_error *error);
int bus_service_method_bind_mount(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_service_method_mount_image(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_service_commit_properties(Unit *u);
int bus_service_method_dump_file_descriptor_store(sd_bus_message *message, void *userdata, sd_bus_error *error);
| 651 | 39.75 | 118 |
h
|
null |
systemd-main/src/core/dbus-unit.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "unit.h"
extern const sd_bus_vtable bus_unit_vtable[];
extern const sd_bus_vtable bus_unit_cgroup_vtable[];
void bus_unit_send_change_signal(Unit *u);
void bus_unit_send_pending_change_signal(Unit *u, bool including_new);
int bus_unit_send_pending_freezer_message(Unit *u, bool cancelled);
void bus_unit_send_removed_signal(Unit *u);
int bus_unit_method_start_generic(sd_bus_message *message, Unit *u, JobType job_type, bool reload_if_possible, sd_bus_error *error);
int bus_unit_method_enqueue_job(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_kill(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_reset_failed(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_set_properties(Unit *u, sd_bus_message *message, UnitWriteFlags flags, bool commit, sd_bus_error *error);
int bus_unit_method_set_properties(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_get_processes(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_attach_processes(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_ref(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_unref(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_clean(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_freeze(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_unit_method_thaw(sd_bus_message *message, void *userdata, sd_bus_error *error);
typedef enum BusUnitQueueFlags {
BUS_UNIT_QUEUE_RELOAD_IF_POSSIBLE = 1 << 0,
BUS_UNIT_QUEUE_VERBOSE_REPLY = 1 << 1,
} BusUnitQueueFlags;
int bus_unit_queue_job_one(
sd_bus_message *message,
Unit *u,
JobType type,
JobMode mode,
BusUnitQueueFlags flags,
sd_bus_message *reply,
sd_bus_error *error);
int bus_unit_queue_job(
sd_bus_message *message,
Unit *u,
JobType type,
JobMode mode,
BusUnitQueueFlags flags,
sd_bus_error *error);
int bus_unit_validate_load_state(Unit *u, sd_bus_error *error);
int bus_unit_track_add_name(Unit *u, const char *name);
int bus_unit_track_add_sender(Unit *u, sd_bus_message *m);
int bus_unit_track_remove_sender(Unit *u, sd_bus_message *m);
| 2,625 | 45.892857 | 132 |
h
|
null |
systemd-main/src/core/dbus-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bus-polkit.h"
#include "bus-util.h"
#include "dbus-util.h"
#include "escape.h"
#include "parse-util.h"
#include "path-util.h"
#include "unit-printf.h"
#include "user-util.h"
#include "unit.h"
int bus_property_get_triggered_unit(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
Unit *u = userdata, *trigger;
assert(bus);
assert(reply);
assert(u);
trigger = UNIT_TRIGGER(u);
return sd_bus_message_append(reply, "s", trigger ? trigger->id : NULL);
}
BUS_DEFINE_SET_TRANSIENT(mode_t, "u", uint32_t, mode_t, "%04o");
BUS_DEFINE_SET_TRANSIENT(unsigned, "u", uint32_t, unsigned, "%" PRIu32);
static inline bool valid_user_group_name_or_id_relaxed(const char *u) {
return valid_user_group_name(u, VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX);
}
BUS_DEFINE_SET_TRANSIENT_STRING_WITH_CHECK(user_relaxed, valid_user_group_name_or_id_relaxed);
BUS_DEFINE_SET_TRANSIENT_STRING_WITH_CHECK(path, path_is_absolute);
int bus_set_transient_string(
Unit *u,
const char *name,
char **p,
sd_bus_message *message,
UnitWriteFlags flags,
sd_bus_error *error) {
const char *v;
int r;
assert(p);
r = sd_bus_message_read(message, "s", &v);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
r = free_and_strdup(p, empty_to_null(v));
if (r < 0)
return r;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name,
"%s=%s", name, strempty(v));
}
return 1;
}
int bus_set_transient_bool(
Unit *u,
const char *name,
bool *p,
sd_bus_message *message,
UnitWriteFlags flags,
sd_bus_error *error) {
int v, r;
assert(p);
r = sd_bus_message_read(message, "b", &v);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
*p = v;
unit_write_settingf(u, flags, name, "%s=%s", name, yes_no(v));
}
return 1;
}
int bus_set_transient_tristate(
Unit *u,
const char *name,
int *p,
sd_bus_message *message,
UnitWriteFlags flags,
sd_bus_error *error) {
int v, r;
assert(p);
r = sd_bus_message_read(message, "b", &v);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
*p = v;
unit_write_settingf(u, flags, name, "%s=%s", name, yes_no(v));
}
return 1;
}
int bus_set_transient_usec_internal(
Unit *u,
const char *name,
usec_t *p,
bool fix_0,
sd_bus_message *message,
UnitWriteFlags flags,
sd_bus_error *error) {
uint64_t v;
int r;
assert(p);
r = sd_bus_message_read(message, "t", &v);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (fix_0)
*p = v != 0 ? v: USEC_INFINITY;
else
*p = v;
char *n = strndupa_safe(name, strlen(name) - 4);
unit_write_settingf(u, flags, name, "%sSec=%s", n, FORMAT_TIMESPAN(v, USEC_PER_MSEC));
}
return 1;
}
int bus_verify_manage_units_async_full(
Unit *u,
const char *verb,
int capability,
const char *polkit_message,
bool interactive,
sd_bus_message *call,
sd_bus_error *error) {
const char *details[9] = {
"unit", u->id,
"verb", verb,
};
if (polkit_message) {
details[4] = "polkit.message";
details[5] = polkit_message;
details[6] = "polkit.gettext_domain";
details[7] = GETTEXT_PACKAGE;
}
return bus_verify_polkit_async(
call,
capability,
"org.freedesktop.systemd1.manage-units",
details,
interactive,
UID_INVALID,
&u->manager->polkit_registry,
error);
}
/* ret_format_str is an accumulator, so if it has any pre-existing content, new options will be appended to it */
int bus_read_mount_options(
sd_bus_message *message,
sd_bus_error *error,
MountOptions **ret_options,
char **ret_format_str,
const char *separator) {
_cleanup_(mount_options_free_allp) MountOptions *options = NULL;
_cleanup_free_ char *format_str = NULL;
const char *mount_options, *partition;
int r;
assert(message);
assert(ret_options);
assert(separator);
r = sd_bus_message_enter_container(message, 'a', "(ss)");
if (r < 0)
return r;
while ((r = sd_bus_message_read(message, "(ss)", &partition, &mount_options)) > 0) {
_cleanup_free_ char *escaped = NULL;
_cleanup_free_ MountOptions *o = NULL;
PartitionDesignator partition_designator;
if (chars_intersect(mount_options, WHITESPACE))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
"Invalid mount options string, contains whitespace character(s): %s", mount_options);
partition_designator = partition_designator_from_string(partition);
if (partition_designator < 0)
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid partition name %s", partition);
/* Need to store the options with the escapes, so that they can be parsed again */
escaped = shell_escape(mount_options, ":");
if (!escaped)
return -ENOMEM;
if (!strextend_with_separator(&format_str, separator, partition, ":", escaped))
return -ENOMEM;
o = new(MountOptions, 1);
if (!o)
return -ENOMEM;
*o = (MountOptions) {
.partition_designator = partition_designator,
.options = strdup(mount_options),
};
if (!o->options)
return -ENOMEM;
LIST_APPEND(mount_options, options, TAKE_PTR(o));
}
if (r < 0)
return r;
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
if (options) {
if (ret_format_str) {
char *final = strjoin(*ret_format_str, !isempty(*ret_format_str) ? separator : "", format_str);
if (!final)
return -ENOMEM;
free_and_replace(*ret_format_str, final);
}
LIST_JOIN(mount_options, *ret_options, options);
}
return 0;
}
int bus_property_get_activation_details(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
ActivationDetails **details = ASSERT_PTR(userdata);
_cleanup_strv_free_ char **pairs = NULL;
int r;
assert(reply);
r = activation_details_append_pair(*details, &pairs);
if (r < 0)
return r;
r = sd_bus_message_open_container(reply, 'a', "(ss)");
if (r < 0)
return r;
STRV_FOREACH_PAIR(key, value, pairs) {
r = sd_bus_message_append(reply, "(ss)", *key, *value);
if (r < 0)
return r;
}
return sd_bus_message_close_container(reply);
}
| 8,671 | 29.216028 | 133 |
c
|
null |
systemd-main/src/core/dbus.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "manager.h"
int bus_send_pending_reload_message(Manager *m);
int bus_init_private(Manager *m);
int bus_init_api(Manager *m);
int bus_init_system(Manager *m);
void bus_done_private(Manager *m);
void bus_done_api(Manager *m);
void bus_done_system(Manager *m);
void bus_done(Manager *m);
int bus_fdset_add_all(Manager *m, FDSet *fds);
void bus_track_serialize(sd_bus_track *t, FILE *f, const char *prefix);
int bus_track_coldplug(Manager *m, sd_bus_track **t, bool recursive, char **l);
int bus_foreach_bus(Manager *m, sd_bus_track *subscribed2, int (*send_message)(sd_bus *bus, void *userdata), void *userdata);
int bus_verify_manage_units_async(Manager *m, sd_bus_message *call, sd_bus_error *error);
int bus_verify_manage_unit_files_async(Manager *m, sd_bus_message *call, sd_bus_error *error);
int bus_verify_reload_daemon_async(Manager *m, sd_bus_message *call, sd_bus_error *error);
int bus_verify_set_environment_async(Manager *m, sd_bus_message *call, sd_bus_error *error);
int bus_verify_bypass_dump_ratelimit_async(Manager *m, sd_bus_message *call, sd_bus_error *error);
int bus_forward_agent_released(Manager *m, const char *path);
uint64_t manager_bus_n_queued_write(Manager *m);
void dump_bus_properties(FILE *f);
int bus_manager_introspect_implementations(FILE *out, const char *pattern);
| 1,403 | 35.947368 | 125 |
h
|
null |
systemd-main/src/core/device.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "unit.h"
typedef struct Device Device;
/* A mask specifying where we have seen the device currently. This is a bitmask because the device might show up
* asynchronously from each other at various places. For example, in very common case a device might already be mounted
* before udev finished probing it (think: a script setting up a loopback block device, formatting it and mounting it
* in quick succession). Hence we need to track precisely where it is already visible and where not. */
typedef enum DeviceFound {
DEVICE_NOT_FOUND = 0,
DEVICE_FOUND_UDEV = 1 << 0, /* The device has shown up in the udev database */
DEVICE_FOUND_MOUNT = 1 << 1, /* The device has shown up in /proc/self/mountinfo */
DEVICE_FOUND_SWAP = 1 << 2, /* The device has shown up in /proc/swaps */
DEVICE_FOUND_MASK = DEVICE_FOUND_UDEV|DEVICE_FOUND_MOUNT|DEVICE_FOUND_SWAP,
} DeviceFound;
struct Device {
Unit meta;
char *sysfs, *deserialized_sysfs;
char *path; /* syspath, device node, alias, or devlink */
/* In order to be able to distinguish dependencies on different device nodes we might end up creating multiple
* devices for the same sysfs path. We chain them up here. */
LIST_FIELDS(struct Device, same_sysfs);
DeviceState state, deserialized_state;
DeviceFound found, deserialized_found, enumerated_found;
bool bind_mounts;
/* The SYSTEMD_WANTS udev property for this device the last time we saw it */
char **wants_property;
};
extern const UnitVTable device_vtable;
void device_found_node(Manager *m, const char *node, DeviceFound found, DeviceFound mask);
bool device_shall_be_bound_by(Unit *device, Unit *u);
DEFINE_CAST(DEVICE, Device);
| 1,848 | 40.088889 | 119 |
h
|
null |
systemd-main/src/core/dynamic-user.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct DynamicUser DynamicUser;
typedef struct DynamicCreds {
/* A combination of a dynamic user and group */
DynamicUser *user;
DynamicUser *group;
} DynamicCreds;
#include "manager.h"
/* Note that this object always allocates a pair of user and group under the same name, even if one of them isn't
* used. This means, if you want to allocate a group and user pair, and they might have two different names, then you
* need to allocated two of these objects. DynamicCreds below makes that easy. */
struct DynamicUser {
Manager *manager;
unsigned n_ref;
/* An AF_UNIX socket pair that contains a datagram containing both the numeric ID assigned, as well as a lock
* file fd locking the user ID we picked. */
int storage_socket[2];
char name[];
};
int dynamic_user_serialize(Manager *m, FILE *f, FDSet *fds);
void dynamic_user_deserialize_one(Manager *m, const char *value, FDSet *fds);
void dynamic_user_vacuum(Manager *m, bool close_user);
int dynamic_user_current(DynamicUser *d, uid_t *ret);
int dynamic_user_lookup_uid(Manager *m, uid_t uid, char **ret);
int dynamic_user_lookup_name(Manager *m, const char *name, uid_t *ret);
int dynamic_creds_make(Manager *m, const char *user, const char *group, DynamicCreds **ret);
int dynamic_creds_realize(DynamicCreds *creds, char **suggested_paths, uid_t *uid, gid_t *gid);
DynamicCreds *dynamic_creds_unref(DynamicCreds *creds);
DynamicCreds *dynamic_creds_destroy(DynamicCreds *creds);
DEFINE_TRIVIAL_CLEANUP_FUNC(DynamicCreds*, dynamic_creds_unref);
DEFINE_TRIVIAL_CLEANUP_FUNC(DynamicCreds*, dynamic_creds_destroy);
| 1,721 | 38.136364 | 117 |
h
|
null |
systemd-main/src/core/efi-random.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <unistd.h>
#include "alloc-util.h"
#include "chattr-util.h"
#include "efi-random.h"
#include "efivars.h"
#include "fd-util.h"
#include "fs-util.h"
#include "random-util.h"
#include "strv.h"
void lock_down_efi_variables(void) {
_cleanup_close_ int fd = -EBADF;
int r;
fd = open(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderSystemToken)), O_RDONLY|O_CLOEXEC);
if (fd < 0) {
if (errno != ENOENT)
log_warning_errno(errno, "Unable to open LoaderSystemToken EFI variable, ignoring: %m");
return;
}
/* Paranoia: let's restrict access modes of these a bit, so that unprivileged users can't use them to
* identify the system or gain too much insight into what we might have credited to the entropy
* pool. */
r = chattr_fd(fd, 0, FS_IMMUTABLE_FL, NULL);
if (r < 0)
log_warning_errno(r, "Failed to drop FS_IMMUTABLE_FL from LoaderSystemToken EFI variable, ignoring: %m");
if (fchmod(fd, 0600) < 0)
log_warning_errno(errno, "Failed to reduce access mode of LoaderSystemToken EFI variable, ignoring: %m");
}
| 1,249 | 34.714286 | 121 |
c
|
null |
systemd-main/src/core/emergency-action.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include "runtime-scope.h"
typedef enum EmergencyAction {
EMERGENCY_ACTION_NONE,
EMERGENCY_ACTION_REBOOT,
EMERGENCY_ACTION_REBOOT_FORCE,
EMERGENCY_ACTION_REBOOT_IMMEDIATE,
EMERGENCY_ACTION_POWEROFF,
EMERGENCY_ACTION_POWEROFF_FORCE,
EMERGENCY_ACTION_POWEROFF_IMMEDIATE,
EMERGENCY_ACTION_EXIT,
_EMERGENCY_ACTION_FIRST_USER_ACTION = EMERGENCY_ACTION_EXIT,
EMERGENCY_ACTION_EXIT_FORCE,
EMERGENCY_ACTION_SOFT_REBOOT,
EMERGENCY_ACTION_SOFT_REBOOT_FORCE,
EMERGENCY_ACTION_KEXEC,
EMERGENCY_ACTION_KEXEC_FORCE,
EMERGENCY_ACTION_HALT,
EMERGENCY_ACTION_HALT_FORCE,
EMERGENCY_ACTION_HALT_IMMEDIATE,
_EMERGENCY_ACTION_MAX,
_EMERGENCY_ACTION_INVALID = -EINVAL,
} EmergencyAction;
typedef enum EmergencyActionFlags {
EMERGENCY_ACTION_IS_WATCHDOG = 1 << 0,
EMERGENCY_ACTION_WARN = 1 << 1,
} EmergencyActionFlags;
#include "macro.h"
#include "manager.h"
void emergency_action(Manager *m,
EmergencyAction action, EmergencyActionFlags options,
const char *reboot_arg, int exit_status, const char *reason);
const char* emergency_action_to_string(EmergencyAction i) _const_;
EmergencyAction emergency_action_from_string(const char *s) _pure_;
int parse_emergency_action(const char *value, RuntimeScope runtime_scope, EmergencyAction *ret);
| 1,527 | 32.217391 | 96 |
h
|
null |
systemd-main/src/core/fuzz-manager-serialize.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdio.h>
#include "alloc-util.h"
#include "fd-util.h"
#include "fuzz.h"
#include "manager-serialize.h"
#include "manager.h"
#include "service.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
_cleanup_(manager_freep) Manager *m = NULL;
_cleanup_fclose_ FILE *f = NULL, *null = NULL;
_cleanup_fdset_free_ FDSet *fdset = NULL;
/* We don't want to fill the logs with messages about parse errors.
* Disable most logging if not running standalone. */
if (!getenv("SYSTEMD_LOG_LEVEL")) {
log_set_max_level(LOG_CRIT);
log_set_target(LOG_TARGET_NULL);
}
assert_se(manager_new(RUNTIME_SCOPE_SYSTEM, MANAGER_TEST_RUN_MINIMAL, &m) >= 0);
/* Set log overrides as well to make it harder for a serialization file
* to switch log levels/targets during fuzzing */
manager_override_log_level(m, log_get_max_level());
manager_override_log_target(m, log_get_target());
assert_se(null = fopen("/dev/null", "we"));
assert_se(fdset = fdset_new());
assert_se(f = data_to_file(data, size));
(void) manager_deserialize(m, f, fdset);
(void) manager_serialize(m, null, fdset, true);
(void) manager_serialize(m, null, fdset, false);
return 0;
}
| 1,385 | 34.538462 | 88 |
c
|
null |
systemd-main/src/core/fuzz-unit-file.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "conf-parser.h"
#include "fd-util.h"
#include "fuzz.h"
#include "install.h"
#include "load-fragment.h"
#include "manager-dump.h"
#include "memstream-util.h"
#include "string-util.h"
#include "unit-serialize.h"
#include "utf8.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
_cleanup_fclose_ FILE *f = NULL;
_cleanup_free_ char *p = NULL;
UnitType t;
_cleanup_(manager_freep) Manager *m = NULL;
Unit *u;
const char *name;
long offset;
if (outside_size_range(size, 0, 65536))
return 0;
f = data_to_file(data, size);
assert_se(f);
if (read_line(f, LINE_MAX, &p) < 0)
return 0;
t = unit_type_from_string(p);
if (t < 0)
return 0;
if (!unit_vtable[t]->load)
return 0;
offset = ftell(f);
assert_se(offset >= 0);
for (;;) {
_cleanup_free_ char *l = NULL;
const char *ll;
if (read_line(f, LONG_LINE_MAX, &l) <= 0)
break;
ll = startswith(l, UTF8_BYTE_ORDER_MARK) ?: l;
ll = ll + strspn(ll, WHITESPACE);
if (HAS_FEATURE_MEMORY_SANITIZER && startswith(ll, "ListenNetlink")) {
/* ListenNetlink causes a false positive in msan,
* let's skip this for now. */
log_notice("Skipping test because ListenNetlink= is present");
return 0;
}
}
assert_se(fseek(f, offset, SEEK_SET) == 0);
/* We don't want to fill the logs with messages about parse errors.
* Disable most logging if not running standalone */
if (!getenv("SYSTEMD_LOG_LEVEL"))
log_set_max_level(LOG_CRIT);
assert_se(manager_new(RUNTIME_SCOPE_SYSTEM, MANAGER_TEST_RUN_MINIMAL, &m) >= 0);
name = strjoina("a.", unit_type_to_string(t));
assert_se(unit_new_for_name(m, unit_vtable[t]->object_size, name, &u) >= 0);
(void) config_parse(
name, name, f,
UNIT_VTABLE(u)->sections,
config_item_perf_lookup, load_fragment_gperf_lookup,
0,
u,
NULL);
_cleanup_(memstream_done) MemStream ms = {};
FILE *g;
assert_se(g = memstream_init(&ms));
unit_dump(u, g, "");
manager_dump(m, g, /* patterns= */ NULL, ">>>");
return 0;
}
| 2,663 | 28.6 | 88 |
c
|
null |
systemd-main/src/core/generator-setup.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "generator-setup.h"
#include "macro.h"
#include "mkdir-label.h"
#include "rm-rf.h"
int lookup_paths_mkdir_generator(LookupPaths *p) {
int r, q;
assert(p);
if (!p->generator || !p->generator_early || !p->generator_late)
return -EINVAL;
r = mkdir_p_label(p->generator, 0755);
q = mkdir_p_label(p->generator_early, 0755);
if (q < 0 && r >= 0)
r = q;
q = mkdir_p_label(p->generator_late, 0755);
if (q < 0 && r >= 0)
r = q;
return r;
}
void lookup_paths_trim_generator(LookupPaths *p) {
assert(p);
/* Trim empty dirs */
if (p->generator)
(void) rmdir(p->generator);
if (p->generator_early)
(void) rmdir(p->generator_early);
if (p->generator_late)
(void) rmdir(p->generator_late);
}
void lookup_paths_flush_generator(LookupPaths *p) {
assert(p);
/* Flush the generated unit files in full */
if (p->generator)
(void) rm_rf(p->generator, REMOVE_ROOT|REMOVE_PHYSICAL);
if (p->generator_early)
(void) rm_rf(p->generator_early, REMOVE_ROOT|REMOVE_PHYSICAL);
if (p->generator_late)
(void) rm_rf(p->generator_late, REMOVE_ROOT|REMOVE_PHYSICAL);
if (p->temporary_dir)
(void) rm_rf(p->temporary_dir, REMOVE_ROOT|REMOVE_PHYSICAL);
}
| 1,531 | 24.966102 | 78 |
c
|
null |
systemd-main/src/core/ima-setup.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/***
Copyright © 2012 Roberto Sassu - Politecnico di Torino, Italy
TORSEC group — http://security.polito.it
***/
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "alloc-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "ima-setup.h"
#include "log.h"
#define IMA_SECFS_DIR "/sys/kernel/security/ima"
#define IMA_SECFS_POLICY IMA_SECFS_DIR "/policy"
#define IMA_POLICY_PATH "/etc/ima/ima-policy"
int ima_setup(void) {
#if ENABLE_IMA
_cleanup_fclose_ FILE *input = NULL;
_cleanup_close_ int imafd = -EBADF;
unsigned lineno = 0;
int r;
if (access(IMA_SECFS_DIR, F_OK) < 0) {
log_debug_errno(errno, "IMA support is disabled in the kernel, ignoring: %m");
return 0;
}
if (access(IMA_SECFS_POLICY, W_OK) < 0) {
log_warning_errno(errno, "Another IMA custom policy has already been loaded, ignoring: %m");
return 0;
}
if (access(IMA_POLICY_PATH, F_OK) < 0) {
log_debug_errno(errno, "No IMA custom policy file "IMA_POLICY_PATH", ignoring: %m");
return 0;
}
imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC);
if (imafd < 0) {
log_error_errno(errno, "Failed to open the IMA kernel interface "IMA_SECFS_POLICY", ignoring: %m");
return 0;
}
/* attempt to write the name of the policy file into sysfs file */
if (write(imafd, IMA_POLICY_PATH, STRLEN(IMA_POLICY_PATH)) > 0)
goto done;
/* fall back to copying the policy line-by-line */
input = fopen(IMA_POLICY_PATH, "re");
if (!input) {
log_warning_errno(errno, "Failed to open the IMA custom policy file "IMA_POLICY_PATH", ignoring: %m");
return 0;
}
safe_close(imafd);
imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC);
if (imafd < 0) {
log_error_errno(errno, "Failed to open the IMA kernel interface "IMA_SECFS_POLICY", ignoring: %m");
return 0;
}
for (;;) {
_cleanup_free_ char *line = NULL;
size_t len;
r = read_line(input, LONG_LINE_MAX, &line);
if (r < 0)
return log_error_errno(r, "Failed to read the IMA custom policy file "IMA_POLICY_PATH": %m");
if (r == 0)
break;
len = strlen(line);
lineno++;
if (len > 0 && write(imafd, line, len) < 0)
return log_error_errno(errno, "Failed to load the IMA custom policy file "IMA_POLICY_PATH"%u: %m",
lineno);
}
done:
log_info("Successfully loaded the IMA custom policy "IMA_POLICY_PATH".");
#endif /* ENABLE_IMA */
return 0;
}
| 3,058 | 31.892473 | 122 |
c
|
null |
systemd-main/src/core/job.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "sd-event.h"
#include "list.h"
#include "unit-dependency-atom.h"
#include "unit-name.h"
#include "unit.h"
typedef struct ActivationDetails ActivationDetails;
typedef struct Job Job;
typedef struct JobDependency JobDependency;
typedef enum JobType JobType;
typedef enum JobState JobState;
typedef enum JobMode JobMode;
typedef enum JobResult JobResult;
/* Be careful when changing the job types! Adjust job_merging_table[] accordingly! */
enum JobType {
JOB_START, /* if a unit does not support being started, we'll just wait until it becomes active */
JOB_VERIFY_ACTIVE,
JOB_STOP,
JOB_RELOAD, /* if running, reload */
/* Note that restarts are first treated like JOB_STOP, but
* then instead of finishing are patched to become
* JOB_START. */
JOB_RESTART, /* If running, stop. Then start unconditionally. */
_JOB_TYPE_MAX_MERGING,
/* JOB_NOP can enter into a transaction, but as it won't pull in
* any dependencies and it uses the special 'nop_job' slot in Unit,
* it won't have to merge with anything (except possibly into another
* JOB_NOP, previously installed). JOB_NOP is special-cased in
* job_type_is_*() functions so that the transaction can be
* activated. */
JOB_NOP = _JOB_TYPE_MAX_MERGING, /* do nothing */
_JOB_TYPE_MAX_IN_TRANSACTION,
/* JOB_TRY_RESTART can never appear in a transaction, because
* it always collapses into JOB_RESTART or JOB_NOP before entering.
* Thus we never need to merge it with anything. */
JOB_TRY_RESTART = _JOB_TYPE_MAX_IN_TRANSACTION, /* if running, stop and then start */
/* Similar to JOB_TRY_RESTART but collapses to JOB_RELOAD or JOB_NOP */
JOB_TRY_RELOAD,
/* JOB_RELOAD_OR_START won't enter into a transaction and cannot result
* from transaction merging (there's no way for JOB_RELOAD and
* JOB_START to meet in one transaction). It can result from a merge
* during job installation, but then it will immediately collapse into
* one of the two simpler types. */
JOB_RELOAD_OR_START, /* if running, reload, otherwise start */
_JOB_TYPE_MAX,
_JOB_TYPE_INVALID = -EINVAL,
};
enum JobState {
JOB_WAITING,
JOB_RUNNING,
_JOB_STATE_MAX,
_JOB_STATE_INVALID = -EINVAL,
};
enum JobMode {
JOB_FAIL, /* Fail if a conflicting job is already queued */
JOB_REPLACE, /* Replace an existing conflicting job */
JOB_REPLACE_IRREVERSIBLY,/* Like JOB_REPLACE + produce irreversible jobs */
JOB_ISOLATE, /* Start a unit, and stop all others */
JOB_FLUSH, /* Flush out all other queued jobs when queueing this one */
JOB_IGNORE_DEPENDENCIES, /* Ignore both requirement and ordering dependencies */
JOB_IGNORE_REQUIREMENTS, /* Ignore requirement dependencies */
JOB_TRIGGERING, /* Adds TRIGGERED_BY dependencies to the same transaction */
JOB_RESTART_DEPENDENCIES,/* A "start" job for the specified unit becomes "restart" for depending units */
_JOB_MODE_MAX,
_JOB_MODE_INVALID = -EINVAL,
};
enum JobResult {
JOB_DONE, /* Job completed successfully (or skipped due to an unmet ConditionXYZ=) */
JOB_CANCELED, /* Job canceled by a conflicting job installation or by explicit cancel request */
JOB_TIMEOUT, /* Job timeout elapsed */
JOB_FAILED, /* Job failed */
JOB_DEPENDENCY, /* A required dependency job did not result in JOB_DONE */
JOB_SKIPPED, /* Negative result of JOB_VERIFY_ACTIVE or skip due to ExecCondition= */
JOB_INVALID, /* JOB_RELOAD of inactive unit */
JOB_ASSERT, /* Couldn't start a unit, because an assert didn't hold */
JOB_UNSUPPORTED, /* Couldn't start a unit, because the unit type is not supported on the system */
JOB_COLLECTED, /* Job was garbage collected, since nothing needed it anymore */
JOB_ONCE, /* Unit was started before, and hence can't be started again */
_JOB_RESULT_MAX,
_JOB_RESULT_INVALID = -EINVAL,
};
struct JobDependency {
/* Encodes that the 'subject' job needs the 'object' job in
* some way. This structure is used only while building a transaction. */
Job *subject;
Job *object;
LIST_FIELDS(JobDependency, subject);
LIST_FIELDS(JobDependency, object);
bool matters:1;
bool conflicts:1;
};
struct Job {
Manager *manager;
Unit *unit;
LIST_FIELDS(Job, transaction);
LIST_FIELDS(Job, dbus_queue);
LIST_FIELDS(Job, gc_queue);
LIST_HEAD(JobDependency, subject_list);
LIST_HEAD(JobDependency, object_list);
/* Used for graph algs as a "I have been here" marker */
Job* marker;
unsigned generation;
uint32_t id;
JobType type;
JobState state;
sd_event_source *timer_event_source;
usec_t begin_usec;
usec_t begin_running_usec;
/*
* This tracks where to send signals, and also which clients
* are allowed to call DBus methods on the job (other than
* root).
*
* There can be more than one client, because of job merging.
*/
sd_bus_track *bus_track;
char **deserialized_clients;
JobResult result;
unsigned run_queue_idx;
/* If the job had a specific trigger that needs to be advertised (eg: a path unit), store it. */
ActivationDetails *activation_details;
bool installed:1;
bool in_run_queue:1;
bool matters_to_anchor:1;
bool in_dbus_queue:1;
bool sent_dbus_new_signal:1;
bool ignore_order:1;
bool irreversible:1;
bool in_gc_queue:1;
bool ref_by_private_bus:1;
};
Job* job_new(Unit *unit, JobType type);
Job* job_new_raw(Unit *unit);
void job_unlink(Job *job);
Job* job_free(Job *job);
Job* job_install(Job *j, bool refuse_late_merge);
int job_install_deserialized(Job *j);
void job_uninstall(Job *j);
void job_dump(Job *j, FILE *f, const char *prefix);
int job_serialize(Job *j, FILE *f);
int job_deserialize(Job *j, FILE *f);
int job_coldplug(Job *j);
JobDependency* job_dependency_new(Job *subject, Job *object, bool matters, bool conflicts);
void job_dependency_free(JobDependency *l);
int job_merge(Job *j, Job *other);
JobType job_type_lookup_merge(JobType a, JobType b) _pure_;
_pure_ static inline bool job_type_is_mergeable(JobType a, JobType b) {
return job_type_lookup_merge(a, b) >= 0;
}
_pure_ static inline bool job_type_is_conflicting(JobType a, JobType b) {
return a != JOB_NOP && b != JOB_NOP && !job_type_is_mergeable(a, b);
}
_pure_ static inline bool job_type_is_superset(JobType a, JobType b) {
/* Checks whether operation a is a "superset" of b in its actions */
if (b == JOB_NOP)
return true;
if (a == JOB_NOP)
return false;
return a == job_type_lookup_merge(a, b);
}
bool job_type_is_redundant(JobType a, UnitActiveState b) _pure_;
/* Collapses a state-dependent job type into a simpler type by observing
* the state of the unit which it is going to be applied to. */
JobType job_type_collapse(JobType t, Unit *u);
int job_type_merge_and_collapse(JobType *a, JobType b, Unit *u);
void job_add_to_run_queue(Job *j);
void job_add_to_dbus_queue(Job *j);
int job_start_timer(Job *j, bool job_running);
int job_run_and_invalidate(Job *j);
int job_finish_and_invalidate(Job *j, JobResult result, bool recursive, bool already);
char *job_dbus_path(Job *j);
void job_shutdown_magic(Job *j);
int job_get_timeout(Job *j, usec_t *ret);
bool job_may_gc(Job *j);
void job_add_to_gc_queue(Job *j);
int job_get_before(Job *j, Job*** ret);
int job_get_after(Job *j, Job*** ret);
DEFINE_TRIVIAL_CLEANUP_FUNC(Job*, job_free);
const char* job_type_to_string(JobType t) _const_;
JobType job_type_from_string(const char *s) _pure_;
const char* job_state_to_string(JobState t) _const_;
JobState job_state_from_string(const char *s) _pure_;
const char* job_mode_to_string(JobMode t) _const_;
JobMode job_mode_from_string(const char *s) _pure_;
const char* job_result_to_string(JobResult t) _const_;
JobResult job_result_from_string(const char *s) _pure_;
const char* job_type_to_access_method(JobType t);
int job_compare(Job *a, Job *b, UnitDependencyAtom assume_dep);
void job_set_activation_details(Job *j, ActivationDetails *info);
| 8,935 | 34.601594 | 123 |
h
|
null |
systemd-main/src/core/kill.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "kill.h"
#include "signal-util.h"
#include "string-table.h"
void kill_context_init(KillContext *c) {
assert(c);
c->kill_signal = SIGTERM;
/* restart_kill_signal is unset by default and we fall back to kill_signal */
c->final_kill_signal = SIGKILL;
c->send_sigkill = true;
c->send_sighup = false;
c->watchdog_signal = SIGABRT;
}
void kill_context_dump(KillContext *c, FILE *f, const char *prefix) {
assert(c);
prefix = strempty(prefix);
fprintf(f,
"%sKillMode: %s\n"
"%sKillSignal: SIG%s\n"
"%sRestartKillSignal: SIG%s\n"
"%sFinalKillSignal: SIG%s\n"
"%sSendSIGKILL: %s\n"
"%sSendSIGHUP: %s\n",
prefix, kill_mode_to_string(c->kill_mode),
prefix, signal_to_string(c->kill_signal),
prefix, signal_to_string(restart_kill_signal(c)),
prefix, signal_to_string(c->final_kill_signal),
prefix, yes_no(c->send_sigkill),
prefix, yes_no(c->send_sighup));
}
static const char* const kill_mode_table[_KILL_MODE_MAX] = {
[KILL_CONTROL_GROUP] = "control-group",
[KILL_PROCESS] = "process",
[KILL_MIXED] = "mixed",
[KILL_NONE] = "none",
};
DEFINE_STRING_TABLE_LOOKUP(kill_mode, KillMode);
static const char* const kill_who_table[_KILL_WHO_MAX] = {
[KILL_MAIN] = "main",
[KILL_CONTROL] = "control",
[KILL_ALL] = "all",
[KILL_MAIN_FAIL] = "main-fail",
[KILL_CONTROL_FAIL] = "control-fail",
[KILL_ALL_FAIL] = "all-fail",
};
DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);
| 1,823 | 31 | 85 |
c
|
null |
systemd-main/src/core/kill.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct KillContext KillContext;
#include <stdbool.h>
#include <stdio.h>
#include "macro.h"
typedef enum KillMode {
/* The kill mode is a property of a unit. */
KILL_CONTROL_GROUP = 0,
KILL_PROCESS,
KILL_MIXED,
KILL_NONE,
_KILL_MODE_MAX,
_KILL_MODE_INVALID = -EINVAL,
} KillMode;
struct KillContext {
KillMode kill_mode;
int kill_signal;
int restart_kill_signal;
int final_kill_signal;
int watchdog_signal;
bool send_sigkill;
bool send_sighup;
};
typedef enum KillWho {
/* Kill who is a property of an operation */
KILL_MAIN,
KILL_CONTROL,
KILL_ALL,
KILL_MAIN_FAIL,
KILL_CONTROL_FAIL,
KILL_ALL_FAIL,
_KILL_WHO_MAX,
_KILL_WHO_INVALID = -EINVAL,
} KillWho;
void kill_context_init(KillContext *c);
void kill_context_dump(KillContext *c, FILE *f, const char *prefix);
const char *kill_mode_to_string(KillMode k) _const_;
KillMode kill_mode_from_string(const char *s) _pure_;
const char *kill_who_to_string(KillWho k) _const_;
KillWho kill_who_from_string(const char *s) _pure_;
static inline int restart_kill_signal(const KillContext *c) {
if (c->restart_kill_signal != 0)
return c->restart_kill_signal;
return c->kill_signal;
}
| 1,420 | 23.929825 | 68 |
h
|
null |
systemd-main/src/core/kmod-setup.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "alloc-util.h"
#include "bus-util.h"
#include "capability-util.h"
#include "efi-api.h"
#include "fileio.h"
#include "kmod-setup.h"
#include "macro.h"
#include "recurse-dir.h"
#include "string-util.h"
#include "strv.h"
#include "virt.h"
#if HAVE_KMOD
#include "module-util.h"
static void systemd_kmod_log(
void *data,
int priority,
const char *file, int line,
const char *fn,
const char *format,
va_list args) {
/* library logging is enabled at debug only */
DISABLE_WARNING_FORMAT_NONLITERAL;
log_internalv(LOG_DEBUG, 0, file, line, fn, format, args);
REENABLE_WARNING;
}
static int match_modalias_recurse_dir_cb(
RecurseDirEvent event,
const char *path,
int dir_fd,
int inode_fd,
const struct dirent *de,
const struct statx *sx,
void *userdata) {
_cleanup_free_ char *alias = NULL;
char **modaliases = ASSERT_PTR(userdata);
int r;
if (event != RECURSE_DIR_ENTRY)
return RECURSE_DIR_CONTINUE;
if (de->d_type != DT_REG)
return RECURSE_DIR_CONTINUE;
if (!streq(de->d_name, "modalias"))
return RECURSE_DIR_CONTINUE;
r = read_one_line_file(path, &alias);
if (r < 0) {
log_debug_errno(r, "Failed to read %s, ignoring: %m", path);
return RECURSE_DIR_LEAVE_DIRECTORY;
}
if (startswith_strv(alias, modaliases))
return 1;
return RECURSE_DIR_LEAVE_DIRECTORY;
}
static bool has_virtio_rng(void) {
int r;
/* Directory traversal might be slow, hence let's do a cheap check first if it's even worth it */
if (detect_vm() == VIRTUALIZATION_NONE)
return false;
r = recurse_dir_at(
AT_FDCWD,
"/sys/devices/pci0000:00",
/* statx_mask= */ 0,
/* n_depth_max= */ 2,
RECURSE_DIR_ENSURE_TYPE,
match_modalias_recurse_dir_cb,
STRV_MAKE("pci:v00001AF4d00001005", "pci:v00001AF4d00001044"));
if (r < 0)
log_debug_errno(r, "Failed to determine whether host has virtio-rng device, ignoring: %m");
return r > 0;
}
static bool has_virtio_console(void) {
int r;
/* Directory traversal might be slow, hence let's do a cheap check first if it's even worth it */
if (detect_vm() == VIRTUALIZATION_NONE)
return false;
r = recurse_dir_at(
AT_FDCWD,
"/sys/devices/pci0000:00",
/* statx_mask= */ 0,
/* n_depth_max= */ 3,
RECURSE_DIR_ENSURE_TYPE,
match_modalias_recurse_dir_cb,
STRV_MAKE("virtio:d00000003v", "virtio:d0000000Bv"));
if (r < 0)
log_debug_errno(r, "Failed to determine whether host has virtio-console device, ignoring: %m");
return r > 0;
}
static bool has_virtio_vsock(void) {
int r;
/* Directory traversal might be slow, hence let's do a cheap check first if it's even worth it */
if (detect_vm() == VIRTUALIZATION_NONE)
return false;
r = recurse_dir_at(
AT_FDCWD,
"/sys/devices/pci0000:00",
/* statx_mask= */ 0,
/* n_depth_max= */ 3,
RECURSE_DIR_ENSURE_TYPE,
match_modalias_recurse_dir_cb,
STRV_MAKE("virtio:d00000013v"));
if (r < 0)
log_debug_errno(r, "Failed to determine whether host has virtio-vsock device, ignoring: %m");
return r > 0;
}
static bool in_qemu(void) {
return IN_SET(detect_vm(), VIRTUALIZATION_KVM, VIRTUALIZATION_QEMU);
}
#endif
int kmod_setup(void) {
#if HAVE_KMOD
static const struct {
const char *module;
const char *path;
bool warn_if_unavailable:1;
bool warn_if_module:1;
bool (*condition_fn)(void);
} kmod_table[] = {
/* This one we need to load explicitly, since auto-loading on use doesn't work
* before udev created the ghost device nodes, and we need it earlier than that. */
{ "autofs4", "/sys/class/misc/autofs", true, false, NULL },
/* This one we need to load explicitly, since auto-loading of IPv6 is not done when
* we try to configure ::1 on the loopback device. */
{ "ipv6", "/sys/module/ipv6", false, true, NULL },
/* This should never be a module */
{ "unix", "/proc/net/unix", true, true, NULL },
#if HAVE_LIBIPTC
/* netfilter is needed by networkd, nspawn among others, and cannot be autoloaded */
{ "ip_tables", "/proc/net/ip_tables_names", false, false, NULL },
#endif
/* virtio_rng would be loaded by udev later, but real entropy might be needed very early */
{ "virtio_rng", NULL, false, false, has_virtio_rng },
/* we want early logging to hvc consoles if possible, and make sure systemd-getty-generator
* can rely on all consoles being probed already.*/
{ "virtio_console", NULL, false, false, has_virtio_console },
/* Make sure we can send sd-notify messages over vsock as early as possible. */
{ "vmw_vsock_virtio_transport", NULL, false, false, has_virtio_vsock },
/* qemu_fw_cfg would be loaded by udev later, but we want to import credentials from it super early */
{ "qemu_fw_cfg", "/sys/firmware/qemu_fw_cfg", false, false, in_qemu },
/* dmi-sysfs is needed to import credentials from it super early */
{ "dmi-sysfs", "/sys/firmware/dmi/entries", false, false, NULL },
#if HAVE_TPM2
/* Make sure the tpm subsystem is available which ConditionSecurity=tpm2 depends on. */
{ "tpm", "/sys/class/tpmrm", false, false, efi_has_tpm2 },
#endif
};
_cleanup_(kmod_unrefp) struct kmod_ctx *ctx = NULL;
unsigned i;
if (have_effective_cap(CAP_SYS_MODULE) <= 0)
return 0;
for (i = 0; i < ELEMENTSOF(kmod_table); i++) {
if (kmod_table[i].path && access(kmod_table[i].path, F_OK) >= 0)
continue;
if (kmod_table[i].condition_fn && !kmod_table[i].condition_fn())
continue;
if (kmod_table[i].warn_if_module)
log_debug("Your kernel apparently lacks built-in %s support. Might be "
"a good idea to compile it in. We'll now try to work around "
"this by loading the module...", kmod_table[i].module);
if (!ctx) {
ctx = kmod_new(NULL, NULL);
if (!ctx)
return log_oom();
kmod_set_log_fn(ctx, systemd_kmod_log, NULL);
kmod_load_resources(ctx);
}
(void) module_load_and_warn(ctx, kmod_table[i].module, kmod_table[i].warn_if_unavailable);
}
#endif
return 0;
}
| 8,129 | 36.813953 | 118 |
c
|
null |
systemd-main/src/core/load-dropin.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "conf-parser.h"
#include "fs-util.h"
#include "load-dropin.h"
#include "load-fragment.h"
#include "log.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
#include "unit-name.h"
#include "unit.h"
static int process_deps(Unit *u, UnitDependency dependency, const char *dir_suffix) {
_cleanup_strv_free_ char **paths = NULL;
int r;
r = unit_file_find_dropin_paths(NULL,
u->manager->lookup_paths.search_path,
u->manager->unit_path_cache,
dir_suffix, NULL,
u->id, u->aliases,
&paths);
if (r < 0)
return r;
STRV_FOREACH(p, paths) {
_cleanup_free_ char *target = NULL;
const char *entry;
entry = basename(*p);
if (null_or_empty_path(*p) > 0) {
/* an error usually means an invalid symlink, which is not a mask */
log_unit_debug(u, "%s dependency on %s is masked by %s, ignoring.",
unit_dependency_to_string(dependency), entry, *p);
continue;
}
r = is_symlink(*p);
if (r < 0) {
log_unit_warning_errno(u, r, "%s dropin %s unreadable, ignoring: %m",
unit_dependency_to_string(dependency), *p);
continue;
}
if (r == 0) {
log_unit_warning(u, "%s dependency dropin %s is not a symlink, ignoring.",
unit_dependency_to_string(dependency), *p);
continue;
}
if (!unit_name_is_valid(entry, UNIT_NAME_ANY)) {
log_unit_warning(u, "%s dependency dropin %s is not a valid unit name, ignoring.",
unit_dependency_to_string(dependency), *p);
continue;
}
r = readlink_malloc(*p, &target);
if (r < 0) {
log_unit_warning_errno(u, r, "readlink(\"%s\") failed, ignoring: %m", *p);
continue;
}
/* We don't treat this as an error, especially because we didn't check this for a
* long time. Nevertheless, we warn, because such mismatch can be mighty confusing. */
r = unit_symlink_name_compatible(entry, basename(target), u->instance);
if (r < 0) {
log_unit_warning_errno(u, r, "Can't check if names %s and %s are compatible, ignoring: %m",
entry, basename(target));
continue;
}
if (r == 0)
log_unit_warning(u, "%s dependency dropin %s target %s has different name",
unit_dependency_to_string(dependency), *p, target);
r = unit_add_dependency_by_name(u, dependency, entry, true, UNIT_DEPENDENCY_FILE);
if (r < 0)
log_unit_warning_errno(u, r, "Cannot add %s dependency on %s, ignoring: %m",
unit_dependency_to_string(dependency), entry);
}
return 0;
}
int unit_load_dropin(Unit *u) {
_cleanup_strv_free_ char **l = NULL;
int r;
assert(u);
/* Load dependencies from .wants, .requires and .upholds directories */
r = process_deps(u, UNIT_WANTS, ".wants");
if (r < 0)
return r;
r = process_deps(u, UNIT_REQUIRES, ".requires");
if (r < 0)
return r;
r = process_deps(u, UNIT_UPHOLDS, ".upholds");
if (r < 0)
return r;
/* Load .conf dropins */
r = unit_find_dropin_paths(u, &l);
if (r <= 0)
return 0;
if (!u->dropin_paths)
u->dropin_paths = TAKE_PTR(l);
else {
r = strv_extend_strv(&u->dropin_paths, l, true);
if (r < 0)
return log_oom();
}
u->dropin_mtime = 0;
STRV_FOREACH(f, u->dropin_paths) {
struct stat st;
r = config_parse(u->id, *f, NULL,
UNIT_VTABLE(u)->sections,
config_item_perf_lookup, load_fragment_gperf_lookup,
0, u, &st);
if (r > 0)
u->dropin_mtime = MAX(u->dropin_mtime, timespec_load(&st.st_mtim));
}
return 0;
}
| 4,960 | 36.870229 | 115 |
c
|
null |
systemd-main/src/core/load-dropin.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "dropin.h"
#include "unit.h"
/* Read service data supplementary drop-in directories */
static inline int unit_find_dropin_paths(Unit *u, char ***paths) {
assert(u);
return unit_file_find_dropin_paths(NULL,
u->manager->lookup_paths.search_path,
u->manager->unit_path_cache,
".d", ".conf",
u->id, u->aliases,
paths);
}
int unit_load_dropin(Unit *u);
| 655 | 30.238095 | 80 |
h
|
null |
systemd-main/src/core/load-fragment.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "conf-parser.h"
#include "unit.h"
/* These functions are declared in the header to make them accessible to unit tests. */
bool contains_instance_specifier_superset(const char *s);
int unit_is_likely_recursive_template_dependency(Unit *u, const char *name, const char *format);
/* Config-parsing helpers relevant only for sources under src/core/ */
int parse_crash_chvt(const char *value, int *data);
int parse_confirm_spawn(const char *value, char **console);
int hashmap_put_credential(Hashmap **h, const char *id, const char *path, bool encrypted);
/* Read service data from .desktop file style configuration fragments */
int unit_load_fragment(Unit *u);
void unit_dump_config_items(FILE *f);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_deps);
CONFIG_PARSER_PROTOTYPE(config_parse_obsolete_unit_deps);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_string_printf);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_strv_printf);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_path_printf);
CONFIG_PARSER_PROTOTYPE(config_parse_colon_separated_paths);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_path_strv_printf);
CONFIG_PARSER_PROTOTYPE(config_parse_documentation);
CONFIG_PARSER_PROTOTYPE(config_parse_socket_listen);
CONFIG_PARSER_PROTOTYPE(config_parse_socket_protocol);
CONFIG_PARSER_PROTOTYPE(config_parse_socket_bind);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_nice);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_oom_score_adjust);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_coredump_filter);
CONFIG_PARSER_PROTOTYPE(config_parse_exec);
CONFIG_PARSER_PROTOTYPE(config_parse_service_timeout);
CONFIG_PARSER_PROTOTYPE(config_parse_service_timeout_abort);
CONFIG_PARSER_PROTOTYPE(config_parse_service_timeout_failure_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_service_type);
CONFIG_PARSER_PROTOTYPE(config_parse_service_exit_type);
CONFIG_PARSER_PROTOTYPE(config_parse_service_restart);
CONFIG_PARSER_PROTOTYPE(config_parse_service_restart_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_socket_bindtodevice);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_output);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_input);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_input_text);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_input_data);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_io_class);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_io_priority);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_cpu_sched_policy);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_cpu_sched_prio);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_cpu_affinity);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_mount_apivfs);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_secure_bits);
CONFIG_PARSER_PROTOTYPE(config_parse_root_image_options);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_root_hash);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_root_hash_sig);
CONFIG_PARSER_PROTOTYPE(config_parse_capability_set);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_mount_propagation_flag);
CONFIG_PARSER_PROTOTYPE(config_parse_timer);
CONFIG_PARSER_PROTOTYPE(config_parse_trigger_unit);
CONFIG_PARSER_PROTOTYPE(config_parse_path_spec);
CONFIG_PARSER_PROTOTYPE(config_parse_socket_service);
CONFIG_PARSER_PROTOTYPE(config_parse_service_sockets);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_env_file);
CONFIG_PARSER_PROTOTYPE(config_parse_ip_tos);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_condition_path);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_condition_string);
CONFIG_PARSER_PROTOTYPE(config_parse_kill_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_notify_access);
CONFIG_PARSER_PROTOTYPE(config_parse_emergency_action);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_requires_mounts_for);
CONFIG_PARSER_PROTOTYPE(config_parse_syscall_filter);
CONFIG_PARSER_PROTOTYPE(config_parse_syscall_archs);
CONFIG_PARSER_PROTOTYPE(config_parse_syscall_errno);
CONFIG_PARSER_PROTOTYPE(config_parse_syscall_log);
CONFIG_PARSER_PROTOTYPE(config_parse_environ);
CONFIG_PARSER_PROTOTYPE(config_parse_pass_environ);
CONFIG_PARSER_PROTOTYPE(config_parse_unset_environ);
CONFIG_PARSER_PROTOTYPE(config_parse_unit_slice);
CONFIG_PARSER_PROTOTYPE(config_parse_cg_weight);
CONFIG_PARSER_PROTOTYPE(config_parse_cg_cpu_weight);
CONFIG_PARSER_PROTOTYPE(config_parse_cpu_shares);
CONFIG_PARSER_PROTOTYPE(config_parse_memory_limit);
CONFIG_PARSER_PROTOTYPE(config_parse_tasks_max);
CONFIG_PARSER_PROTOTYPE(config_parse_delegate);
CONFIG_PARSER_PROTOTYPE(config_parse_delegate_subgroup);
CONFIG_PARSER_PROTOTYPE(config_parse_managed_oom_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_managed_oom_mem_pressure_limit);
CONFIG_PARSER_PROTOTYPE(config_parse_managed_oom_preference);
CONFIG_PARSER_PROTOTYPE(config_parse_device_policy);
CONFIG_PARSER_PROTOTYPE(config_parse_device_allow);
CONFIG_PARSER_PROTOTYPE(config_parse_io_device_latency);
CONFIG_PARSER_PROTOTYPE(config_parse_io_device_weight);
CONFIG_PARSER_PROTOTYPE(config_parse_io_limit);
CONFIG_PARSER_PROTOTYPE(config_parse_blockio_weight);
CONFIG_PARSER_PROTOTYPE(config_parse_blockio_device_weight);
CONFIG_PARSER_PROTOTYPE(config_parse_blockio_bandwidth);
CONFIG_PARSER_PROTOTYPE(config_parse_job_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_job_mode_isolate);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_selinux_context);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_apparmor_profile);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_smack_process_label);
CONFIG_PARSER_PROTOTYPE(config_parse_address_families);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_preserve_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_directories);
CONFIG_PARSER_PROTOTYPE(config_parse_set_credential);
CONFIG_PARSER_PROTOTYPE(config_parse_load_credential);
CONFIG_PARSER_PROTOTYPE(config_parse_import_credential);
CONFIG_PARSER_PROTOTYPE(config_parse_set_status);
CONFIG_PARSER_PROTOTYPE(config_parse_namespace_path_strv);
CONFIG_PARSER_PROTOTYPE(config_parse_temporary_filesystems);
CONFIG_PARSER_PROTOTYPE(config_parse_cpu_quota);
CONFIG_PARSER_PROTOTYPE(config_parse_allowed_cpuset);
CONFIG_PARSER_PROTOTYPE(config_parse_protect_home);
CONFIG_PARSER_PROTOTYPE(config_parse_protect_system);
CONFIG_PARSER_PROTOTYPE(config_parse_bus_name);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_utmp_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_working_directory);
CONFIG_PARSER_PROTOTYPE(config_parse_fdname);
CONFIG_PARSER_PROTOTYPE(config_parse_user_group_compat);
CONFIG_PARSER_PROTOTYPE(config_parse_user_group_strv_compat);
CONFIG_PARSER_PROTOTYPE(config_parse_restrict_namespaces);
CONFIG_PARSER_PROTOTYPE(config_parse_restrict_filesystems);
CONFIG_PARSER_PROTOTYPE(config_parse_bind_paths);
CONFIG_PARSER_PROTOTYPE(config_parse_exec_keyring_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_protect_proc);
CONFIG_PARSER_PROTOTYPE(config_parse_proc_subset);
CONFIG_PARSER_PROTOTYPE(config_parse_job_timeout_sec);
CONFIG_PARSER_PROTOTYPE(config_parse_job_running_timeout_sec);
CONFIG_PARSER_PROTOTYPE(config_parse_log_extra_fields);
CONFIG_PARSER_PROTOTYPE(config_parse_log_namespace);
CONFIG_PARSER_PROTOTYPE(config_parse_collect_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_pid_file);
CONFIG_PARSER_PROTOTYPE(config_parse_exit_status);
CONFIG_PARSER_PROTOTYPE(config_parse_disable_controllers);
CONFIG_PARSER_PROTOTYPE(config_parse_oom_policy);
CONFIG_PARSER_PROTOTYPE(config_parse_numa_policy);
CONFIG_PARSER_PROTOTYPE(config_parse_numa_mask);
CONFIG_PARSER_PROTOTYPE(config_parse_ip_filter_bpf_progs);
CONFIG_PARSER_PROTOTYPE(config_parse_cpu_affinity2);
CONFIG_PARSER_PROTOTYPE(config_parse_show_status);
CONFIG_PARSER_PROTOTYPE(config_parse_status_unit_format);
CONFIG_PARSER_PROTOTYPE(config_parse_output_restricted);
CONFIG_PARSER_PROTOTYPE(config_parse_crash_chvt);
CONFIG_PARSER_PROTOTYPE(config_parse_timeout_abort);
CONFIG_PARSER_PROTOTYPE(config_parse_swap_priority);
CONFIG_PARSER_PROTOTYPE(config_parse_mount_images);
CONFIG_PARSER_PROTOTYPE(config_parse_socket_timestamping);
CONFIG_PARSER_PROTOTYPE(config_parse_extension_images);
CONFIG_PARSER_PROTOTYPE(config_parse_bpf_foreign_program);
CONFIG_PARSER_PROTOTYPE(config_parse_cgroup_socket_bind);
CONFIG_PARSER_PROTOTYPE(config_parse_restrict_network_interfaces);
CONFIG_PARSER_PROTOTYPE(config_parse_watchdog_sec);
CONFIG_PARSER_PROTOTYPE(config_parse_tty_size);
CONFIG_PARSER_PROTOTYPE(config_parse_log_filter_patterns);
CONFIG_PARSER_PROTOTYPE(config_parse_open_file);
CONFIG_PARSER_PROTOTYPE(config_parse_memory_pressure_watch);
/* gperf prototypes */
const struct ConfigPerfItem* load_fragment_gperf_lookup(const char *key, GPERF_LEN_TYPE length);
extern const char load_fragment_gperf_nulstr[];
| 8,527 | 50.684848 | 96 |
h
|
null |
systemd-main/src/core/manager-dump.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "build.h"
#include "fd-util.h"
#include "fileio.h"
#include "hashmap.h"
#include "manager-dump.h"
#include "memstream-util.h"
#include "unit-serialize.h"
void manager_dump_jobs(Manager *s, FILE *f, char **patterns, const char *prefix) {
Job *j;
assert(s);
assert(f);
HASHMAP_FOREACH(j, s->jobs) {
if (!strv_fnmatch_or_empty(patterns, j->unit->id, FNM_NOESCAPE))
continue;
job_dump(j, f, prefix);
}
}
void manager_dump_units(Manager *s, FILE *f, char **patterns, const char *prefix) {
Unit *u;
const char *t;
assert(s);
assert(f);
HASHMAP_FOREACH_KEY(u, t, s->units) {
if (u->id != t)
continue;
if (!strv_fnmatch_or_empty(patterns, u->id, FNM_NOESCAPE))
continue;
unit_dump(u, f, prefix);
}
}
static void manager_dump_header(Manager *m, FILE *f, const char *prefix) {
/* NB: this is a debug interface for developers. It's not supposed to be machine readable or be
* stable between versions. We take the liberty to restructure it entirely between versions and
* add/remove fields at will. */
fprintf(f, "%sManager: systemd " STRINGIFY(PROJECT_VERSION) " (" GIT_VERSION ")\n", strempty(prefix));
fprintf(f, "%sFeatures: %s\n", strempty(prefix), systemd_features);
for (ManagerTimestamp q = 0; q < _MANAGER_TIMESTAMP_MAX; q++) {
const dual_timestamp *t = m->timestamps + q;
if (dual_timestamp_is_set(t))
fprintf(f, "%sTimestamp %s: %s\n",
strempty(prefix),
manager_timestamp_to_string(q),
timestamp_is_set(t->realtime) ? FORMAT_TIMESTAMP(t->realtime) :
FORMAT_TIMESPAN(t->monotonic, 1));
}
}
void manager_dump(Manager *m, FILE *f, char **patterns, const char *prefix) {
assert(m);
assert(f);
/* If no pattern is provided, dump the full manager state including the manager version, features and
* so on. Otherwise limit the dump to the units/jobs matching the specified patterns. */
if (!patterns)
manager_dump_header(m, f, prefix);
manager_dump_units(m, f, patterns, prefix);
manager_dump_jobs(m, f, patterns, prefix);
}
int manager_get_dump_string(Manager *m, char **patterns, char **ret) {
_cleanup_(memstream_done) MemStream ms = {};
FILE *f;
assert(m);
assert(ret);
f = memstream_init(&ms);
if (!f)
return -errno;
manager_dump(m, f, patterns, NULL);
return memstream_finalize(&ms, ret, NULL);
}
void manager_test_summary(Manager *m) {
assert(m);
printf("-> By units:\n");
manager_dump_units(m, stdout, /* patterns= */ NULL, "\t");
printf("-> By jobs:\n");
manager_dump_jobs(m, stdout, /* patterns= */ NULL, "\t");
}
| 3,208 | 30.15534 | 110 |
c
|
null |
systemd-main/src/core/mount.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct Mount Mount;
#include "kill.h"
#include "dynamic-user.h"
#include "unit.h"
typedef enum MountExecCommand {
MOUNT_EXEC_MOUNT,
MOUNT_EXEC_UNMOUNT,
MOUNT_EXEC_REMOUNT,
_MOUNT_EXEC_COMMAND_MAX,
_MOUNT_EXEC_COMMAND_INVALID = -EINVAL,
} MountExecCommand;
typedef enum MountResult {
MOUNT_SUCCESS,
MOUNT_FAILURE_RESOURCES, /* a bit of a misnomer, just our catch-all error for errnos we didn't expect */
MOUNT_FAILURE_TIMEOUT,
MOUNT_FAILURE_EXIT_CODE,
MOUNT_FAILURE_SIGNAL,
MOUNT_FAILURE_CORE_DUMP,
MOUNT_FAILURE_START_LIMIT_HIT,
MOUNT_FAILURE_PROTOCOL,
_MOUNT_RESULT_MAX,
_MOUNT_RESULT_INVALID = -EINVAL,
} MountResult;
typedef struct MountParameters {
char *what;
char *options;
char *fstype;
} MountParameters;
/* Used while looking for mount points that vanished or got added from/to /proc/self/mountinfo */
typedef enum MountProcFlags {
MOUNT_PROC_IS_MOUNTED = 1 << 0,
MOUNT_PROC_JUST_MOUNTED = 1 << 1,
MOUNT_PROC_JUST_CHANGED = 1 << 2,
} MountProcFlags;
struct Mount {
Unit meta;
char *where;
MountParameters parameters_proc_self_mountinfo;
MountParameters parameters_fragment;
bool from_proc_self_mountinfo:1;
bool from_fragment:1;
MountProcFlags proc_flags;
bool sloppy_options;
bool lazy_unmount;
bool force_unmount;
bool read_write_only;
MountResult result;
MountResult reload_result;
MountResult clean_result;
mode_t directory_mode;
usec_t timeout_usec;
ExecCommand exec_command[_MOUNT_EXEC_COMMAND_MAX];
ExecContext exec_context;
KillContext kill_context;
CGroupContext cgroup_context;
ExecRuntime *exec_runtime;
MountState state, deserialized_state;
ExecCommand* control_command;
MountExecCommand control_command_id;
pid_t control_pid;
sd_event_source *timer_event_source;
unsigned n_retry_umount;
};
extern const UnitVTable mount_vtable;
void mount_fd_event(Manager *m, int events);
const char* mount_exec_command_to_string(MountExecCommand i) _const_;
MountExecCommand mount_exec_command_from_string(const char *s) _pure_;
const char* mount_result_to_string(MountResult i) _const_;
MountResult mount_result_from_string(const char *s) _pure_;
DEFINE_CAST(MOUNT, Mount);
| 2,568 | 24.186275 | 112 |
h
|
null |
systemd-main/src/core/namespace.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/***
Copyright © 2016 Djalal Harouni
***/
typedef struct NamespaceInfo NamespaceInfo;
typedef struct BindMount BindMount;
typedef struct TemporaryFileSystem TemporaryFileSystem;
typedef struct MountImage MountImage;
#include <stdbool.h>
#include "dissect-image.h"
#include "fs-util.h"
#include "macro.h"
#include "namespace-util.h"
#include "string-util.h"
typedef enum ProtectHome {
PROTECT_HOME_NO,
PROTECT_HOME_YES,
PROTECT_HOME_READ_ONLY,
PROTECT_HOME_TMPFS,
_PROTECT_HOME_MAX,
_PROTECT_HOME_INVALID = -EINVAL,
} ProtectHome;
typedef enum ProtectSystem {
PROTECT_SYSTEM_NO,
PROTECT_SYSTEM_YES,
PROTECT_SYSTEM_FULL,
PROTECT_SYSTEM_STRICT,
_PROTECT_SYSTEM_MAX,
_PROTECT_SYSTEM_INVALID = -EINVAL,
} ProtectSystem;
typedef enum ProtectProc {
PROTECT_PROC_DEFAULT,
PROTECT_PROC_NOACCESS, /* hidepid=noaccess */
PROTECT_PROC_INVISIBLE, /* hidepid=invisible */
PROTECT_PROC_PTRACEABLE, /* hidepid=ptraceable */
_PROTECT_PROC_MAX,
_PROTECT_PROC_INVALID = -EINVAL,
} ProtectProc;
typedef enum ProcSubset {
PROC_SUBSET_ALL,
PROC_SUBSET_PID, /* subset=pid */
_PROC_SUBSET_MAX,
_PROC_SUBSET_INVALID = -EINVAL,
} ProcSubset;
struct NamespaceInfo {
bool ignore_protect_paths;
bool private_dev;
bool protect_control_groups;
bool protect_kernel_tunables;
bool protect_kernel_modules;
bool protect_kernel_logs;
bool mount_apivfs;
bool protect_hostname;
bool private_network;
bool private_ipc;
bool mount_nosuid;
ProtectHome protect_home;
ProtectSystem protect_system;
ProtectProc protect_proc;
ProcSubset proc_subset;
};
struct BindMount {
char *source;
char *destination;
bool read_only;
bool nosuid;
bool recursive;
bool ignore_enoent;
};
struct TemporaryFileSystem {
char *path;
char *options;
};
typedef enum MountImageType {
MOUNT_IMAGE_DISCRETE,
MOUNT_IMAGE_EXTENSION,
_MOUNT_IMAGE_TYPE_MAX,
_MOUNT_IMAGE_TYPE_INVALID = -EINVAL,
} MountImageType;
struct MountImage {
char *source;
char *destination; /* Unused if MountImageType == MOUNT_IMAGE_EXTENSION */
LIST_HEAD(MountOptions, mount_options);
bool ignore_enoent;
MountImageType type;
};
int setup_namespace(
const char *root_directory,
const char *root_image,
const MountOptions *root_image_options,
const ImagePolicy *root_image_policy,
const NamespaceInfo *ns_info,
char **read_write_paths,
char **read_only_paths,
char **inaccessible_paths,
char **exec_paths,
char **no_exec_paths,
char **empty_directories,
char **exec_dir_symlinks,
const BindMount *bind_mounts,
size_t n_bind_mounts,
const TemporaryFileSystem *temporary_filesystems,
size_t n_temporary_filesystems,
const MountImage *mount_images,
size_t n_mount_images,
const ImagePolicy *mount_image_policy,
const char *tmp_dir,
const char *var_tmp_dir,
const char *creds_path,
const char *log_namespace,
unsigned long mount_propagation_flag,
VeritySettings *verity,
const MountImage *extension_images,
size_t n_extension_images,
const ImagePolicy *extension_image_policy,
char **extension_directories,
const char *propagate_dir,
const char *incoming_dir,
const char *extension_dir,
const char *notify_socket,
char **error_path);
#define RUN_SYSTEMD_EMPTY "/run/systemd/empty"
static inline char* namespace_cleanup_tmpdir(char *p) {
PROTECT_ERRNO;
if (!streq_ptr(p, RUN_SYSTEMD_EMPTY))
(void) rmdir(p);
return mfree(p);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(char*, namespace_cleanup_tmpdir);
int setup_tmp_dirs(
const char *id,
char **tmp_dir,
char **var_tmp_dir);
int setup_shareable_ns(int ns_storage_socket[static 2], unsigned long nsflag);
int open_shareable_ns_path(int netns_storage_socket[static 2], const char *path, unsigned long nsflag);
const char* protect_home_to_string(ProtectHome p) _const_;
ProtectHome protect_home_from_string(const char *s) _pure_;
const char* protect_system_to_string(ProtectSystem p) _const_;
ProtectSystem protect_system_from_string(const char *s) _pure_;
const char* protect_proc_to_string(ProtectProc i) _const_;
ProtectProc protect_proc_from_string(const char *s) _pure_;
const char* proc_subset_to_string(ProcSubset i) _const_;
ProcSubset proc_subset_from_string(const char *s) _pure_;
void bind_mount_free_many(BindMount *b, size_t n);
int bind_mount_add(BindMount **b, size_t *n, const BindMount *item);
void temporary_filesystem_free_many(TemporaryFileSystem *t, size_t n);
int temporary_filesystem_add(TemporaryFileSystem **t, size_t *n,
const char *path, const char *options);
MountImage* mount_image_free_many(MountImage *m, size_t *n);
int mount_image_add(MountImage **m, size_t *n, const MountImage *item);
const char* namespace_type_to_string(NamespaceType t) _const_;
NamespaceType namespace_type_from_string(const char *s) _pure_;
bool ns_type_supported(NamespaceType type);
| 5,810 | 30.928571 | 103 |
h
|
null |
systemd-main/src/core/path.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct Path Path;
typedef struct PathSpec PathSpec;
typedef struct ActivationDetailsPath ActivationDetailsPath;
#include "unit.h"
typedef enum PathType {
PATH_EXISTS,
PATH_EXISTS_GLOB,
PATH_DIRECTORY_NOT_EMPTY,
PATH_CHANGED,
PATH_MODIFIED,
_PATH_TYPE_MAX,
_PATH_TYPE_INVALID = -EINVAL,
} PathType;
typedef struct PathSpec {
Unit *unit;
char *path;
sd_event_source *event_source;
LIST_FIELDS(struct PathSpec, spec);
PathType type;
int inotify_fd;
int primary_wd;
bool previous_exists;
} PathSpec;
int path_spec_watch(PathSpec *s, sd_event_io_handler_t handler);
void path_spec_unwatch(PathSpec *s);
int path_spec_fd_event(PathSpec *s, uint32_t events);
void path_spec_done(PathSpec *s);
static inline bool path_spec_owns_inotify_fd(PathSpec *s, int fd) {
return s->inotify_fd == fd;
}
typedef enum PathResult {
PATH_SUCCESS,
PATH_FAILURE_RESOURCES,
PATH_FAILURE_START_LIMIT_HIT,
PATH_FAILURE_UNIT_START_LIMIT_HIT,
PATH_FAILURE_TRIGGER_LIMIT_HIT,
_PATH_RESULT_MAX,
_PATH_RESULT_INVALID = -EINVAL,
} PathResult;
struct Path {
Unit meta;
LIST_HEAD(PathSpec, specs);
PathState state, deserialized_state;
bool make_directory;
mode_t directory_mode;
PathResult result;
RateLimit trigger_limit;
sd_event_source *trigger_notify_event_source;
};
struct ActivationDetailsPath {
ActivationDetails meta;
char *trigger_path_filename;
};
void path_free_specs(Path *p);
extern const UnitVTable path_vtable;
extern const ActivationDetailsVTable activation_details_path_vtable;
const char* path_type_to_string(PathType i) _const_;
PathType path_type_from_string(const char *s) _pure_;
const char* path_result_to_string(PathResult i) _const_;
PathResult path_result_from_string(const char *s) _pure_;
DEFINE_CAST(PATH, Path);
DEFINE_ACTIVATION_DETAILS_CAST(ACTIVATION_DETAILS_PATH, ActivationDetailsPath, PATH);
| 2,152 | 22.922222 | 85 |
h
|
null |
systemd-main/src/core/restrict-ifaces.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "fd-util.h"
#include "restrict-ifaces.h"
#include "netlink-util.h"
#if BPF_FRAMEWORK
/* libbpf, clang and llc compile time dependencies are satisfied */
#include "bpf-dlopen.h"
#include "bpf-link.h"
#include "bpf-util.h"
#include "bpf/restrict_ifaces/restrict-ifaces-skel.h"
static struct restrict_ifaces_bpf *restrict_ifaces_bpf_free(struct restrict_ifaces_bpf *obj) {
restrict_ifaces_bpf__destroy(obj);
return NULL;
}
DEFINE_TRIVIAL_CLEANUP_FUNC(struct restrict_ifaces_bpf *, restrict_ifaces_bpf_free);
static int prepare_restrict_ifaces_bpf(
Unit* u,
bool is_allow_list,
const Set *restrict_network_interfaces,
struct restrict_ifaces_bpf **ret_object) {
_cleanup_(restrict_ifaces_bpf_freep) struct restrict_ifaces_bpf *obj = NULL;
_cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
char *iface;
int r, map_fd;
assert(ret_object);
obj = restrict_ifaces_bpf__open();
if (!obj)
return log_unit_full_errno(u, u ? LOG_ERR : LOG_DEBUG, errno, "restrict-interfaces: Failed to open BPF object: %m");
r = sym_bpf_map__set_max_entries(obj->maps.sd_restrictif, MAX(set_size(restrict_network_interfaces), 1u));
if (r != 0)
return log_unit_full_errno(u, u ? LOG_ERR : LOG_WARNING, r,
"restrict-interfaces: Failed to resize BPF map '%s': %m",
sym_bpf_map__name(obj->maps.sd_restrictif));
obj->rodata->is_allow_list = is_allow_list;
r = restrict_ifaces_bpf__load(obj);
if (r != 0)
return log_unit_full_errno(u, u ? LOG_ERR : LOG_DEBUG, r, "restrict-interfaces: Failed to load BPF object: %m");
map_fd = sym_bpf_map__fd(obj->maps.sd_restrictif);
SET_FOREACH(iface, restrict_network_interfaces) {
uint8_t dummy = 0;
int ifindex;
ifindex = rtnl_resolve_interface(&rtnl, iface);
if (ifindex < 0) {
log_unit_warning_errno(u, ifindex,
"restrict-interfaces: Couldn't find index of network interface '%s', ignoring: %m",
iface);
continue;
}
if (sym_bpf_map_update_elem(map_fd, &ifindex, &dummy, BPF_ANY))
return log_unit_full_errno(u, u ? LOG_ERR : LOG_WARNING, errno,
"restrict-interfaces: Failed to update BPF map '%s' fd: %m",
sym_bpf_map__name(obj->maps.sd_restrictif));
}
*ret_object = TAKE_PTR(obj);
return 0;
}
int restrict_network_interfaces_supported(void) {
_cleanup_(restrict_ifaces_bpf_freep) struct restrict_ifaces_bpf *obj = NULL;
static int supported = -1;
int r;
if (supported >= 0)
return supported;
if (!cgroup_bpf_supported())
return (supported = false);
if (!compat_libbpf_probe_bpf_prog_type(BPF_PROG_TYPE_CGROUP_SKB, /*opts=*/NULL)) {
log_debug("restrict-interfaces: BPF program type cgroup_skb is not supported");
return (supported = false);
}
r = prepare_restrict_ifaces_bpf(NULL, true, NULL, &obj);
if (r < 0) {
log_debug_errno(r, "restrict-interfaces: Failed to load BPF object: %m");
return (supported = false);
}
return (supported = bpf_can_link_program(obj->progs.sd_restrictif_i));
}
static int restrict_network_interfaces_install_impl(Unit *u) {
_cleanup_(bpf_link_freep) struct bpf_link *egress_link = NULL, *ingress_link = NULL;
_cleanup_(restrict_ifaces_bpf_freep) struct restrict_ifaces_bpf *obj = NULL;
_cleanup_free_ char *cgroup_path = NULL;
_cleanup_close_ int cgroup_fd = -EBADF;
CGroupContext *cc;
int r;
cc = unit_get_cgroup_context(u);
if (!cc)
return 0;
r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, NULL, &cgroup_path);
if (r < 0)
return log_unit_error_errno(u, r, "restrict-interfaces: Failed to get cgroup path: %m");
if (!cc->restrict_network_interfaces)
return 0;
r = prepare_restrict_ifaces_bpf(u,
cc->restrict_network_interfaces_is_allow_list,
cc->restrict_network_interfaces,
&obj);
if (r < 0)
return r;
cgroup_fd = open(cgroup_path, O_RDONLY | O_CLOEXEC | O_DIRECTORY, 0);
if (cgroup_fd < 0)
return -errno;
ingress_link = sym_bpf_program__attach_cgroup(obj->progs.sd_restrictif_i, cgroup_fd);
r = sym_libbpf_get_error(ingress_link);
if (r != 0)
return log_unit_error_errno(u, r, "restrict-interfaces: Failed to create ingress cgroup link: %m");
egress_link = sym_bpf_program__attach_cgroup(obj->progs.sd_restrictif_e, cgroup_fd);
r = sym_libbpf_get_error(egress_link);
if (r != 0)
return log_unit_error_errno(u, r, "restrict-interfaces: Failed to create egress cgroup link: %m");
u->restrict_ifaces_ingress_bpf_link = TAKE_PTR(ingress_link);
u->restrict_ifaces_egress_bpf_link = TAKE_PTR(egress_link);
return 0;
}
int restrict_network_interfaces_install(Unit *u) {
int r = restrict_network_interfaces_install_impl(u);
fdset_close(u->initial_restric_ifaces_link_fds);
return r;
}
int serialize_restrict_network_interfaces(Unit *u, FILE *f, FDSet *fds) {
int r;
assert(u);
r = bpf_serialize_link(f, fds, "restrict-ifaces-bpf-fd", u->restrict_ifaces_ingress_bpf_link);
if (r < 0)
return r;
return bpf_serialize_link(f, fds, "restrict-ifaces-bpf-fd", u->restrict_ifaces_egress_bpf_link);
}
int restrict_network_interfaces_add_initial_link_fd(Unit *u, int fd) {
int r;
assert(u);
if (!u->initial_restric_ifaces_link_fds) {
u->initial_restric_ifaces_link_fds = fdset_new();
if (!u->initial_restric_ifaces_link_fds)
return log_oom();
}
r = fdset_put(u->initial_restric_ifaces_link_fds, fd);
if (r < 0)
return log_unit_error_errno(u, r,
"restrict-interfaces: Failed to put restrict-ifaces-bpf-fd %d to restored fdset: %m", fd);
return 0;
}
#else /* ! BPF_FRAMEWORK */
int restrict_network_interfaces_supported(void) {
return 0;
}
int restrict_network_interfaces_install(Unit *u) {
return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EOPNOTSUPP),
"restrict-interfaces: Failed to install; BPF programs built from source code are not supported: %m");
}
int serialize_restrict_network_interfaces(Unit *u, FILE *f, FDSet *fds) {
return 0;
}
int restrict_network_interfaces_add_initial_link_fd(Unit *u, int fd) {
return 0;
}
#endif
| 7,283 | 35.238806 | 132 |
c
|
null |
systemd-main/src/core/restrict-ifaces.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "fdset.h"
#include "unit.h"
typedef struct Unit Unit;
int restrict_network_interfaces_supported(void);
int restrict_network_interfaces_install(Unit *u);
int serialize_restrict_network_interfaces(Unit *u, FILE *f, FDSet *fds);
/* Add BPF link fd created before daemon-reload or daemon-reexec.
* FDs will be closed at the end of restrict_network_interfaces_install. */
int restrict_network_interfaces_add_initial_link_fd(Unit *u, int fd);
| 514 | 29.294118 | 75 |
h
|
null |
systemd-main/src/core/selinux-setup.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#if HAVE_SELINUX
#include <selinux/selinux.h>
#endif
#include "initrd-util.h"
#include "log.h"
#include "macro.h"
#include "selinux-setup.h"
#include "selinux-util.h"
#include "string-util.h"
#include "time-util.h"
#if HAVE_SELINUX
_printf_(2,3)
static int null_log(int type, const char *fmt, ...) {
return 0;
}
#endif
int mac_selinux_setup(bool *loaded_policy) {
#if HAVE_SELINUX
int enforce = 0;
usec_t before_load, after_load;
char *con;
int r;
bool initialized;
assert(loaded_policy);
/* Turn off all of SELinux' own logging, we want to do that */
selinux_set_callback(SELINUX_CB_LOG, (const union selinux_callback) { .func_log = null_log });
/* Don't load policy in the initrd if we don't appear to have it. For the real root, we check below
* if we've already loaded policy, and return gracefully. */
if (in_initrd() && access(selinux_path(), F_OK) < 0)
return 0;
/* Already initialized by somebody else? */
r = getcon_raw(&con);
/* getcon_raw can return 0, and still give us a NULL pointer if /proc/self/attr/current is
* empty. SELinux guarantees this won't happen, but that file isn't specific to SELinux, and may be
* provided by some other arbitrary LSM with different semantics. */
if (r == 0 && con) {
initialized = !streq(con, "kernel");
freecon(con);
} else
initialized = false;
/* Make sure we have no fds open while loading the policy and
* transitioning */
log_close();
/* Now load the policy */
before_load = now(CLOCK_MONOTONIC);
r = selinux_init_load_policy(&enforce);
if (r == 0) {
_cleanup_(mac_selinux_freep) char *label = NULL;
mac_selinux_retest();
/* Transition to the new context */
r = mac_selinux_get_create_label_from_exe(SYSTEMD_BINARY_PATH, &label);
if (r < 0 || !label) {
log_open();
log_error("Failed to compute init label, ignoring.");
} else {
r = setcon_raw(label);
log_open();
if (r < 0)
log_error("Failed to transition into init label '%s', ignoring.", label);
}
after_load = now(CLOCK_MONOTONIC);
log_info("Successfully loaded SELinux policy in %s.",
FORMAT_TIMESPAN(after_load - before_load, 0));
*loaded_policy = true;
} else {
log_open();
if (enforce > 0) {
if (!initialized)
return log_emergency_errno(SYNTHETIC_ERRNO(EIO),
"Failed to load SELinux policy.");
log_warning("Failed to load new SELinux policy. Continuing with old policy.");
} else
log_debug("Unable to load SELinux policy. Ignoring.");
}
#endif
return 0;
}
| 3,344 | 31.163462 | 108 |
c
|
null |
systemd-main/src/core/show-status.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "alloc-util.h"
#include "fd-util.h"
#include "io-util.h"
#include "parse-util.h"
#include "show-status.h"
#include "string-table.h"
#include "string-util.h"
#include "terminal-util.h"
static const char* const show_status_table[_SHOW_STATUS_MAX] = {
[SHOW_STATUS_NO] = "no",
[SHOW_STATUS_ERROR] = "error",
[SHOW_STATUS_AUTO] = "auto",
[SHOW_STATUS_TEMPORARY] = "temporary",
[SHOW_STATUS_YES] = "yes",
};
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(show_status, ShowStatus, SHOW_STATUS_YES);
int parse_show_status(const char *v, ShowStatus *ret) {
ShowStatus s;
assert(ret);
s = show_status_from_string(v);
if (s < 0 || s == SHOW_STATUS_TEMPORARY)
return -EINVAL;
*ret = s;
return 0;
}
int status_vprintf(const char *status, ShowStatusFlags flags, const char *format, va_list ap) {
static const char status_indent[] = " "; /* "[" STATUS "] " */
_cleanup_free_ char *s = NULL;
_cleanup_close_ int fd = -EBADF;
struct iovec iovec[7] = {};
int n = 0;
static bool prev_ephemeral;
assert(format);
/* This is independent of logging, as status messages are
* optional and go exclusively to the console. */
if (vasprintf(&s, format, ap) < 0)
return log_oom();
/* Before you ask: yes, on purpose we open/close the console for each status line we write individually. This
* is a good strategy to avoid PID 1 getting killed by the kernel's SAK concept (it doesn't fix this entirely,
* but minimizes the time window the kernel might end up killing PID 1 due to SAK). It also makes things easier
* for us so that we don't have to recover from hangups and suchlike triggered on the console. */
fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
if (fd < 0)
return fd;
if (FLAGS_SET(flags, SHOW_STATUS_ELLIPSIZE)) {
char *e;
size_t emax, sl;
int c;
c = fd_columns(fd);
if (c <= 0)
c = 80;
sl = status ? sizeof(status_indent)-1 : 0;
emax = c - sl - 1;
if (emax < 3)
emax = 3;
e = ellipsize(s, emax, 50);
if (e)
free_and_replace(s, e);
}
if (prev_ephemeral)
iovec[n++] = IOVEC_MAKE_STRING(ANSI_REVERSE_LINEFEED "\r" ANSI_ERASE_TO_END_OF_LINE);
if (status) {
if (!isempty(status)) {
iovec[n++] = IOVEC_MAKE_STRING("[");
iovec[n++] = IOVEC_MAKE_STRING(status);
iovec[n++] = IOVEC_MAKE_STRING("] ");
} else
iovec[n++] = IOVEC_MAKE_STRING(status_indent);
}
iovec[n++] = IOVEC_MAKE_STRING(s);
iovec[n++] = IOVEC_MAKE_STRING("\n");
if (prev_ephemeral && !FLAGS_SET(flags, SHOW_STATUS_EPHEMERAL))
iovec[n++] = IOVEC_MAKE_STRING(ANSI_ERASE_TO_END_OF_LINE);
prev_ephemeral = FLAGS_SET(flags, SHOW_STATUS_EPHEMERAL) ;
if (writev(fd, iovec, n) < 0)
return -errno;
return 0;
}
int status_printf(const char *status, ShowStatusFlags flags, const char *format, ...) {
va_list ap;
int r;
assert(format);
va_start(ap, format);
r = status_vprintf(status, flags, format, ap);
va_end(ap);
return r;
}
static const char* const status_unit_format_table[_STATUS_UNIT_FORMAT_MAX] = {
[STATUS_UNIT_FORMAT_NAME] = "name",
[STATUS_UNIT_FORMAT_DESCRIPTION] = "description",
[STATUS_UNIT_FORMAT_COMBINED] = "combined",
};
DEFINE_STRING_TABLE_LOOKUP(status_unit_format, StatusUnitFormat);
| 4,087 | 30.689922 | 119 |
c
|
null |
systemd-main/src/core/show-status.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "macro.h"
/* Manager status */
typedef enum ShowStatus {
SHOW_STATUS_NO, /* printing of status is disabled */
SHOW_STATUS_ERROR, /* only print errors */
SHOW_STATUS_AUTO, /* disabled but may flip to _TEMPORARY */
SHOW_STATUS_TEMPORARY, /* enabled temporarily, may flip back to _AUTO */
SHOW_STATUS_YES, /* printing of status is enabled */
_SHOW_STATUS_MAX,
_SHOW_STATUS_INVALID = -EINVAL,
} ShowStatus;
typedef enum ShowStatusFlags {
SHOW_STATUS_ELLIPSIZE = 1 << 0,
SHOW_STATUS_EPHEMERAL = 1 << 1,
} ShowStatusFlags;
typedef enum StatusUnitFormat {
STATUS_UNIT_FORMAT_NAME,
STATUS_UNIT_FORMAT_DESCRIPTION,
STATUS_UNIT_FORMAT_COMBINED,
_STATUS_UNIT_FORMAT_MAX,
_STATUS_UNIT_FORMAT_INVALID = -EINVAL,
} StatusUnitFormat;
static inline bool show_status_on(ShowStatus s) {
return IN_SET(s, SHOW_STATUS_TEMPORARY, SHOW_STATUS_YES);
}
ShowStatus show_status_from_string(const char *v) _const_;
const char* show_status_to_string(ShowStatus s) _pure_;
int parse_show_status(const char *v, ShowStatus *ret);
StatusUnitFormat status_unit_format_from_string(const char *v) _const_;
const char* status_unit_format_to_string(StatusUnitFormat s) _pure_;
int status_vprintf(const char *status, ShowStatusFlags flags, const char *format, va_list ap) _printf_(3,0);
int status_printf(const char *status, ShowStatusFlags flags, const char *format, ...) _printf_(3,4);
| 1,598 | 34.533333 | 108 |
h
|
null |
systemd-main/src/core/slice.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include "alloc-util.h"
#include "dbus-slice.h"
#include "dbus-unit.h"
#include "fd-util.h"
#include "log.h"
#include "serialize.h"
#include "slice.h"
#include "special.h"
#include "string-util.h"
#include "strv.h"
#include "unit-name.h"
#include "unit.h"
static const UnitActiveState state_translation_table[_SLICE_STATE_MAX] = {
[SLICE_DEAD] = UNIT_INACTIVE,
[SLICE_ACTIVE] = UNIT_ACTIVE
};
static void slice_init(Unit *u) {
assert(u);
assert(u->load_state == UNIT_STUB);
u->ignore_on_isolate = true;
}
static void slice_set_state(Slice *t, SliceState state) {
SliceState old_state;
assert(t);
if (t->state != state)
bus_unit_send_pending_change_signal(UNIT(t), false);
old_state = t->state;
t->state = state;
if (state != old_state)
log_debug("%s changed %s -> %s",
UNIT(t)->id,
slice_state_to_string(old_state),
slice_state_to_string(state));
unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], /* reload_success = */ true);
}
static int slice_add_parent_slice(Slice *s) {
Unit *u = UNIT(s);
_cleanup_free_ char *a = NULL;
int r;
assert(s);
if (UNIT_GET_SLICE(u))
return 0;
r = slice_build_parent_slice(u->id, &a);
if (r <= 0) /* 0 means root slice */
return r;
return unit_add_dependency_by_name(u, UNIT_IN_SLICE, a, true, UNIT_DEPENDENCY_IMPLICIT);
}
static int slice_add_default_dependencies(Slice *s) {
int r;
assert(s);
if (!UNIT(s)->default_dependencies)
return 0;
/* Make sure slices are unloaded on shutdown */
r = unit_add_two_dependencies_by_name(
UNIT(s),
UNIT_BEFORE, UNIT_CONFLICTS,
SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
if (r < 0)
return r;
return 0;
}
static int slice_verify(Slice *s) {
_cleanup_free_ char *parent = NULL;
int r;
assert(s);
assert(UNIT(s)->load_state == UNIT_LOADED);
if (!slice_name_is_valid(UNIT(s)->id))
return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Slice name %s is not valid. Refusing.", UNIT(s)->id);
r = slice_build_parent_slice(UNIT(s)->id, &parent);
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to determine parent slice: %m");
if (parent ? !unit_has_name(UNIT_GET_SLICE(UNIT(s)), parent) : !!UNIT_GET_SLICE(UNIT(s)))
return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Located outside of parent slice. Refusing.");
return 0;
}
static int slice_load_root_slice(Unit *u) {
assert(u);
if (!unit_has_name(u, SPECIAL_ROOT_SLICE))
return 0;
u->perpetual = true;
/* The root slice is a bit special. For example it is always running and cannot be terminated. Because of its
* special semantics we synthesize it here, instead of relying on the unit file on disk. */
u->default_dependencies = false;
if (!u->description)
u->description = strdup("Root Slice");
if (!u->documentation)
u->documentation = strv_new("man:systemd.special(7)");
return 1;
}
static int slice_load_system_slice(Unit *u) {
assert(u);
if (!MANAGER_IS_SYSTEM(u->manager))
return 0;
if (!unit_has_name(u, SPECIAL_SYSTEM_SLICE))
return 0;
u->perpetual = true;
/* The system slice is a bit special. For example it is always running and cannot be terminated. Because of its
* special semantics we synthesize it here, instead of relying on the unit file on disk. */
u->default_dependencies = false;
if (!u->description)
u->description = strdup("System Slice");
if (!u->documentation)
u->documentation = strv_new("man:systemd.special(7)");
return 1;
}
static int slice_load(Unit *u) {
Slice *s = SLICE(u);
int r;
assert(s);
assert(u->load_state == UNIT_STUB);
r = slice_load_root_slice(u);
if (r < 0)
return r;
r = slice_load_system_slice(u);
if (r < 0)
return r;
r = unit_load_fragment_and_dropin(u, false);
if (r < 0)
return r;
if (u->load_state != UNIT_LOADED)
return 0;
/* This is a new unit? Then let's add in some extras */
r = unit_patch_contexts(u);
if (r < 0)
return r;
r = slice_add_parent_slice(s);
if (r < 0)
return r;
r = slice_add_default_dependencies(s);
if (r < 0)
return r;
if (!u->description) {
_cleanup_free_ char *tmp = NULL;
r = unit_name_to_path(u->id, &tmp);
if (r >= 0) /* Failure is ignored… */
u->description = strjoin("Slice ", tmp);
}
return slice_verify(s);
}
static int slice_coldplug(Unit *u) {
Slice *t = SLICE(u);
assert(t);
assert(t->state == SLICE_DEAD);
if (t->deserialized_state != t->state)
slice_set_state(t, t->deserialized_state);
return 0;
}
static void slice_dump(Unit *u, FILE *f, const char *prefix) {
Slice *t = SLICE(u);
assert(t);
assert(f);
fprintf(f,
"%sSlice State: %s\n",
prefix, slice_state_to_string(t->state));
cgroup_context_dump(UNIT(t), f, prefix);
}
static int slice_start(Unit *u) {
Slice *t = SLICE(u);
int r;
assert(t);
assert(t->state == SLICE_DEAD);
r = unit_acquire_invocation_id(u);
if (r < 0)
return r;
(void) unit_realize_cgroup(u);
(void) unit_reset_accounting(u);
slice_set_state(t, SLICE_ACTIVE);
return 1;
}
static int slice_stop(Unit *u) {
Slice *t = SLICE(u);
assert(t);
assert(t->state == SLICE_ACTIVE);
/* We do not need to destroy the cgroup explicitly,
* unit_notify() will do that for us anyway. */
slice_set_state(t, SLICE_DEAD);
return 1;
}
static int slice_kill(Unit *u, KillWho who, int signo, int code, int value, sd_bus_error *error) {
return unit_kill_common(u, who, signo, code, value, -1, -1, error);
}
static int slice_serialize(Unit *u, FILE *f, FDSet *fds) {
Slice *s = SLICE(u);
assert(s);
assert(f);
assert(fds);
(void) serialize_item(f, "state", slice_state_to_string(s->state));
return 0;
}
static int slice_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
Slice *s = SLICE(u);
assert(u);
assert(key);
assert(value);
assert(fds);
if (streq(key, "state")) {
SliceState state;
state = slice_state_from_string(value);
if (state < 0)
log_debug("Failed to parse state value %s", value);
else
s->deserialized_state = state;
} else
log_debug("Unknown serialization key '%s'", key);
return 0;
}
_pure_ static UnitActiveState slice_active_state(Unit *u) {
assert(u);
return state_translation_table[SLICE(u)->state];
}
_pure_ static const char *slice_sub_state_to_string(Unit *u) {
assert(u);
return slice_state_to_string(SLICE(u)->state);
}
static int slice_make_perpetual(Manager *m, const char *name, Unit **ret) {
Unit *u;
int r;
assert(m);
assert(name);
u = manager_get_unit(m, name);
if (!u) {
r = unit_new_for_name(m, sizeof(Slice), name, &u);
if (r < 0)
return log_error_errno(r, "Failed to allocate the special %s unit: %m", name);
}
u->perpetual = true;
SLICE(u)->deserialized_state = SLICE_ACTIVE;
unit_add_to_load_queue(u);
unit_add_to_dbus_queue(u);
if (ret)
*ret = u;
return 0;
}
static void slice_enumerate_perpetual(Manager *m) {
Unit *u;
int r;
assert(m);
r = slice_make_perpetual(m, SPECIAL_ROOT_SLICE, &u);
if (r >= 0 && manager_owns_host_root_cgroup(m)) {
Slice *s = SLICE(u);
/* If we are managing the root cgroup then this means our root slice covers the whole system, which
* means the kernel will track CPU/tasks/memory for us anyway, and it is all available in /proc. Let's
* hence turn accounting on here, so that our APIs to query this data are available. */
s->cgroup_context.cpu_accounting = true;
s->cgroup_context.tasks_accounting = true;
s->cgroup_context.memory_accounting = true;
}
if (MANAGER_IS_SYSTEM(m))
(void) slice_make_perpetual(m, SPECIAL_SYSTEM_SLICE, NULL);
}
static bool slice_freezer_action_supported_by_children(Unit *s) {
Unit *member;
assert(s);
UNIT_FOREACH_DEPENDENCY(member, s, UNIT_ATOM_SLICE_OF) {
if (member->type == UNIT_SLICE &&
!slice_freezer_action_supported_by_children(member))
return false;
if (!UNIT_VTABLE(member)->freeze)
return false;
}
return true;
}
static int slice_freezer_action(Unit *s, FreezerAction action) {
Unit *member;
int r;
assert(s);
assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
if (action == FREEZER_FREEZE && !slice_freezer_action_supported_by_children(s)) {
log_unit_warning(s, "Requested freezer operation is not supported by all children of the slice");
return 0;
}
UNIT_FOREACH_DEPENDENCY(member, s, UNIT_ATOM_SLICE_OF) {
if (!member->cgroup_realized)
continue;
if (action == FREEZER_FREEZE)
r = UNIT_VTABLE(member)->freeze(member);
else if (UNIT_VTABLE(member)->thaw)
r = UNIT_VTABLE(member)->thaw(member);
else
/* Thawing is requested but no corresponding method is available, ignore. */
r = 0;
if (r < 0)
return r;
}
return unit_cgroup_freezer_action(s, action);
}
static int slice_freeze(Unit *s) {
assert(s);
return slice_freezer_action(s, FREEZER_FREEZE);
}
static int slice_thaw(Unit *s) {
assert(s);
return slice_freezer_action(s, FREEZER_THAW);
}
static bool slice_can_freeze(Unit *s) {
assert(s);
return slice_freezer_action_supported_by_children(s);
}
const UnitVTable slice_vtable = {
.object_size = sizeof(Slice),
.cgroup_context_offset = offsetof(Slice, cgroup_context),
.sections =
"Unit\0"
"Slice\0"
"Install\0",
.private_section = "Slice",
.can_transient = true,
.can_set_managed_oom = true,
.init = slice_init,
.load = slice_load,
.coldplug = slice_coldplug,
.dump = slice_dump,
.start = slice_start,
.stop = slice_stop,
.kill = slice_kill,
.freeze = slice_freeze,
.thaw = slice_thaw,
.can_freeze = slice_can_freeze,
.serialize = slice_serialize,
.deserialize_item = slice_deserialize_item,
.active_state = slice_active_state,
.sub_state_to_string = slice_sub_state_to_string,
.bus_set_property = bus_slice_set_property,
.bus_commit_properties = bus_slice_commit_properties,
.enumerate_perpetual = slice_enumerate_perpetual,
.status_message_formats = {
.finished_start_job = {
[JOB_DONE] = "Created slice %s.",
},
.finished_stop_job = {
[JOB_DONE] = "Removed slice %s.",
},
},
};
| 12,717 | 26.350538 | 133 |
c
|
null |
systemd-main/src/core/socket.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct Socket Socket;
typedef struct SocketPeer SocketPeer;
#include "mount.h"
#include "socket-util.h"
#include "unit.h"
typedef enum SocketExecCommand {
SOCKET_EXEC_START_PRE,
SOCKET_EXEC_START_CHOWN,
SOCKET_EXEC_START_POST,
SOCKET_EXEC_STOP_PRE,
SOCKET_EXEC_STOP_POST,
_SOCKET_EXEC_COMMAND_MAX,
_SOCKET_EXEC_COMMAND_INVALID = -EINVAL,
} SocketExecCommand;
typedef enum SocketType {
SOCKET_SOCKET,
SOCKET_FIFO,
SOCKET_SPECIAL,
SOCKET_MQUEUE,
SOCKET_USB_FUNCTION,
_SOCKET_TYPE_MAX,
_SOCKET_TYPE_INVALID = -EINVAL,
} SocketType;
typedef enum SocketResult {
SOCKET_SUCCESS,
SOCKET_FAILURE_RESOURCES,
SOCKET_FAILURE_TIMEOUT,
SOCKET_FAILURE_EXIT_CODE,
SOCKET_FAILURE_SIGNAL,
SOCKET_FAILURE_CORE_DUMP,
SOCKET_FAILURE_START_LIMIT_HIT,
SOCKET_FAILURE_TRIGGER_LIMIT_HIT,
SOCKET_FAILURE_SERVICE_START_LIMIT_HIT,
_SOCKET_RESULT_MAX,
_SOCKET_RESULT_INVALID = -EINVAL,
} SocketResult;
typedef struct SocketPort {
Socket *socket;
SocketType type;
int fd;
int *auxiliary_fds;
size_t n_auxiliary_fds;
SocketAddress address;
char *path;
sd_event_source *event_source;
LIST_FIELDS(struct SocketPort, port);
} SocketPort;
typedef enum SocketTimestamping {
SOCKET_TIMESTAMPING_OFF,
SOCKET_TIMESTAMPING_US, /* SO_TIMESTAMP */
SOCKET_TIMESTAMPING_NS, /* SO_TIMESTAMPNS */
_SOCKET_TIMESTAMPING_MAX,
_SOCKET_TIMESTAMPING_INVALID = -EINVAL,
} SocketTimestamping;
struct Socket {
Unit meta;
LIST_HEAD(SocketPort, ports);
Set *peers_by_address;
unsigned n_accepted;
unsigned n_connections;
unsigned n_refused;
unsigned max_connections;
unsigned max_connections_per_source;
unsigned backlog;
unsigned keep_alive_cnt;
usec_t timeout_usec;
usec_t keep_alive_time;
usec_t keep_alive_interval;
usec_t defer_accept;
ExecCommand* exec_command[_SOCKET_EXEC_COMMAND_MAX];
ExecContext exec_context;
KillContext kill_context;
CGroupContext cgroup_context;
ExecRuntime *exec_runtime;
/* For Accept=no sockets refers to the one service we'll
* activate. For Accept=yes sockets is either NULL, or filled
* to refer to the next service we spawn. */
UnitRef service;
SocketState state, deserialized_state;
sd_event_source *timer_event_source;
ExecCommand* control_command;
SocketExecCommand control_command_id;
pid_t control_pid;
mode_t directory_mode;
mode_t socket_mode;
SocketResult result;
SocketResult clean_result;
char **symlinks;
bool accept;
bool remove_on_stop;
bool writable;
bool flush_pending;
int socket_protocol;
/* Socket options */
bool keep_alive;
bool no_delay;
bool free_bind;
bool transparent;
bool broadcast;
bool pass_cred;
bool pass_sec;
bool pass_pktinfo;
SocketTimestamping timestamping;
/* Only for INET6 sockets: issue IPV6_V6ONLY sockopt */
SocketAddressBindIPv6Only bind_ipv6_only;
int priority;
int mark;
size_t receive_buffer;
size_t send_buffer;
int ip_tos;
int ip_ttl;
size_t pipe_size;
char *bind_to_device;
char *tcp_congestion;
bool reuse_port;
long mq_maxmsg;
long mq_msgsize;
char *smack;
char *smack_ip_in;
char *smack_ip_out;
bool selinux_context_from_net;
char *user, *group;
char *fdname;
RateLimit trigger_limit;
};
SocketPeer *socket_peer_ref(SocketPeer *p);
SocketPeer *socket_peer_unref(SocketPeer *p);
int socket_acquire_peer(Socket *s, int fd, SocketPeer **p);
DEFINE_TRIVIAL_CLEANUP_FUNC(SocketPeer*, socket_peer_unref);
/* Called from the service code when collecting fds */
int socket_collect_fds(Socket *s, int **fds);
/* Called from the service code when a per-connection service ended */
void socket_connection_unref(Socket *s);
SocketPort *socket_port_free(SocketPort *p);
DEFINE_TRIVIAL_CLEANUP_FUNC(SocketPort*, socket_port_free);
void socket_free_ports(Socket *s);
int socket_load_service_unit(Socket *s, int cfd, Unit **ret);
char *socket_fdname(Socket *s);
extern const UnitVTable socket_vtable;
const char* socket_exec_command_to_string(SocketExecCommand i) _const_;
SocketExecCommand socket_exec_command_from_string(const char *s) _pure_;
const char* socket_result_to_string(SocketResult i) _const_;
SocketResult socket_result_from_string(const char *s) _pure_;
const char* socket_port_type_to_string(SocketPort *p) _pure_;
SocketType socket_port_type_from_string(const char *p) _pure_;
const char* socket_timestamping_to_string(SocketTimestamping p) _const_;
SocketTimestamping socket_timestamping_from_string(const char *p) _pure_;
SocketTimestamping socket_timestamping_from_string_harder(const char *p) _pure_;
DEFINE_CAST(SOCKET, Socket);
| 5,352 | 25.765 | 80 |
h
|
null |
systemd-main/src/core/swap.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/***
Copyright © 2010 Maarten Lankhorst
***/
#include "sd-device.h"
#include "unit.h"
typedef struct Swap Swap;
typedef enum SwapExecCommand {
SWAP_EXEC_ACTIVATE,
SWAP_EXEC_DEACTIVATE,
_SWAP_EXEC_COMMAND_MAX,
_SWAP_EXEC_COMMAND_INVALID = -EINVAL,
} SwapExecCommand;
typedef enum SwapResult {
SWAP_SUCCESS,
SWAP_FAILURE_RESOURCES,
SWAP_FAILURE_TIMEOUT,
SWAP_FAILURE_EXIT_CODE,
SWAP_FAILURE_SIGNAL,
SWAP_FAILURE_CORE_DUMP,
SWAP_FAILURE_START_LIMIT_HIT,
_SWAP_RESULT_MAX,
_SWAP_RESULT_INVALID = -EINVAL,
} SwapResult;
typedef struct SwapParameters {
char *what;
char *options;
int priority;
bool priority_set;
} SwapParameters;
struct Swap {
Unit meta;
char *what;
/* If the device has already shown up, this is the device
* node, which might be different from what, due to
* symlinks */
char *devnode;
SwapParameters parameters_proc_swaps;
SwapParameters parameters_fragment;
bool from_proc_swaps:1;
bool from_fragment:1;
/* Used while looking for swaps that vanished or got added
* from/to /proc/swaps */
bool is_active:1;
bool just_activated:1;
SwapResult result;
SwapResult clean_result;
usec_t timeout_usec;
ExecCommand exec_command[_SWAP_EXEC_COMMAND_MAX];
ExecContext exec_context;
KillContext kill_context;
CGroupContext cgroup_context;
ExecRuntime *exec_runtime;
SwapState state, deserialized_state;
ExecCommand* control_command;
SwapExecCommand control_command_id;
pid_t control_pid;
sd_event_source *timer_event_source;
/* In order to be able to distinguish dependencies on
different device nodes we might end up creating multiple
devices for the same swap. We chain them up here. */
LIST_FIELDS(struct Swap, same_devnode);
};
extern const UnitVTable swap_vtable;
int swap_process_device_new(Manager *m, sd_device *dev);
int swap_process_device_remove(Manager *m, sd_device *dev);
const char* swap_exec_command_to_string(SwapExecCommand i) _const_;
SwapExecCommand swap_exec_command_from_string(const char *s) _pure_;
const char* swap_result_to_string(SwapResult i) _const_;
SwapResult swap_result_from_string(const char *s) _pure_;
DEFINE_CAST(SWAP, Swap);
| 2,543 | 24.69697 | 68 |
h
|
null |
systemd-main/src/core/timer.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct Timer Timer;
typedef struct ActivationDetailsTimer ActivationDetailsTimer;
#include "calendarspec.h"
#include "unit.h"
typedef enum TimerBase {
TIMER_ACTIVE,
TIMER_BOOT,
TIMER_STARTUP,
TIMER_UNIT_ACTIVE,
TIMER_UNIT_INACTIVE,
TIMER_CALENDAR,
_TIMER_BASE_MAX,
_TIMER_BASE_INVALID = -EINVAL,
} TimerBase;
typedef struct TimerValue {
TimerBase base;
bool disabled;
usec_t value; /* only for monotonic events */
CalendarSpec *calendar_spec; /* only for calendar events */
usec_t next_elapse;
LIST_FIELDS(struct TimerValue, value);
} TimerValue;
typedef enum TimerResult {
TIMER_SUCCESS,
TIMER_FAILURE_RESOURCES,
TIMER_FAILURE_START_LIMIT_HIT,
_TIMER_RESULT_MAX,
_TIMER_RESULT_INVALID = -EINVAL,
} TimerResult;
struct Timer {
Unit meta;
usec_t accuracy_usec;
usec_t random_usec;
LIST_HEAD(TimerValue, values);
usec_t next_elapse_realtime;
usec_t next_elapse_monotonic_or_boottime;
dual_timestamp last_trigger;
TimerState state, deserialized_state;
sd_event_source *monotonic_event_source;
sd_event_source *realtime_event_source;
TimerResult result;
bool persistent;
bool wake_system;
bool remain_after_elapse;
bool on_clock_change;
bool on_timezone_change;
bool fixed_random_delay;
char *stamp_path;
};
struct ActivationDetailsTimer {
ActivationDetails meta;
dual_timestamp last_trigger;
};
#define TIMER_MONOTONIC_CLOCK(t) ((t)->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC)
void timer_free_values(Timer *t);
extern const UnitVTable timer_vtable;
extern const ActivationDetailsVTable activation_details_timer_vtable;
const char *timer_base_to_string(TimerBase i) _const_;
TimerBase timer_base_from_string(const char *s) _pure_;
const char* timer_result_to_string(TimerResult i) _const_;
TimerResult timer_result_from_string(const char *s) _pure_;
DEFINE_CAST(TIMER, Timer);
DEFINE_ACTIVATION_DETAILS_CAST(ACTIVATION_DETAILS_TIMER, ActivationDetailsTimer, TIMER);
| 2,277 | 24.886364 | 92 |
h
|
null |
systemd-main/src/core/transaction.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct Transaction Transaction;
#include "hashmap.h"
#include "job.h"
#include "manager.h"
#include "unit.h"
struct Transaction {
/* Jobs to be added */
Hashmap *jobs; /* Unit object => Job object list 1:1 */
Job *anchor_job; /* the job the user asked for */
bool irreversible;
};
Transaction *transaction_new(bool irreversible);
Transaction *transaction_free(Transaction *tr);
Transaction *transaction_abort_and_free(Transaction *tr);
DEFINE_TRIVIAL_CLEANUP_FUNC(Transaction*, transaction_abort_and_free);
typedef enum TransactionAddFlags {
TRANSACTION_MATTERS = 1 << 0,
TRANSACTION_CONFLICTS = 1 << 1,
TRANSACTION_IGNORE_REQUIREMENTS = 1 << 2,
TRANSACTION_IGNORE_ORDER = 1 << 3,
/* Propagate a START job to other units like a RESTART */
TRANSACTION_PROPAGATE_START_AS_RESTART = 1 << 4,
/* Indicate that we're in the recursion for processing UNIT_ATOM_PROPAGATE_STOP_GRACEFUL units */
TRANSACTION_PROCESS_PROPAGATE_STOP_GRACEFUL = 1 << 5,
} TransactionAddFlags;
void transaction_add_propagate_reload_jobs(
Transaction *tr,
Unit *unit, Job *by,
TransactionAddFlags flags);
int transaction_add_job_and_dependencies(
Transaction *tr,
JobType type,
Unit *unit,
Job *by,
TransactionAddFlags flags,
sd_bus_error *e);
int transaction_activate(Transaction *tr, Manager *m, JobMode mode, Set *affected, sd_bus_error *e);
int transaction_add_isolate_jobs(Transaction *tr, Manager *m);
int transaction_add_triggering_jobs(Transaction *tr, Unit *u);
| 1,851 | 34.615385 | 105 |
h
|
null |
systemd-main/src/core/unit-dependency-atom.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "unit-dependency-atom.h"
static const UnitDependencyAtom atom_map[_UNIT_DEPENDENCY_MAX] = {
/* A table that maps high-level dependency types to low-level dependency "atoms". The latter actually
* describe specific facets of dependency behaviour. The former combine them into one user-facing
* concept. Atoms are a bit mask, though a bunch of dependency types have only a single bit set.
*
* Typically when the user configures a dependency they go via dependency type, but when we act on
* them we go by atom.
*
* NB: when you add a new dependency type here, make sure to also add one to the (best-effort)
* reverse table in unit_dependency_from_unique_atom() further down. */
[UNIT_REQUIRES] = UNIT_ATOM_PULL_IN_START |
UNIT_ATOM_RETROACTIVE_START_REPLACE |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE,
[UNIT_REQUISITE] = UNIT_ATOM_PULL_IN_VERIFY |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE,
[UNIT_WANTS] = UNIT_ATOM_PULL_IN_START_IGNORED |
UNIT_ATOM_RETROACTIVE_START_FAIL |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE,
[UNIT_BINDS_TO] = UNIT_ATOM_PULL_IN_START |
UNIT_ATOM_RETROACTIVE_START_REPLACE |
UNIT_ATOM_CANNOT_BE_ACTIVE_WITHOUT |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE,
[UNIT_PART_OF] = UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE,
[UNIT_UPHOLDS] = UNIT_ATOM_PULL_IN_START_IGNORED |
UNIT_ATOM_RETROACTIVE_START_REPLACE |
UNIT_ATOM_ADD_START_WHEN_UPHELD_QUEUE |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE,
[UNIT_REQUIRED_BY] = UNIT_ATOM_PROPAGATE_STOP |
UNIT_ATOM_PROPAGATE_RESTART |
UNIT_ATOM_PROPAGATE_START_FAILURE |
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED |
UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES,
[UNIT_REQUISITE_OF] = UNIT_ATOM_PROPAGATE_STOP |
UNIT_ATOM_PROPAGATE_RESTART |
UNIT_ATOM_PROPAGATE_START_FAILURE |
UNIT_ATOM_PROPAGATE_INACTIVE_START_AS_FAILURE |
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED |
UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES,
[UNIT_WANTED_BY] = UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES |
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED,
[UNIT_BOUND_BY] = UNIT_ATOM_RETROACTIVE_STOP_ON_STOP |
UNIT_ATOM_PROPAGATE_STOP |
UNIT_ATOM_PROPAGATE_RESTART |
UNIT_ATOM_PROPAGATE_START_FAILURE |
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED |
UNIT_ATOM_ADD_CANNOT_BE_ACTIVE_WITHOUT_QUEUE |
UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES,
[UNIT_UPHELD_BY] = UNIT_ATOM_START_STEADILY |
UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES |
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED,
[UNIT_CONSISTS_OF] = UNIT_ATOM_PROPAGATE_STOP |
UNIT_ATOM_PROPAGATE_RESTART,
[UNIT_CONFLICTS] = UNIT_ATOM_PULL_IN_STOP |
UNIT_ATOM_RETROACTIVE_STOP_ON_START,
[UNIT_CONFLICTED_BY] = UNIT_ATOM_PULL_IN_STOP_IGNORED |
UNIT_ATOM_RETROACTIVE_STOP_ON_START |
UNIT_ATOM_PROPAGATE_STOP_FAILURE,
[UNIT_PROPAGATES_STOP_TO] = UNIT_ATOM_RETROACTIVE_STOP_ON_STOP |
UNIT_ATOM_PROPAGATE_STOP_GRACEFUL,
/* These are simple dependency types: they consist of a single atom only */
[UNIT_ON_FAILURE] = UNIT_ATOM_ON_FAILURE,
[UNIT_ON_SUCCESS] = UNIT_ATOM_ON_SUCCESS,
[UNIT_ON_FAILURE_OF] = UNIT_ATOM_ON_FAILURE_OF,
[UNIT_ON_SUCCESS_OF] = UNIT_ATOM_ON_SUCCESS_OF,
[UNIT_BEFORE] = UNIT_ATOM_BEFORE,
[UNIT_AFTER] = UNIT_ATOM_AFTER,
[UNIT_TRIGGERS] = UNIT_ATOM_TRIGGERS,
[UNIT_TRIGGERED_BY] = UNIT_ATOM_TRIGGERED_BY,
[UNIT_PROPAGATES_RELOAD_TO] = UNIT_ATOM_PROPAGATES_RELOAD_TO,
[UNIT_JOINS_NAMESPACE_OF] = UNIT_ATOM_JOINS_NAMESPACE_OF,
[UNIT_REFERENCES] = UNIT_ATOM_REFERENCES,
[UNIT_REFERENCED_BY] = UNIT_ATOM_REFERENCED_BY,
[UNIT_IN_SLICE] = UNIT_ATOM_IN_SLICE,
[UNIT_SLICE_OF] = UNIT_ATOM_SLICE_OF,
/* These are dependency types without effect on our state engine. We maintain them only to make
* things discoverable/debuggable as they are the inverse dependencies to some of the above. As they
* have no effect of their own, they all map to no atoms at all, i.e. the value 0. */
[UNIT_RELOAD_PROPAGATED_FROM] = 0,
[UNIT_STOP_PROPAGATED_FROM] = 0,
};
UnitDependencyAtom unit_dependency_to_atom(UnitDependency d) {
if (d < 0)
return _UNIT_DEPENDENCY_ATOM_INVALID;
assert(d < _UNIT_DEPENDENCY_MAX);
return atom_map[d];
}
UnitDependency unit_dependency_from_unique_atom(UnitDependencyAtom atom) {
/* This is a "best-effort" function that maps the specified 'atom' mask to a dependency type that is
* is equal to or has a superset of bits set if that's uniquely possible. The idea is that this
* function is used when iterating through deps that have a specific atom: if there's exactly one
* dependency type of the specific atom we don't need iterate through all deps a unit has, but can
* pinpoint things directly.
*
* This function will return _UNIT_DEPENDENCY_INVALID in case the specified value is not known or not
* uniquely defined, i.e. there are multiple dependencies with the atom or the combination set. */
switch ((int64_t) atom) {
/* Note that we can't list UNIT_REQUIRES here since it's a true subset of UNIT_BINDS_TO, and
* hence its atom bits not uniquely mappable. */
case UNIT_ATOM_PULL_IN_VERIFY |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE:
case UNIT_ATOM_PULL_IN_VERIFY: /* a single dep type uses this atom */
return UNIT_REQUISITE;
case UNIT_ATOM_PULL_IN_START_IGNORED |
UNIT_ATOM_RETROACTIVE_START_FAIL |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE:
case UNIT_ATOM_RETROACTIVE_START_FAIL:
return UNIT_WANTS;
case UNIT_ATOM_PULL_IN_START |
UNIT_ATOM_RETROACTIVE_START_REPLACE |
UNIT_ATOM_CANNOT_BE_ACTIVE_WITHOUT |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE:
case UNIT_ATOM_CANNOT_BE_ACTIVE_WITHOUT:
return UNIT_BINDS_TO;
case UNIT_ATOM_PULL_IN_START_IGNORED |
UNIT_ATOM_RETROACTIVE_START_REPLACE |
UNIT_ATOM_ADD_START_WHEN_UPHELD_QUEUE |
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE |
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE:
case UNIT_ATOM_ADD_START_WHEN_UPHELD_QUEUE:
return UNIT_UPHOLDS;
case UNIT_ATOM_PROPAGATE_STOP |
UNIT_ATOM_PROPAGATE_RESTART |
UNIT_ATOM_PROPAGATE_START_FAILURE |
UNIT_ATOM_PROPAGATE_INACTIVE_START_AS_FAILURE |
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED |
UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES:
case UNIT_ATOM_PROPAGATE_INACTIVE_START_AS_FAILURE:
return UNIT_REQUISITE_OF;
case UNIT_ATOM_RETROACTIVE_STOP_ON_STOP |
UNIT_ATOM_PROPAGATE_STOP |
UNIT_ATOM_PROPAGATE_RESTART |
UNIT_ATOM_PROPAGATE_START_FAILURE |
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED |
UNIT_ATOM_ADD_CANNOT_BE_ACTIVE_WITHOUT_QUEUE |
UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES:
case UNIT_ATOM_ADD_CANNOT_BE_ACTIVE_WITHOUT_QUEUE:
return UNIT_BOUND_BY;
case UNIT_ATOM_START_STEADILY |
UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES |
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED:
case UNIT_ATOM_START_STEADILY:
return UNIT_UPHELD_BY;
case UNIT_ATOM_PULL_IN_STOP |
UNIT_ATOM_RETROACTIVE_STOP_ON_START:
case UNIT_ATOM_PULL_IN_STOP:
return UNIT_CONFLICTS;
case UNIT_ATOM_PULL_IN_STOP_IGNORED |
UNIT_ATOM_RETROACTIVE_STOP_ON_START |
UNIT_ATOM_PROPAGATE_STOP_FAILURE:
case UNIT_ATOM_PULL_IN_STOP_IGNORED:
case UNIT_ATOM_PROPAGATE_STOP_FAILURE:
return UNIT_CONFLICTED_BY;
case UNIT_ATOM_RETROACTIVE_STOP_ON_STOP |
UNIT_ATOM_PROPAGATE_STOP_GRACEFUL:
case UNIT_ATOM_PROPAGATE_STOP_GRACEFUL:
return UNIT_PROPAGATES_STOP_TO;
/* And now, the simple ones */
case UNIT_ATOM_ON_FAILURE:
return UNIT_ON_FAILURE;
case UNIT_ATOM_ON_SUCCESS:
return UNIT_ON_SUCCESS;
case UNIT_ATOM_ON_SUCCESS_OF:
return UNIT_ON_SUCCESS_OF;
case UNIT_ATOM_ON_FAILURE_OF:
return UNIT_ON_FAILURE_OF;
case UNIT_ATOM_BEFORE:
return UNIT_BEFORE;
case UNIT_ATOM_AFTER:
return UNIT_AFTER;
case UNIT_ATOM_TRIGGERS:
return UNIT_TRIGGERS;
case UNIT_ATOM_TRIGGERED_BY:
return UNIT_TRIGGERED_BY;
case UNIT_ATOM_PROPAGATES_RELOAD_TO:
return UNIT_PROPAGATES_RELOAD_TO;
case UNIT_ATOM_JOINS_NAMESPACE_OF:
return UNIT_JOINS_NAMESPACE_OF;
case UNIT_ATOM_REFERENCES:
return UNIT_REFERENCES;
case UNIT_ATOM_REFERENCED_BY:
return UNIT_REFERENCED_BY;
case UNIT_ATOM_IN_SLICE:
return UNIT_IN_SLICE;
case UNIT_ATOM_SLICE_OF:
return UNIT_SLICE_OF;
default:
return _UNIT_DEPENDENCY_INVALID;
}
}
| 11,772 | 45.718254 | 109 |
c
|
null |
systemd-main/src/core/unit-dependency-atom.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include "unit-def.h"
/* Flags that identify the various "atomic" behaviours a specific dependency type implies. Each dependency is
* a combination of one or more of these flags that define what they actually entail. */
typedef enum UnitDependencyAtom {
/* This unit pulls in the other unit as JOB_START job into the transaction, and if that doesn't work
* the transaction fails. */
UNIT_ATOM_PULL_IN_START = UINT64_C(1) << 0,
/* Similar, but if it doesn't work, ignore. */
UNIT_ATOM_PULL_IN_START_IGNORED = UINT64_C(1) << 1,
/* Pull in a JOB_VERIFY job into the transaction, i.e. pull in JOB_VERIFY rather than
* JOB_START. i.e. check the unit is started but don't pull it in. */
UNIT_ATOM_PULL_IN_VERIFY = UINT64_C(1) << 2,
/* Pull in a JOB_STOP job for the other job into transactions, and fail if that doesn't work. */
UNIT_ATOM_PULL_IN_STOP = UINT64_C(1) << 3,
/* Same, but don't fail, ignore it. */
UNIT_ATOM_PULL_IN_STOP_IGNORED = UINT64_C(1) << 4,
/* If our enters inactive state, add the other unit to the StopWhenUneeded= queue */
UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE = UINT64_C(1) << 5,
/* Pin the other unit i.e. ensure StopWhenUneeded= won't trigger for the other unit as long as we are
* not in inactive state */
UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED = UINT64_C(1) << 6,
/* Stop our unit if the other unit happens to inactive */
UNIT_ATOM_CANNOT_BE_ACTIVE_WITHOUT = UINT64_C(1) << 7,
/* If our unit enters inactive state, add the other unit to the BoundBy= queue */
UNIT_ATOM_ADD_CANNOT_BE_ACTIVE_WITHOUT_QUEUE = UINT64_C(1) << 8,
/* Start this unit whenever we find it inactive and the other unit active */
UNIT_ATOM_START_STEADILY = UINT64_C(1) << 9,
/* Whenever our unit becomes active, add other unit to start_when_upheld_queue */
UNIT_ATOM_ADD_START_WHEN_UPHELD_QUEUE = UINT64_C(1) << 10,
/* If our unit unexpectedly becomes active, retroactively start the other unit too, in "replace" job
* mode */
UNIT_ATOM_RETROACTIVE_START_REPLACE = UINT64_C(1) << 11,
/* Similar, but in "fail" job mode */
UNIT_ATOM_RETROACTIVE_START_FAIL = UINT64_C(1) << 12,
/* If our unit unexpectedly becomes active, retroactively stop the other unit too */
UNIT_ATOM_RETROACTIVE_STOP_ON_START = UINT64_C(1) << 13,
/* If our unit unexpectedly becomes inactive, retroactively stop the other unit too */
UNIT_ATOM_RETROACTIVE_STOP_ON_STOP = UINT64_C(1) << 14,
/* If a start job for this unit fails, propagate the failure to start job of other unit too */
UNIT_ATOM_PROPAGATE_START_FAILURE = UINT64_C(1) << 15,
/* If a stop job for this unit fails, propagate the failure to any stop job of the other unit too */
UNIT_ATOM_PROPAGATE_STOP_FAILURE = UINT64_C(1) << 16,
/* If our start job succeeded but the unit is inactive then (think: oneshot units), propagate this as
* failure to the other unit. */
UNIT_ATOM_PROPAGATE_INACTIVE_START_AS_FAILURE = UINT64_C(1) << 17,
/* When putting together a transaction, propagate JOB_STOP from our unit to the other. */
UNIT_ATOM_PROPAGATE_STOP = UINT64_C(1) << 18,
/* Like UNIT_ATOM_PROPAGATE_STOP, but enqueues a restart job if there's already a start job (avoids
* job type conflict). */
UNIT_ATOM_PROPAGATE_STOP_GRACEFUL = UINT64_C(1) << 19,
/* When putting together a transaction, propagate JOB_RESTART from our unit to the other. */
UNIT_ATOM_PROPAGATE_RESTART = UINT64_C(1) << 20,
/* Add the other unit to the default target dependency queue */
UNIT_ATOM_ADD_DEFAULT_TARGET_DEPENDENCY_QUEUE = UINT64_C(1) << 21,
/* Recheck default target deps on other units (which are target units) */
UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES = UINT64_C(1) << 22,
/* The remaining atoms map 1:1 to the equally named high-level deps */
UNIT_ATOM_ON_FAILURE = UINT64_C(1) << 23,
UNIT_ATOM_ON_SUCCESS = UINT64_C(1) << 24,
UNIT_ATOM_ON_FAILURE_OF = UINT64_C(1) << 25,
UNIT_ATOM_ON_SUCCESS_OF = UINT64_C(1) << 26,
UNIT_ATOM_BEFORE = UINT64_C(1) << 27,
UNIT_ATOM_AFTER = UINT64_C(1) << 28,
UNIT_ATOM_TRIGGERS = UINT64_C(1) << 29,
UNIT_ATOM_TRIGGERED_BY = UINT64_C(1) << 30,
UNIT_ATOM_PROPAGATES_RELOAD_TO = UINT64_C(1) << 31,
UNIT_ATOM_JOINS_NAMESPACE_OF = UINT64_C(1) << 32,
UNIT_ATOM_REFERENCES = UINT64_C(1) << 33,
UNIT_ATOM_REFERENCED_BY = UINT64_C(1) << 34,
UNIT_ATOM_IN_SLICE = UINT64_C(1) << 35,
UNIT_ATOM_SLICE_OF = UINT64_C(1) << 36,
_UNIT_DEPENDENCY_ATOM_MAX = (UINT64_C(1) << 37) - 1,
_UNIT_DEPENDENCY_ATOM_INVALID = -EINVAL,
} UnitDependencyAtom;
UnitDependencyAtom unit_dependency_to_atom(UnitDependency d);
UnitDependency unit_dependency_from_unique_atom(UnitDependencyAtom atom);
| 5,812 | 61.505376 | 109 |
h
|
null |
systemd-main/src/core/unit-printf.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "creds-util.h"
#include "env-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "unit.h"
int unit_name_printf(const Unit *u, const char* text, char **ret);
int unit_full_printf_full(const Unit *u, const char *text, size_t max_length, char **ret);
static inline int unit_full_printf(const Unit *u, const char *text, char **ret) {
return unit_full_printf_full(u, text, LONG_LINE_MAX, ret);
}
static inline int unit_path_printf(const Unit *u, const char *text, char **ret) {
return unit_full_printf_full(u, text, PATH_MAX-1, ret);
}
static inline int unit_fd_printf(const Unit *u, const char *text, char **ret) {
return unit_full_printf_full(u, text, FDNAME_MAX, ret);
}
static inline int unit_cred_printf(const Unit *u, const char *text, char **ret) {
return unit_full_printf_full(u, text, CREDENTIAL_NAME_MAX, ret);
}
static inline int unit_env_printf(const Unit *u, const char *text, char **ret) {
return unit_full_printf_full(u, text, sc_arg_max(), ret);
}
| 1,078 | 38.962963 | 90 |
h
|
null |
systemd-main/src/core/bpf/restrict_fs/restrict-fs-skel.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* The SPDX header above is actually correct in claiming this was
* LGPL-2.1-or-later, because it is. Since the kernel doesn't consider that
* compatible with GPL we will claim this to be GPL however, which should be
* fine given that LGPL-2.1-or-later downgrades to GPL if needed.
*/
/* libbpf is used via dlopen(), so rename symbols */
#define bpf_object__open_skeleton sym_bpf_object__open_skeleton
#define bpf_object__load_skeleton sym_bpf_object__load_skeleton
#define bpf_object__destroy_skeleton sym_bpf_object__destroy_skeleton
#include "bpf/restrict_fs/restrict-fs.skel.h"
| 638 | 41.6 | 76 |
h
|
null |
systemd-main/src/core/bpf/restrict_fs/restrict-fs.bpf.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* The SPDX header above is actually correct in claiming this was
* LGPL-2.1-or-later, because it is. Since the kernel doesn't consider that
* compatible with GPL we will claim this to be GPL however, which should be
* fine given that LGPL-2.1-or-later downgrades to GPL if needed.
*/
#include <linux/types.h>
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
struct super_block {
unsigned long int s_magic;
} __attribute__((preserve_access_index));
struct inode {
struct super_block *i_sb;
} __attribute__((preserve_access_index));
struct file {
struct inode *f_inode;
} __attribute__((preserve_access_index));
/*
* max_entries is set from user space with the bpf_map__set_max_entries helper.
* */
struct {
__uint(type, BPF_MAP_TYPE_HASH_OF_MAPS);
__type(key, uint64_t); /* cgroup ID */
__type(value, uint32_t); /* fs magic set */
} cgroup_hash SEC(".maps");
SEC("lsm/file_open")
int BPF_PROG(restrict_filesystems, struct file *file, int ret)
{
unsigned long raw_magic_number;
uint64_t cgroup_id;
uint32_t *value, *magic_map, magic_number, zero = 0, *is_allow;
/* ret is the return value from the previous BPF program or 0 if it's
* the first hook */
if (ret != 0)
return ret;
BPF_CORE_READ_INTO(&raw_magic_number, file, f_inode, i_sb, s_magic);
/* super_block.s_magic is unsigned long, but magic_map keys are
* uint32_t. Using s_magic as-is would fail on big-endian systems,
* which have 64-bit unsigned long. So cast it. */
magic_number = (uint32_t)raw_magic_number;
cgroup_id = bpf_get_current_cgroup_id();
magic_map = bpf_map_lookup_elem(&cgroup_hash, &cgroup_id);
if (!magic_map)
return 0;
is_allow = bpf_map_lookup_elem(magic_map, &zero);
if (!is_allow)
/* Malformed map, it doesn't include whether it's an allow list
* or a deny list. Allow. */
return 0;
if (*is_allow) {
/* Allow-list: Allow access only if magic_number present in inner map */
if (!bpf_map_lookup_elem(magic_map, &magic_number))
return -EPERM;
} else {
/* Deny-list: Allow access only if magic_number is not present in inner map */
if (bpf_map_lookup_elem(magic_map, &magic_number))
return -EPERM;
}
return 0;
}
static const char _license[] SEC("license") = "GPL";
| 2,744 | 32.072289 | 94 |
c
|
null |
systemd-main/src/core/bpf/restrict_ifaces/restrict-ifaces-skel.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* The SPDX header above is actually correct in claiming this was
* LGPL-2.1-or-later, because it is. Since the kernel doesn't consider that
* compatible with GPL we will claim this to be GPL however, which should be
* fine given that LGPL-2.1-or-later downgrades to GPL if needed.
*/
/* libbpf is used via dlopen(), so rename symbols */
#define bpf_object__open_skeleton sym_bpf_object__open_skeleton
#define bpf_object__load_skeleton sym_bpf_object__load_skeleton
#define bpf_object__destroy_skeleton sym_bpf_object__destroy_skeleton
#include "bpf/restrict_ifaces/restrict-ifaces.skel.h"
| 646 | 42.133333 | 76 |
h
|
null |
systemd-main/src/core/bpf/restrict_ifaces/restrict-ifaces.bpf.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* <linux/bpf.h> must precede <bpf/bpf_helpers.h> due to integer types
* in bpf helpers signatures.
*/
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
const volatile __u8 is_allow_list = 0;
/* Map containing the network interfaces indexes.
* The interpretation of the map depends on the value of is_allow_list.
*/
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__type(key, __u32);
__type(value, __u8);
} sd_restrictif SEC(".maps");
#define DROP 0
#define PASS 1
static __always_inline int restrict_network_interfaces_impl(const struct __sk_buff *sk) {
__u32 zero = 0, ifindex;
__u8 *lookup_result;
ifindex = sk->ifindex;
lookup_result = bpf_map_lookup_elem(&sd_restrictif, &ifindex);
if (is_allow_list) {
/* allow-list: let the packet pass if iface in the list */
if (lookup_result)
return PASS;
} else {
/* deny-list: let the packet pass if iface *not* in the list */
if (!lookup_result)
return PASS;
}
return DROP;
}
SEC("cgroup_skb/egress")
int sd_restrictif_e(const struct __sk_buff *sk) {
return restrict_network_interfaces_impl(sk);
}
SEC("cgroup_skb/ingress")
int sd_restrictif_i(const struct __sk_buff *sk) {
return restrict_network_interfaces_impl(sk);
}
static const char _license[] SEC("license") = "LGPL-2.1-or-later";
| 1,505 | 27.415094 | 89 |
c
|
null |
systemd-main/src/core/bpf/socket_bind/socket-bind-api.bpf.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* The SPDX header above is actually correct in claiming this was
* LGPL-2.1-or-later, because it is. Since the kernel doesn't consider that
* compatible with GPL we will claim this to be GPL however, which should be
* fine given that LGPL-2.1-or-later downgrades to GPL if needed.
*/
#include <linux/types.h>
/*
* Bind rule is matched with socket fields accessible to cgroup/bind{4,6} hook
* through bpf_sock_addr struct.
* 'address_family' is expected to be one of AF_UNSPEC, AF_INET or AF_INET6.
* Matching by family is bypassed for rules with AF_UNSPEC set, which makes the
* rest of a rule applicable for both IPv4 and IPv6 addresses.
* If matching by family is either successful or bypassed, a rule and a socket
* are matched by ip protocol.
* If 'protocol' is 0, matching is bypassed.
* 'nr_ports' and 'port_min' fields specify a set of ports to match a user port
* with.
* If 'nr_ports' is 0, matching by port is bypassed, making that rule applicable
* for all possible ports, e.g. [1, 65535] range. Thus a rule with
* 'address_family', 'protocol' and 'nr_ports' equal to AF_UNSPEC, 0 and 0
* correspondingly forms 'allow any' or 'deny any' cases.
* For positive 'nr_ports', a user_port lying in a range from 'port_min' to'
* 'port_min' + 'nr_ports' exclusively is considered to be a match. 'nr_ports'
* equalling to 1 forms a rule for a single port.
* Ports are in host order.
*
* Examples:
* AF_UNSPEC, 1, 0, 7777: match IPv4 and IPv6 addresses with 7777 user port;
*
* AF_INET, 1023, 0, 1: match IPv4 addresses with user port in [1, 1023]
* range inclusively;
*
* AF_INET6, 0, 0, 0: match IPv6 addresses;
*
* AF_UNSPEC, 0, 0, 0: match IPv4 and IPv6 addresses;
*
* AF_INET6, IPPROTO_TCP, 0, 0: match IPv6/TCP addresses.
*/
struct socket_bind_rule {
__u32 address_family;
__u32 protocol;
__u16 nr_ports;
__u16 port_min;
};
#define SOCKET_BIND_MAX_RULES 128
| 1,987 | 37.230769 | 80 |
h
|
null |
systemd-main/src/core/bpf/socket_bind/socket-bind-skel.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* The SPDX header above is actually correct in claiming this was
* LGPL-2.1-or-later, because it is. Since the kernel doesn't consider that
* compatible with GPL we will claim this to be GPL however, which should be
* fine given that LGPL-2.1-or-later downgrades to GPL if needed.
*/
/* libbpf is used via dlopen(), so rename symbols */
#define bpf_object__open_skeleton sym_bpf_object__open_skeleton
#define bpf_object__load_skeleton sym_bpf_object__load_skeleton
#define bpf_object__destroy_skeleton sym_bpf_object__destroy_skeleton
#include "bpf/socket_bind/socket-bind.skel.h"
| 638 | 41.6 | 76 |
h
|
null |
systemd-main/src/core/bpf/socket_bind/socket-bind.bpf.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* The SPDX header above is actually correct in claiming this was
* LGPL-2.1-or-later, because it is. Since the kernel doesn't consider that
* compatible with GPL we will claim this to be GPL however, which should be
* fine given that LGPL-2.1-or-later downgrades to GPL if needed.
*/
#include "socket-bind-api.bpf.h"
/* <linux/types.h> must precede <bpf/bpf_helpers.h> due to
* <bpf/bpf_helpers.h> does not depend from type header by design.
*/
#include <linux/types.h>
#include <bpf/bpf_endian.h>
#include <bpf/bpf_helpers.h>
#include <linux/bpf.h>
#include <netinet/in.h>
#include <stdbool.h>
/*
* max_entries is set from user space with bpf_map__set_max_entries helper.
*/
struct socket_bind_map_t {
__uint(type, BPF_MAP_TYPE_ARRAY);
__type(key, __u32);
__type(value, struct socket_bind_rule);
};
enum socket_bind_action {
SOCKET_BIND_DENY = 0,
SOCKET_BIND_ALLOW = 1,
};
struct socket_bind_map_t sd_bind_allow SEC(".maps");
struct socket_bind_map_t sd_bind_deny SEC(".maps");
static __always_inline bool match_af(
__u8 address_family, const struct socket_bind_rule *r) {
return r->address_family == AF_UNSPEC || address_family == r->address_family;
}
static __always_inline bool match_protocol(
__u32 protocol, const struct socket_bind_rule *r) {
return r->protocol == 0 || r->protocol == protocol;
}
static __always_inline bool match_user_port(
__u16 port, const struct socket_bind_rule *r) {
return r->nr_ports == 0 ||
(port >= r->port_min && port < r->port_min + (__u32) r->nr_ports);
}
static __always_inline bool match(
__u8 address_family,
__u32 protocol,
__u16 port,
const struct socket_bind_rule *r) {
return match_af(address_family, r) &&
match_protocol(protocol, r) &&
match_user_port(port, r);
}
static __always_inline bool match_rules(
struct bpf_sock_addr *ctx,
struct socket_bind_map_t *rules) {
volatile __u32 user_port = ctx->user_port;
__u16 port = (__u16)bpf_ntohs(user_port);
for (__u32 i = 0; i < SOCKET_BIND_MAX_RULES; ++i) {
const __u32 key = i;
const struct socket_bind_rule *rule = bpf_map_lookup_elem(rules, &key);
/* Lookup returns NULL if iterator is advanced past the last
* element put in the map. */
if (!rule)
break;
if (match(ctx->user_family, ctx->protocol, port, rule))
return true;
}
return false;
}
static __always_inline int bind_socket(struct bpf_sock_addr *ctx) {
if (match_rules(ctx, &sd_bind_allow))
return SOCKET_BIND_ALLOW;
if (match_rules(ctx, &sd_bind_deny))
return SOCKET_BIND_DENY;
return SOCKET_BIND_ALLOW;
}
SEC("cgroup/bind4")
int sd_bind4(struct bpf_sock_addr *ctx) {
if (ctx->user_family != AF_INET || ctx->family != AF_INET)
return SOCKET_BIND_ALLOW;
return bind_socket(ctx);
}
SEC("cgroup/bind6")
int sd_bind6(struct bpf_sock_addr *ctx) {
if (ctx->user_family != AF_INET6 || ctx->family != AF_INET6)
return SOCKET_BIND_ALLOW;
return bind_socket(ctx);
}
char _license[] SEC("license") = "GPL";
| 3,499 | 30.25 | 87 |
c
|
null |
systemd-main/src/coredump/coredump-vacuum.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/statvfs.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "alloc-util.h"
#include "coredump-vacuum.h"
#include "dirent-util.h"
#include "fd-util.h"
#include "fs-util.h"
#include "hashmap.h"
#include "macro.h"
#include "memory-util.h"
#include "stat-util.h"
#include "string-util.h"
#include "time-util.h"
#include "user-util.h"
#define DEFAULT_MAX_USE_LOWER (uint64_t) (1ULL*1024ULL*1024ULL) /* 1 MiB */
#define DEFAULT_MAX_USE_UPPER (uint64_t) (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
#define DEFAULT_KEEP_FREE_UPPER (uint64_t) (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
#define DEFAULT_KEEP_FREE (uint64_t) (1024ULL*1024ULL) /* 1 MB */
typedef struct VacuumCandidate {
unsigned n_files;
char *oldest_file;
usec_t oldest_mtime;
} VacuumCandidate;
static VacuumCandidate* vacuum_candidate_free(VacuumCandidate *c) {
if (!c)
return NULL;
free(c->oldest_file);
return mfree(c);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(VacuumCandidate*, vacuum_candidate_free);
static Hashmap* vacuum_candidate_hashmap_free(Hashmap *h) {
return hashmap_free_with_destructor(h, vacuum_candidate_free);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(Hashmap*, vacuum_candidate_hashmap_free);
static int uid_from_file_name(const char *filename, uid_t *uid) {
const char *p, *e, *u;
p = startswith(filename, "core.");
if (!p)
return -EINVAL;
/* Skip the comm field */
p = strchr(p, '.');
if (!p)
return -EINVAL;
p++;
/* Find end up UID */
e = strchr(p, '.');
if (!e)
return -EINVAL;
u = strndupa_safe(p, e - p);
return parse_uid(u, uid);
}
static bool vacuum_necessary(int fd, uint64_t sum, uint64_t keep_free, uint64_t max_use) {
uint64_t fs_size = 0, fs_free = UINT64_MAX;
struct statvfs sv;
assert(fd >= 0);
if (fstatvfs(fd, &sv) >= 0) {
fs_size = sv.f_frsize * sv.f_blocks;
fs_free = sv.f_frsize * sv.f_bfree;
}
if (max_use == UINT64_MAX) {
if (fs_size > 0) {
max_use = PAGE_ALIGN(fs_size / 10); /* 10% */
if (max_use > DEFAULT_MAX_USE_UPPER)
max_use = DEFAULT_MAX_USE_UPPER;
if (max_use < DEFAULT_MAX_USE_LOWER)
max_use = DEFAULT_MAX_USE_LOWER;
} else
max_use = DEFAULT_MAX_USE_LOWER;
} else
max_use = PAGE_ALIGN(max_use);
if (max_use > 0 && sum > max_use)
return true;
if (keep_free == UINT64_MAX) {
if (fs_size > 0) {
keep_free = PAGE_ALIGN((fs_size * 3) / 20); /* 15% */
if (keep_free > DEFAULT_KEEP_FREE_UPPER)
keep_free = DEFAULT_KEEP_FREE_UPPER;
} else
keep_free = DEFAULT_KEEP_FREE;
} else
keep_free = PAGE_ALIGN(keep_free);
if (keep_free > 0 && fs_free < keep_free)
return true;
return false;
}
int coredump_vacuum(int exclude_fd, uint64_t keep_free, uint64_t max_use) {
_cleanup_closedir_ DIR *d = NULL;
struct stat exclude_st;
int r;
if (keep_free == 0 && max_use == 0)
return 0;
if (exclude_fd >= 0) {
if (fstat(exclude_fd, &exclude_st) < 0)
return log_error_errno(errno, "Failed to fstat(): %m");
}
/* This algorithm will keep deleting the oldest file of the
* user with the most coredumps until we are back in the size
* limits. Note that vacuuming for journal files is different,
* because we rely on rate-limiting of the messages there,
* to avoid being flooded. */
d = opendir("/var/lib/systemd/coredump");
if (!d) {
if (errno == ENOENT)
return 0;
return log_error_errno(errno, "Can't open coredump directory: %m");
}
for (;;) {
_cleanup_(vacuum_candidate_hashmap_freep) Hashmap *h = NULL;
VacuumCandidate *worst = NULL;
uint64_t sum = 0;
rewinddir(d);
FOREACH_DIRENT(de, d, goto fail) {
VacuumCandidate *c;
struct stat st;
uid_t uid;
usec_t t;
r = uid_from_file_name(de->d_name, &uid);
if (r < 0)
continue;
if (fstatat(dirfd(d), de->d_name, &st, AT_NO_AUTOMOUNT|AT_SYMLINK_NOFOLLOW) < 0) {
if (errno == ENOENT)
continue;
log_warning_errno(errno, "Failed to stat /var/lib/systemd/coredump/%s: %m", de->d_name);
continue;
}
if (!S_ISREG(st.st_mode))
continue;
if (exclude_fd >= 0 && stat_inode_same(&exclude_st, &st))
continue;
r = hashmap_ensure_allocated(&h, NULL);
if (r < 0)
return log_oom();
t = timespec_load(&st.st_mtim);
c = hashmap_get(h, UID_TO_PTR(uid));
if (c) {
if (t < c->oldest_mtime) {
char *n;
n = strdup(de->d_name);
if (!n)
return log_oom();
free_and_replace(c->oldest_file, n);
c->oldest_mtime = t;
}
} else {
_cleanup_(vacuum_candidate_freep) VacuumCandidate *n = NULL;
n = new0(VacuumCandidate, 1);
if (!n)
return log_oom();
n->oldest_file = strdup(de->d_name);
if (!n->oldest_file)
return log_oom();
n->oldest_mtime = t;
r = hashmap_put(h, UID_TO_PTR(uid), n);
if (r < 0)
return log_oom();
c = TAKE_PTR(n);
}
c->n_files++;
if (!worst ||
worst->n_files < c->n_files ||
(worst->n_files == c->n_files && c->oldest_mtime < worst->oldest_mtime))
worst = c;
sum += st.st_blocks * 512;
}
if (!worst)
break;
r = vacuum_necessary(dirfd(d), sum, keep_free, max_use);
if (r <= 0)
return r;
r = unlinkat_deallocate(dirfd(d), worst->oldest_file, 0);
if (r == -ENOENT)
continue;
if (r < 0)
return log_error_errno(r, "Failed to remove file %s: %m", worst->oldest_file);
log_info("Removed old coredump %s.", worst->oldest_file);
}
return 0;
fail:
return log_error_errno(errno, "Failed to read directory: %m");
}
| 8,024 | 31.755102 | 120 |
c
|
null |
systemd-main/src/cryptenroll/cryptenroll-pkcs11.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "cryptenroll-pkcs11.h"
#include "hexdecoct.h"
#include "json.h"
#include "memory-util.h"
#include "openssl-util.h"
#include "pkcs11-util.h"
#include "random-util.h"
int enroll_pkcs11(
struct crypt_device *cd,
const void *volume_key,
size_t volume_key_size,
const char *uri) {
_cleanup_(erase_and_freep) void *decrypted_key = NULL;
_cleanup_(erase_and_freep) char *base64_encoded = NULL;
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
_cleanup_free_ char *keyslot_as_string = NULL;
size_t decrypted_key_size, encrypted_key_size;
_cleanup_free_ void *encrypted_key = NULL;
_cleanup_(X509_freep) X509 *cert = NULL;
ssize_t base64_encoded_size;
const char *node;
EVP_PKEY *pkey;
int keyslot, r;
assert_se(cd);
assert_se(volume_key);
assert_se(volume_key_size > 0);
assert_se(uri);
assert_se(node = crypt_get_device_name(cd));
r = pkcs11_acquire_certificate(uri, "volume enrollment operation", "drive-harddisk", &cert, NULL);
if (r < 0)
return r;
pkey = X509_get0_pubkey(cert);
if (!pkey)
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to extract public key from X.509 certificate.");
r = rsa_pkey_to_suitable_key_size(pkey, &decrypted_key_size);
if (r < 0)
return log_error_errno(r, "Failed to determine RSA public key size.");
log_debug("Generating %zu bytes random key.", decrypted_key_size);
decrypted_key = malloc(decrypted_key_size);
if (!decrypted_key)
return log_oom();
r = crypto_random_bytes(decrypted_key, decrypted_key_size);
if (r < 0)
return log_error_errno(r, "Failed to generate random key: %m");
r = rsa_encrypt_bytes(pkey, decrypted_key, decrypted_key_size, &encrypted_key, &encrypted_key_size);
if (r < 0)
return log_error_errno(r, "Failed to encrypt key: %m");
/* Let's base64 encode the key to use, for compat with homed (and it's easier to type it in by
* keyboard, if that might ever end up being necessary.) */
base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
if (base64_encoded_size < 0)
return log_error_errno(base64_encoded_size, "Failed to base64 encode secret key: %m");
r = cryptsetup_set_minimal_pbkdf(cd);
if (r < 0)
return log_error_errno(r, "Failed to set minimal PBKDF: %m");
keyslot = crypt_keyslot_add_by_volume_key(
cd,
CRYPT_ANY_SLOT,
volume_key,
volume_key_size,
base64_encoded,
base64_encoded_size);
if (keyslot < 0)
return log_error_errno(keyslot, "Failed to add new PKCS#11 key to %s: %m", node);
if (asprintf(&keyslot_as_string, "%i", keyslot) < 0)
return log_oom();
r = json_build(&v,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-pkcs11")),
JSON_BUILD_PAIR("keyslots", JSON_BUILD_ARRAY(JSON_BUILD_STRING(keyslot_as_string))),
JSON_BUILD_PAIR("pkcs11-uri", JSON_BUILD_STRING(uri)),
JSON_BUILD_PAIR("pkcs11-key", JSON_BUILD_BASE64(encrypted_key, encrypted_key_size))));
if (r < 0)
return log_error_errno(r, "Failed to prepare PKCS#11 JSON token object: %m");
r = cryptsetup_add_token_json(cd, v);
if (r < 0)
return log_error_errno(r, "Failed to add PKCS#11 JSON token to LUKS2 header: %m");
log_info("New PKCS#11 token enrolled as key slot %i.", keyslot);
return keyslot;
}
| 4,101 | 39.613861 | 125 |
c
|
null |
systemd-main/src/cryptenroll/cryptenroll-pkcs11.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
#include "cryptsetup-util.h"
#include "log.h"
#if HAVE_P11KIT && HAVE_OPENSSL
int enroll_pkcs11(struct crypt_device *cd, const void *volume_key, size_t volume_key_size, const char *uri);
#else
static inline int enroll_pkcs11(struct crypt_device *cd, const void *volume_key, size_t volume_key_size, const char *uri) {
return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"PKCS#11 key enrollment not supported.");
}
#endif
| 547 | 31.235294 | 123 |
h
|
null |
systemd-main/src/cryptenroll/cryptenroll-recovery.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "cryptenroll-recovery.h"
#include "glyph-util.h"
#include "json.h"
#include "memory-util.h"
#include "qrcode-util.h"
#include "recovery-key.h"
#include "terminal-util.h"
int enroll_recovery(
struct crypt_device *cd,
const void *volume_key,
size_t volume_key_size) {
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
_cleanup_(erase_and_freep) char *password = NULL;
_cleanup_free_ char *keyslot_as_string = NULL;
int keyslot, r, q;
const char *node;
assert_se(cd);
assert_se(volume_key);
assert_se(volume_key_size > 0);
assert_se(node = crypt_get_device_name(cd));
r = make_recovery_key(&password);
if (r < 0)
return log_error_errno(r, "Failed to generate recovery key: %m");
r = cryptsetup_set_minimal_pbkdf(cd);
if (r < 0)
return log_error_errno(r, "Failed to set minimal PBKDF: %m");
keyslot = crypt_keyslot_add_by_volume_key(
cd,
CRYPT_ANY_SLOT,
volume_key,
volume_key_size,
password,
strlen(password));
if (keyslot < 0)
return log_error_errno(keyslot, "Failed to add new recovery key to %s: %m", node);
fflush(stdout);
fprintf(stderr,
"A secret recovery key has been generated for this volume:\n\n"
" %s%s%s",
emoji_enabled() ? special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY) : "",
emoji_enabled() ? " " : "",
ansi_highlight());
fflush(stderr);
fputs(password, stdout);
fflush(stdout);
fputs(ansi_normal(), stderr);
fflush(stderr);
fputc('\n', stdout);
fflush(stdout);
fputs("\nPlease save this secret recovery key at a secure location. It may be used to\n"
"regain access to the volume if the other configured access credentials have\n"
"been lost or forgotten. The recovery key may be entered in place of a password\n"
"whenever authentication is requested.\n", stderr);
fflush(stderr);
(void) print_qrcode(stderr, "You may optionally scan the recovery key off screen", password);
if (asprintf(&keyslot_as_string, "%i", keyslot) < 0) {
r = log_oom();
goto rollback;
}
r = json_build(&v,
JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-recovery")),
JSON_BUILD_PAIR("keyslots", JSON_BUILD_ARRAY(JSON_BUILD_STRING(keyslot_as_string)))));
if (r < 0) {
log_error_errno(r, "Failed to prepare recovery key JSON token object: %m");
goto rollback;
}
r = cryptsetup_add_token_json(cd, v);
if (r < 0) {
log_error_errno(r, "Failed to add recovery JSON token to LUKS2 header: %m");
goto rollback;
}
log_info("New recovery key enrolled as key slot %i.", keyslot);
return keyslot;
rollback:
q = crypt_keyslot_destroy(cd, keyslot);
if (q < 0)
log_debug_errno(q, "Unable to remove key slot we just added again, can't rollback, sorry: %m");
return r;
}
| 3,544 | 33.754902 | 125 |
c
|
null |
systemd-main/src/cryptenroll/cryptenroll.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
typedef enum EnrollType {
ENROLL_PASSWORD,
ENROLL_RECOVERY,
ENROLL_PKCS11,
ENROLL_FIDO2,
ENROLL_TPM2,
_ENROLL_TYPE_MAX,
_ENROLL_TYPE_INVALID = -EINVAL,
} EnrollType;
typedef enum UnlockType {
UNLOCK_PASSWORD,
UNLOCK_KEYFILE,
UNLOCK_FIDO2,
_UNLOCK_TYPE_MAX,
_UNLOCK_TYPE_INVALID = -EINVAL,
} UnlockType;
typedef enum WipeScope {
WIPE_EXPLICIT, /* only wipe the listed slots */
WIPE_ALL, /* wipe all slots */
WIPE_EMPTY_PASSPHRASE, /* wipe slots with empty passphrases plus listed slots */
_WIPE_SCOPE_MAX,
_WIPE_SCOPE_INVALID = -EINVAL,
} WipeScope;
const char* enroll_type_to_string(EnrollType t);
EnrollType enroll_type_from_string(const char *s);
const char* luks2_token_type_to_string(EnrollType t);
EnrollType luks2_token_type_from_string(const char *s);
| 1,006 | 26.216216 | 89 |
h
|
null |
systemd-main/src/cryptsetup/cryptsetup-keyfile.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "cryptsetup-keyfile.h"
#include "fileio.h"
#include "path-util.h"
#include "strv.h"
int find_key_file(
const char *key_file,
char **search_path,
const char *bindname,
void **ret_key,
size_t *ret_key_size) {
int r;
assert(key_file);
assert(ret_key);
assert(ret_key_size);
if (strv_isempty(search_path) || path_is_absolute(key_file)) {
r = read_full_file_full(
AT_FDCWD, key_file, UINT64_MAX, SIZE_MAX,
READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
bindname,
(char**) ret_key, ret_key_size);
if (r == -E2BIG)
return log_error_errno(r, "Key file '%s' too large.", key_file);
if (r < 0)
return log_error_errno(r, "Failed to load key file '%s': %m", key_file);
return 1;
}
STRV_FOREACH(i, search_path) {
_cleanup_free_ char *joined = NULL;
joined = path_join(*i, key_file);
if (!joined)
return log_oom();
r = read_full_file_full(
AT_FDCWD, joined, UINT64_MAX, SIZE_MAX,
READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
bindname,
(char**) ret_key, ret_key_size);
if (r >= 0)
return 1;
if (r == -E2BIG) {
log_warning_errno(r, "Key file '%s' too large, ignoring.", key_file);
continue;
}
if (r != -ENOENT)
return log_error_errno(r, "Failed to load key file '%s': %m", key_file);
}
/* Search path supplied, but file not found, report by returning NULL, but not failing */
*ret_key = NULL;
*ret_key_size = 0;
return 0;
}
| 2,253 | 34.777778 | 119 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-pkcs11.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <p11-kit/p11-kit.h>
#include <p11-kit/uri.h>
#include "alloc-util.h"
#include "ask-password-api.h"
#include "cryptsetup-pkcs11.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "hexdecoct.h"
#include "json.h"
#include "macro.h"
#include "memory-util.h"
#include "parse-util.h"
#include "pkcs11-util.h"
#include "random-util.h"
#include "stat-util.h"
#include "strv.h"
int decrypt_pkcs11_key(
const char *volume_name,
const char *friendly_name,
const char *pkcs11_uri,
const char *key_file, /* We either expect key_file and associated parameters to be set (for file keys) … */
size_t key_file_size,
uint64_t key_file_offset,
const void *key_data, /* … or key_data and key_data_size (for literal keys) */
size_t key_data_size,
usec_t until,
bool headless,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size) {
_cleanup_(pkcs11_crypt_device_callback_data_release) pkcs11_crypt_device_callback_data data = {
.friendly_name = friendly_name,
.until = until,
.headless = headless,
};
int r;
assert(friendly_name);
assert(pkcs11_uri);
assert(key_file || key_data);
assert(ret_decrypted_key);
assert(ret_decrypted_key_size);
/* The functions called here log about all errors, except for EAGAIN which means "token not found right now" */
if (key_data) {
data.encrypted_key = (void*) key_data;
data.encrypted_key_size = key_data_size;
data.free_encrypted_key = false;
} else {
_cleanup_free_ char *bindname = NULL;
/* If we read the key via AF_UNIX, make this client recognizable */
if (asprintf(&bindname, "@%" PRIx64"/cryptsetup-pkcs11/%s", random_u64(), volume_name) < 0)
return log_oom();
r = read_full_file_full(
AT_FDCWD, key_file,
key_file_offset == 0 ? UINT64_MAX : key_file_offset,
key_file_size == 0 ? SIZE_MAX : key_file_size,
READ_FULL_FILE_CONNECT_SOCKET,
bindname,
(char**) &data.encrypted_key, &data.encrypted_key_size);
if (r < 0)
return r;
data.free_encrypted_key = true;
}
r = pkcs11_find_token(pkcs11_uri, pkcs11_crypt_device_callback, &data);
if (r < 0)
return r;
*ret_decrypted_key = TAKE_PTR(data.decrypted_key);
*ret_decrypted_key_size = data.decrypted_key_size;
return 0;
}
int find_pkcs11_auto_data(
struct crypt_device *cd,
char **ret_uri,
void **ret_encrypted_key,
size_t *ret_encrypted_key_size,
int *ret_keyslot) {
_cleanup_free_ char *uri = NULL;
_cleanup_free_ void *key = NULL;
int r, keyslot = -1;
size_t key_size = 0;
assert(cd);
assert(ret_uri);
assert(ret_encrypted_key);
assert(ret_encrypted_key_size);
assert(ret_keyslot);
/* Loads PKCS#11 metadata from LUKS2 JSON token headers. */
for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
JsonVariant *w;
int ks;
r = cryptsetup_get_token_as_json(cd, token, "systemd-pkcs11", &v);
if (IN_SET(r, -ENOENT, -EINVAL, -EMEDIUMTYPE))
continue;
if (r < 0)
return log_error_errno(r, "Failed to read JSON token data off disk: %m");
ks = cryptsetup_get_keyslot_from_token(v);
if (ks < 0) {
/* Handle parsing errors of the keyslots field gracefully, since it's not 'owned' by
* us, but by the LUKS2 spec */
log_warning_errno(ks, "Failed to extract keyslot index from PKCS#11 JSON data token %i, skipping: %m", token);
continue;
}
if (uri)
return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
"Multiple PKCS#11 tokens enrolled, cannot automatically determine token.");
assert(keyslot < 0);
keyslot = ks;
w = json_variant_by_key(v, "pkcs11-uri");
if (!w || !json_variant_is_string(w))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"PKCS#11 token data lacks 'pkcs11-uri' field.");
uri = strdup(json_variant_string(w));
if (!uri)
return log_oom();
if (!pkcs11_uri_valid(uri))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"PKCS#11 token data contains invalid PKCS#11 URI.");
w = json_variant_by_key(v, "pkcs11-key");
if (!w || !json_variant_is_string(w))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"PKCS#11 token data lacks 'pkcs11-key' field.");
assert(!key);
assert(key_size == 0);
r = unbase64mem(json_variant_string(w), SIZE_MAX, &key, &key_size);
if (r < 0)
return log_error_errno(r, "Failed to decode base64 encoded key.");
}
if (!uri)
return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
"No valid PKCS#11 token data found.");
log_info("Automatically discovered security PKCS#11 token '%s' unlocks volume.", uri);
*ret_uri = TAKE_PTR(uri);
*ret_encrypted_key = TAKE_PTR(key);
*ret_encrypted_key_size = key_size;
*ret_keyslot = keyslot;
return 0;
}
| 6,516 | 36.454023 | 134 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-pkcs11.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
#include "cryptsetup-util.h"
#include "log.h"
#include "time-util.h"
#if HAVE_P11KIT
int decrypt_pkcs11_key(
const char *volume_name,
const char *friendly_name,
const char *pkcs11_uri,
const char *key_file,
size_t key_file_size,
uint64_t key_file_offset,
const void *key_data,
size_t key_data_size,
usec_t until,
bool headless,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size);
int find_pkcs11_auto_data(
struct crypt_device *cd,
char **ret_uri,
void **ret_encrypted_key,
size_t *ret_encrypted_key_size,
int *ret_keyslot);
#else
static inline int decrypt_pkcs11_key(
const char *volume_name,
const char *friendly_name,
const char *pkcs11_uri,
const char *key_file,
size_t key_file_size,
uint64_t key_file_offset,
const void *key_data,
size_t key_data_size,
usec_t until,
bool headless,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size) {
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"PKCS#11 Token support not available.");
}
static inline int find_pkcs11_auto_data(
struct crypt_device *cd,
char **ret_uri,
void **ret_encrypted_key,
size_t *ret_encrypted_key_size,
int *ret_keyslot) {
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"PKCS#11 Token support not available.");
}
#endif
| 1,930 | 28.707692 | 71 |
h
|
null |
systemd-main/src/cryptsetup/cryptsetup-tpm2.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "ask-password-api.h"
#include "cryptsetup-tpm2.h"
#include "env-util.h"
#include "fileio.h"
#include "hexdecoct.h"
#include "json.h"
#include "parse-util.h"
#include "random-util.h"
#include "sha256.h"
#include "tpm2-util.h"
static int get_pin(usec_t until, AskPasswordFlags ask_password_flags, bool headless, char **ret_pin_str) {
_cleanup_free_ char *pin_str = NULL;
_cleanup_strv_free_erase_ char **pin = NULL;
int r;
assert(ret_pin_str);
r = getenv_steal_erase("PIN", &pin_str);
if (r < 0)
return log_error_errno(r, "Failed to acquire PIN from environment: %m");
if (!r) {
if (headless)
return log_error_errno(
SYNTHETIC_ERRNO(ENOPKG),
"PIN querying disabled via 'headless' option. "
"Use the '$PIN' environment variable.");
pin = strv_free_erase(pin);
r = ask_password_auto(
"Please enter TPM2 PIN:",
"drive-harddisk",
NULL,
"tpm2-pin",
"cryptsetup.tpm2-pin",
until,
ask_password_flags,
&pin);
if (r < 0)
return log_error_errno(r, "Failed to ask for user pin: %m");
assert(strv_length(pin) == 1);
pin_str = strdup(pin[0]);
if (!pin_str)
return log_oom();
}
*ret_pin_str = TAKE_PTR(pin_str);
return r;
}
int acquire_tpm2_key(
const char *volume_name,
const char *device,
uint32_t hash_pcr_mask,
uint16_t pcr_bank,
const void *pubkey,
size_t pubkey_size,
uint32_t pubkey_pcr_mask,
const char *signature_path,
uint16_t primary_alg,
const char *key_file,
size_t key_file_size,
uint64_t key_file_offset,
const void *key_data,
size_t key_data_size,
const void *policy_hash,
size_t policy_hash_size,
const void *salt,
size_t salt_size,
const void *srk_buf,
size_t srk_buf_size,
TPM2Flags flags,
usec_t until,
bool headless,
AskPasswordFlags ask_password_flags,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size) {
_cleanup_(json_variant_unrefp) JsonVariant *signature_json = NULL;
_cleanup_free_ void *loaded_blob = NULL;
_cleanup_free_ char *auto_device = NULL;
size_t blob_size;
const void *blob;
int r;
assert(salt || salt_size == 0);
if (!device) {
r = tpm2_find_device_auto(LOG_DEBUG, &auto_device);
if (r == -ENODEV)
return -EAGAIN; /* Tell the caller to wait for a TPM2 device to show up */
if (r < 0)
return r;
device = auto_device;
}
if (key_data) {
blob = key_data;
blob_size = key_data_size;
} else {
_cleanup_free_ char *bindname = NULL;
/* If we read the salt via AF_UNIX, make this client recognizable */
if (asprintf(&bindname, "@%" PRIx64"/cryptsetup-tpm2/%s", random_u64(), volume_name) < 0)
return log_oom();
r = read_full_file_full(
AT_FDCWD, key_file,
key_file_offset == 0 ? UINT64_MAX : key_file_offset,
key_file_size == 0 ? SIZE_MAX : key_file_size,
READ_FULL_FILE_CONNECT_SOCKET,
bindname,
(char**) &loaded_blob, &blob_size);
if (r < 0)
return r;
blob = loaded_blob;
}
if (pubkey_pcr_mask != 0) {
r = tpm2_load_pcr_signature(signature_path, &signature_json);
if (r < 0)
return r;
}
if (!(flags & TPM2_FLAGS_USE_PIN))
return tpm2_unseal(
device,
hash_pcr_mask,
pcr_bank,
pubkey, pubkey_size,
pubkey_pcr_mask,
signature_json,
/* pin= */ NULL,
primary_alg,
blob,
blob_size,
policy_hash,
policy_hash_size,
srk_buf,
srk_buf_size,
ret_decrypted_key,
ret_decrypted_key_size);
for (int i = 5;; i--) {
_cleanup_(erase_and_freep) char *pin_str = NULL, *b64_salted_pin = NULL;
if (i <= 0)
return -EACCES;
r = get_pin(until, ask_password_flags, headless, &pin_str);
if (r < 0)
return r;
if (salt_size > 0) {
uint8_t salted_pin[SHA256_DIGEST_SIZE] = {};
CLEANUP_ERASE(salted_pin);
r = tpm2_util_pbkdf2_hmac_sha256(pin_str, strlen(pin_str), salt, salt_size, salted_pin);
if (r < 0)
return log_error_errno(r, "Failed to perform PBKDF2: %m");
r = base64mem(salted_pin, sizeof(salted_pin), &b64_salted_pin);
if (r < 0)
return log_error_errno(r, "Failed to base64 encode salted pin: %m");
} else
/* no salting needed, backwards compat with non-salted pins */
b64_salted_pin = TAKE_PTR(pin_str);
r = tpm2_unseal(device,
hash_pcr_mask,
pcr_bank,
pubkey, pubkey_size,
pubkey_pcr_mask,
signature_json,
b64_salted_pin,
primary_alg,
blob,
blob_size,
policy_hash,
policy_hash_size,
srk_buf,
srk_buf_size,
ret_decrypted_key,
ret_decrypted_key_size);
/* We get this error in case there is an authentication policy mismatch. This should
* not happen, but this avoids confusing behavior, just in case. */
if (IN_SET(r, -EPERM, -ENOLCK))
return r;
if (r < 0)
continue;
return r;
}
}
int find_tpm2_auto_data(
struct crypt_device *cd,
uint32_t search_pcr_mask,
int start_token,
uint32_t *ret_hash_pcr_mask,
uint16_t *ret_pcr_bank,
void **ret_pubkey,
size_t *ret_pubkey_size,
uint32_t *ret_pubkey_pcr_mask,
uint16_t *ret_primary_alg,
void **ret_blob,
size_t *ret_blob_size,
void **ret_policy_hash,
size_t *ret_policy_hash_size,
void **ret_salt,
size_t *ret_salt_size,
void **ret_srk_buf,
size_t *ret_srk_buf_size,
TPM2Flags *ret_flags,
int *ret_keyslot,
int *ret_token) {
int r, token;
assert(cd);
for (token = start_token; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
_cleanup_free_ void *blob = NULL, *policy_hash = NULL, *pubkey = NULL, *salt = NULL, *srk_buf = NULL;
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
size_t blob_size, policy_hash_size, pubkey_size, salt_size = 0, srk_buf_size = 0;
uint32_t hash_pcr_mask, pubkey_pcr_mask;
uint16_t pcr_bank, primary_alg;
TPM2Flags flags;
int keyslot;
r = cryptsetup_get_token_as_json(cd, token, "systemd-tpm2", &v);
if (IN_SET(r, -ENOENT, -EINVAL, -EMEDIUMTYPE))
continue;
if (r < 0)
return log_error_errno(r, "Failed to read JSON token data off disk: %m");
r = tpm2_parse_luks2_json(
v,
&keyslot,
&hash_pcr_mask,
&pcr_bank,
&pubkey, &pubkey_size,
&pubkey_pcr_mask,
&primary_alg,
&blob, &blob_size,
&policy_hash, &policy_hash_size,
&salt, &salt_size,
&srk_buf, &srk_buf_size,
&flags);
if (r == -EUCLEAN) /* Gracefully handle issues in JSON fields not owned by us */
continue;
if (r < 0)
return log_error_errno(r, "Failed to parse TPM2 JSON data: %m");
if (search_pcr_mask == UINT32_MAX ||
search_pcr_mask == hash_pcr_mask) {
if (start_token <= 0)
log_info("Automatically discovered security TPM2 token unlocks volume.");
*ret_hash_pcr_mask = hash_pcr_mask;
*ret_pcr_bank = pcr_bank;
*ret_pubkey = TAKE_PTR(pubkey);
*ret_pubkey_size = pubkey_size;
*ret_pubkey_pcr_mask = pubkey_pcr_mask;
*ret_primary_alg = primary_alg;
*ret_blob = TAKE_PTR(blob);
*ret_blob_size = blob_size;
*ret_policy_hash = TAKE_PTR(policy_hash);
*ret_policy_hash_size = policy_hash_size;
*ret_salt = TAKE_PTR(salt);
*ret_salt_size = salt_size;
*ret_keyslot = keyslot;
*ret_token = token;
*ret_srk_buf = TAKE_PTR(srk_buf);
*ret_srk_buf_size = srk_buf_size;
*ret_flags = flags;
return 0;
}
/* PCR mask doesn't match what is configured, ignore this entry, let's see next */
}
return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "No valid TPM2 token data found.");
}
| 11,712 | 38.976109 | 117 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-tpm2.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
#include "ask-password-api.h"
#include "cryptsetup-util.h"
#include "log.h"
#include "time-util.h"
#include "tpm2-util.h"
#if HAVE_TPM2
int acquire_tpm2_key(
const char *volume_name,
const char *device,
uint32_t hash_pcr_mask,
uint16_t pcr_bank,
const void *pubkey,
size_t pubkey_size,
uint32_t pubkey_pcr_mask,
const char *signature_path,
uint16_t primary_alg,
const char *key_file,
size_t key_file_size,
uint64_t key_file_offset,
const void *key_data,
size_t key_data_size,
const void *policy_hash,
size_t policy_hash_size,
const void *salt,
size_t salt_size,
const void *srk_buf,
size_t salt_srk_buf_size,
TPM2Flags flags,
usec_t until,
bool headless,
AskPasswordFlags ask_password_flags,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size);
int find_tpm2_auto_data(
struct crypt_device *cd,
uint32_t search_pcr_mask,
int start_token,
uint32_t *ret_hash_pcr_mask,
uint16_t *ret_pcr_bank,
void **ret_pubkey,
size_t *ret_pubkey_size,
uint32_t *ret_pubkey_pcr_mask,
uint16_t *ret_primary_alg,
void **ret_blob,
size_t *ret_blob_size,
void **ret_policy_hash,
size_t *ret_policy_hash_size,
void **ret_salt,
size_t *ret_salt_size,
void **ret_srk_buf,
size_t *ret_srk_size,
TPM2Flags *ret_flags,
int *ret_keyslot,
int *ret_token);
#else
static inline int acquire_tpm2_key(
const char *volume_name,
const char *device,
uint32_t hash_pcr_mask,
uint16_t pcr_bank,
const void *pubkey,
size_t pubkey_size,
uint32_t pubkey_pcr_mask,
const char *signature_path,
uint16_t primary_alg,
const char *key_file,
size_t key_file_size,
uint64_t key_file_offset,
const void *key_data,
size_t key_data_size,
const void *policy_hash,
size_t policy_hash_size,
const void *salt,
size_t salt_size,
const void *srk_buf,
size_t salt_srk_buf_size,
TPM2Flags flags,
usec_t until,
bool headless,
AskPasswordFlags ask_password_flags,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size) {
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"TPM2 support not available.");
}
static inline int find_tpm2_auto_data(
struct crypt_device *cd,
uint32_t search_pcr_mask,
int start_token,
uint32_t *ret_hash_pcr_mask,
uint16_t *ret_pcr_bank,
void **ret_pubkey,
size_t *ret_pubkey_size,
uint32_t *ret_pubkey_pcr_mask,
uint16_t *ret_primary_alg,
void **ret_blob,
size_t *ret_blob_size,
void **ret_policy_hash,
size_t *ret_policy_hash_size,
void **ret_salt,
size_t *ret_salt_size,
void **ret_srk_buf,
size_t *ret_srk_size,
TPM2Flags *ret_flags,
int *ret_keyslot,
int *ret_token) {
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"TPM2 support not available.");
}
#endif
| 4,189 | 32.52 | 62 |
h
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-systemd-fido2.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <libcryptsetup.h>
#include <string.h>
#include "cryptsetup-token.h"
#include "cryptsetup-token-util.h"
#include "hexdecoct.h"
#include "json.h"
#include "luks2-fido2.h"
#include "memory-util.h"
#include "version.h"
#define TOKEN_NAME "systemd-fido2"
#define TOKEN_VERSION_MAJOR "1"
#define TOKEN_VERSION_MINOR "0"
/* for libcryptsetup debug purpose */
_public_ const char *cryptsetup_token_version(void) {
return TOKEN_VERSION_MAJOR "." TOKEN_VERSION_MINOR " systemd-v" STRINGIFY(PROJECT_VERSION) " (" GIT_VERSION ")";
}
_public_ int cryptsetup_token_open_pin(
struct crypt_device *cd, /* is always LUKS2 context */
int token /* is always >= 0 */,
const char *pin,
size_t pin_size,
char **password, /* freed by cryptsetup_token_buffer_free */
size_t *password_len,
void *usrptr /* plugin defined parameter passed to crypt_activate_by_token*() API */) {
int r;
const char *json;
_cleanup_(erase_and_freep) char *pin_string = NULL;
assert(!pin || pin_size);
assert(token >= 0);
/* This must not fail at this moment (internal error) */
r = crypt_token_json_get(cd, token, &json);
/* Use assert_se() here to avoid emitting warning with -DNDEBUG */
assert_se(token == r);
assert(json);
r = crypt_normalize_pin(pin, pin_size, &pin_string);
if (r < 0)
return crypt_log_debug_errno(cd, r, "Can not normalize PIN: %m");
return acquire_luks2_key(cd, json, (const char *)usrptr, pin_string, password, password_len);
}
/*
* This function is called from within following libcryptsetup calls
* provided conditions further below are met:
*
* crypt_activate_by_token(), crypt_activate_by_token_type(type == 'systemd-fido2'):
*
* - token is assigned to at least one luks2 keyslot eligible to activate LUKS2 device
* (alternatively: name is set to null, flags contains CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY
* and token is assigned to at least single keyslot).
*
* - if plugin defines validate function (see cryptsetup_token_validate below) it must have
* passed the check (aka return 0)
*/
_public_ int cryptsetup_token_open(
struct crypt_device *cd, /* is always LUKS2 context */
int token /* is always >= 0 */,
char **password, /* freed by cryptsetup_token_buffer_free */
size_t *password_len,
void *usrptr /* plugin defined parameter passed to crypt_activate_by_token*() API */) {
return cryptsetup_token_open_pin(cd, token, NULL, 0, password, password_len, usrptr);
}
/*
* libcryptsetup callback for memory deallocation of 'password' parameter passed in
* any crypt_token_open_* plugin function
*/
_public_ void cryptsetup_token_buffer_free(void *buffer, size_t buffer_len) {
erase_and_free(buffer);
}
/*
* prints systemd-fido2 token content in crypt_dump().
* 'type' and 'keyslots' fields are printed by libcryptsetup
*/
_public_ void cryptsetup_token_dump(
struct crypt_device *cd /* is always LUKS2 context */,
const char *json /* validated 'systemd-tpm2' token if cryptsetup_token_validate is defined */) {
int r;
Fido2EnrollFlags required;
size_t cid_size, salt_size;
const char *client_pin_req_str, *up_req_str, *uv_req_str;
_cleanup_free_ void *cid = NULL, *salt = NULL;
_cleanup_free_ char *rp_id = NULL, *cid_str = NULL, *salt_str = NULL;
assert(json);
r = parse_luks2_fido2_data(cd, json, &rp_id, &salt, &salt_size, &cid, &cid_size, &required);
if (r < 0)
return (void) crypt_log_debug_errno(cd, r, "Failed to parse " TOKEN_NAME " metadata: %m.");
r = crypt_dump_buffer_to_hex_string(cid, cid_size, &cid_str);
if (r < 0)
return (void) crypt_log_debug_errno(cd, r, "Can not dump " TOKEN_NAME " content: %m");
r = crypt_dump_buffer_to_hex_string(salt, salt_size, &salt_str);
if (r < 0)
return (void) crypt_log_debug_errno(cd, r, "Can not dump " TOKEN_NAME " content: %m");
if (required & FIDO2ENROLL_PIN)
client_pin_req_str = "true";
else if (required & FIDO2ENROLL_PIN_IF_NEEDED)
client_pin_req_str = NULL;
else
client_pin_req_str = "false";
if (required & FIDO2ENROLL_UP)
up_req_str = "true";
else if (required & FIDO2ENROLL_UP_IF_NEEDED)
up_req_str = NULL;
else
up_req_str = "false";
if (required & FIDO2ENROLL_UV)
uv_req_str = "true";
else if (required & FIDO2ENROLL_UV_OMIT)
uv_req_str = NULL;
else
uv_req_str = "false";
crypt_log(cd, "\tfido2-credential:" CRYPT_DUMP_LINE_SEP "%s\n", cid_str);
crypt_log(cd, "\tfido2-salt: %s\n", salt_str);
/* optional fields */
if (rp_id)
crypt_log(cd, "\tfido2-rp: %s\n", rp_id);
if (client_pin_req_str)
crypt_log(cd, "\tfido2-clientPin-required:" CRYPT_DUMP_LINE_SEP "%s\n",
client_pin_req_str);
if (up_req_str)
crypt_log(cd, "\tfido2-up-required:" CRYPT_DUMP_LINE_SEP "%s\n", up_req_str);
if (uv_req_str)
crypt_log(cd, "\tfido2-uv-required:" CRYPT_DUMP_LINE_SEP "%s\n", uv_req_str);
}
/*
* Note:
* If plugin is available in library path, it's called in before following libcryptsetup calls:
*
* crypt_token_json_set, crypt_dump, any crypt_activate_by_token_* flavour
*/
_public_ int cryptsetup_token_validate(
struct crypt_device *cd, /* is always LUKS2 context */
const char *json /* contains valid 'type' and 'keyslots' fields. 'type' is 'systemd-tpm2' */) {
int r;
JsonVariant *w;
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
assert(json);
r = json_parse(json, 0, &v, NULL, NULL);
if (r < 0)
return crypt_log_debug_errno(cd, r, "Could not parse " TOKEN_NAME " json object: %m.");
w = json_variant_by_key(v, "fido2-credential");
if (!w || !json_variant_is_string(w)) {
crypt_log_debug(cd, "FIDO2 token data lacks 'fido2-credential' field.");
return 1;
}
r = unbase64mem(json_variant_string(w), SIZE_MAX, NULL, NULL);
if (r < 0)
return crypt_log_debug_errno(cd, r, "Invalid base64 data in 'fido2-credential' field: %m");
w = json_variant_by_key(v, "fido2-salt");
if (!w || !json_variant_is_string(w)) {
crypt_log_debug(cd, "FIDO2 token data lacks 'fido2-salt' field.");
return 1;
}
r = unbase64mem(json_variant_string(w), SIZE_MAX, NULL, NULL);
if (r < 0)
return crypt_log_debug_errno(cd, r, "Failed to decode base64 encoded salt: %m.");
/* The "rp" field is optional. */
w = json_variant_by_key(v, "fido2-rp");
if (w && !json_variant_is_string(w)) {
crypt_log_debug(cd, "FIDO2 token data's 'fido2-rp' field is not a string.");
return 1;
}
/* The "fido2-clientPin-required" field is optional. */
w = json_variant_by_key(v, "fido2-clientPin-required");
if (w && !json_variant_is_boolean(w)) {
crypt_log_debug(cd, "FIDO2 token data's 'fido2-clientPin-required' field is not a boolean.");
return 1;
}
/* The "fido2-up-required" field is optional. */
w = json_variant_by_key(v, "fido2-up-required");
if (w && !json_variant_is_boolean(w)) {
crypt_log_debug(cd, "FIDO2 token data's 'fido2-up-required' field is not a boolean.");
return 1;
}
/* The "fido2-uv-required" field is optional. */
w = json_variant_by_key(v, "fido2-uv-required");
if (w && !json_variant_is_boolean(w)) {
crypt_log_debug(cd, "FIDO2 token data's 'fido2-uv-required' field is not a boolean.");
return 1;
}
return 0;
}
| 8,394 | 37.333333 | 120 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-systemd-pkcs11.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <libcryptsetup.h>
#include "cryptsetup-token.h"
#include "cryptsetup-token-util.h"
#include "hexdecoct.h"
#include "json.h"
#include "luks2-pkcs11.h"
#include "memory-util.h"
#include "pkcs11-util.h"
#include "version.h"
#define TOKEN_NAME "systemd-pkcs11"
#define TOKEN_VERSION_MAJOR "1"
#define TOKEN_VERSION_MINOR "0"
/* for libcryptsetup debug purpose */
_public_ const char *cryptsetup_token_version(void) {
return TOKEN_VERSION_MAJOR "." TOKEN_VERSION_MINOR " systemd-v" STRINGIFY(PROJECT_VERSION) " (" GIT_VERSION ")";
}
_public_ int cryptsetup_token_open_pin(
struct crypt_device *cd, /* is always LUKS2 context */
int token /* is always >= 0 */,
const char *pin,
size_t pin_size,
char **password, /* freed by cryptsetup_token_buffer_free */
size_t *password_len,
void *usrptr /* plugin defined parameter passed to crypt_activate_by_token*() API */) {
const char *json;
int r;
assert(!pin || pin_size);
assert(token >= 0);
/* This must not fail at this moment (internal error) */
r = crypt_token_json_get(cd, token, &json);
/* Use assert_se() here to avoid emitting warning with -DNDEBUG */
assert_se(token == r);
assert(json);
return acquire_luks2_key(cd, json, usrptr, pin, pin_size, password, password_len);
}
/*
* This function is called from within following libcryptsetup calls
* provided conditions further below are met:
*
* crypt_activate_by_token(), crypt_activate_by_token_type(type == 'systemd-pkcs11'):
*
* - token is assigned to at least one luks2 keyslot eligible to activate LUKS2 device
* (alternatively: name is set to null, flags contains CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY
* and token is assigned to at least single keyslot).
*
* - if plugin defines validate function (see cryptsetup_token_validate below) it must have
* passed the check (aka return 0)
*/
_public_ int cryptsetup_token_open(
struct crypt_device *cd, /* is always LUKS2 context */
int token /* is always >= 0 */,
char **password, /* freed by cryptsetup_token_buffer_free */
size_t *password_len,
void *usrptr /* plugin defined parameter passed to crypt_activate_by_token*() API */) {
return cryptsetup_token_open_pin(cd, token, NULL, 0, password, password_len, usrptr);
}
/*
* libcryptsetup callback for memory deallocation of 'password' parameter passed in
* any crypt_token_open_* plugin function
*/
_public_ void cryptsetup_token_buffer_free(void *buffer, size_t buffer_len) {
erase_and_free(buffer);
}
/*
* prints systemd-pkcs11 token content in crypt_dump().
* 'type' and 'keyslots' fields are printed by libcryptsetup
*/
_public_ void cryptsetup_token_dump(
struct crypt_device *cd /* is always LUKS2 context */,
const char *json /* validated 'systemd-pkcs11' token if cryptsetup_token_validate is defined */) {
int r;
size_t pkcs11_key_size;
_cleanup_free_ char *pkcs11_uri = NULL, *key_str = NULL;
_cleanup_free_ void *pkcs11_key = NULL;
r = parse_luks2_pkcs11_data(cd, json, &pkcs11_uri, &pkcs11_key, &pkcs11_key_size);
if (r < 0)
return (void) crypt_log_debug_errno(cd, r, "Failed to parse " TOKEN_NAME " metadata: %m.");
r = crypt_dump_buffer_to_hex_string(pkcs11_key, pkcs11_key_size, &key_str);
if (r < 0)
return (void) crypt_log_debug_errno(cd, r, "Can not dump " TOKEN_NAME " content: %m");
crypt_log(cd, "\tpkcs11-uri: %s\n", pkcs11_uri);
crypt_log(cd, "\tpkcs11-key: %s\n", key_str);
}
/*
* Note:
* If plugin is available in library path, it's called in before following libcryptsetup calls:
*
* crypt_token_json_set, crypt_dump, any crypt_activate_by_token_* flavour
*/
_public_ int cryptsetup_token_validate(
struct crypt_device *cd, /* is always LUKS2 context */
const char *json /* contains valid 'type' and 'keyslots' fields. 'type' is 'systemd-pkcs11' */) {
int r;
JsonVariant *w;
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
r = json_parse(json, 0, &v, NULL, NULL);
if (r < 0)
return crypt_log_debug_errno(cd, r, "Could not parse " TOKEN_NAME " json object: %m.");
w = json_variant_by_key(v, "pkcs11-uri");
if (!w || !json_variant_is_string(w)) {
crypt_log_debug(cd, "PKCS#11 token data lacks 'pkcs11-uri' field.");
return 1;
}
if (!pkcs11_uri_valid(json_variant_string(w))) {
crypt_log_debug(cd, "PKCS#11 token data contains invalid PKCS#11 URI.");
return 1;
}
w = json_variant_by_key(v, "pkcs11-key");
if (!w || !json_variant_is_string(w)) {
crypt_log_debug(cd, "PKCS#11 token data lacks 'pkcs11-key' field.");
return 1;
}
r = unbase64mem(json_variant_string(w), SIZE_MAX, NULL, NULL);
if (r < 0)
return crypt_log_debug_errno(cd, r, "Failed to decode base64 encoded key: %m.");
return 0;
}
| 5,381 | 36.117241 | 120 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "cryptsetup-token-util.h"
#include "string-util.h"
int crypt_dump_buffer_to_hex_string(
const char *buf,
size_t buf_size,
char **ret_dump_str) {
int r;
_cleanup_free_ char *dump_str = NULL;
assert(buf || !buf_size);
assert(ret_dump_str);
for (size_t i = 0; i < buf_size; i++) {
/* crypt_dump() breaks line after every
* 16th couple of chars in dumped hexstring */
r = strextendf_with_separator(
&dump_str,
(i && !(i % 16)) ? CRYPT_DUMP_LINE_SEP : " ",
"%02hhx", buf[i]);
if (r < 0)
return r;
}
*ret_dump_str = TAKE_PTR(dump_str);
return 0;
}
int crypt_dump_hex_string(const char *hex_str, char **ret_dump_str) {
int r;
size_t len;
_cleanup_free_ char *dump_str = NULL;
assert(hex_str);
assert(ret_dump_str);
len = strlen(hex_str) >> 1;
for (size_t i = 0; i < len; i++) {
/* crypt_dump() breaks line after every
* 16th couple of chars in dumped hexstring */
r = strextendf_with_separator(
&dump_str,
(i && !(i % 16)) ? CRYPT_DUMP_LINE_SEP : " ",
"%.2s", hex_str + (i<<1));
if (r < 0)
return r;
}
*ret_dump_str = TAKE_PTR(dump_str);
return 0;
}
int crypt_normalize_pin(const void *pin, size_t pin_size, char **ret_pin_string) {
assert(pin || pin_size == 0);
assert(ret_pin_string);
if (pin_size == 0) {
*ret_pin_string = NULL;
return 0;
}
return make_cstring(pin, pin_size, MAKE_CSTRING_ALLOW_TRAILING_NUL, ret_pin_string);
}
| 1,985 | 26.971831 | 92 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <libcryptsetup.h>
/* crypt_dump() internal indentation magic */
#define CRYPT_DUMP_LINE_SEP "\n\t "
#define crypt_log_debug(cd, ...) crypt_logf(cd, CRYPT_LOG_DEBUG, __VA_ARGS__)
#define crypt_log_error(cd, ...) crypt_logf(cd, CRYPT_LOG_ERROR, __VA_ARGS__)
#define crypt_log_verbose(cd, ...) crypt_logf(cd, CRYPT_LOG_VERBOSE, __VA_ARGS__)
#define crypt_log(cd, ...) crypt_logf(cd, CRYPT_LOG_NORMAL, __VA_ARGS__)
#define crypt_log_full_errno(cd, e, lvl, ...) ({ \
int _e = abs(e), _s = errno; \
errno = _e; \
crypt_logf(cd, lvl, __VA_ARGS__); \
errno = _s; \
-_e; \
})
#define crypt_log_debug_errno(cd, e, ...) \
crypt_log_full_errno(cd, e, CRYPT_LOG_DEBUG, __VA_ARGS__)
#define crypt_log_error_errno(cd, e, ...) \
crypt_log_full_errno(cd, e, CRYPT_LOG_ERROR, __VA_ARGS__)
#define crypt_log_oom(cd) crypt_log_error_errno(cd, ENOMEM, "Not enough memory.")
int crypt_dump_buffer_to_hex_string(
const char *buf,
size_t buf_size,
char **ret_dump_str);
int crypt_dump_hex_string(const char *hex_str, char **ret_dump_str);
int crypt_normalize_pin(const void *pin, size_t pin_size, char **ret_pin_string);
| 1,352 | 32 | 81 |
h
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/cryptsetup-token.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/* for more information see libcryptsetup.h crypt-tokens section */
const char *cryptsetup_token_version(void);
int cryptsetup_token_open(struct crypt_device *cd, int token,
char **password, size_t *password_len, void *usrptr);
int cryptsetup_token_open_pin(struct crypt_device *cd, int token,
const char *pin, size_t pin_size,
char **password, size_t *password_len, void *usrptr);
void cryptsetup_token_dump(struct crypt_device *cd, const char *json);
int cryptsetup_token_validate(struct crypt_device *cd, const char *json);
void cryptsetup_token_buffer_free(void *buffer, size_t buffer_len);
| 688 | 33.45 | 73 |
h
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/luks2-fido2.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <libcryptsetup.h>
#include "cryptsetup-token-util.h"
#include "hexdecoct.h"
#include "json.h"
#include "luks2-fido2.h"
#include "memory-util.h"
#include "strv.h"
int acquire_luks2_key(
struct crypt_device *cd,
const char *json,
const char *device,
const char *pin,
char **ret_keyslot_passphrase,
size_t *ret_keyslot_passphrase_size) {
int r;
Fido2EnrollFlags required;
size_t cid_size, salt_size, decrypted_key_size;
_cleanup_free_ void *cid = NULL, *salt = NULL;
_cleanup_free_ char *rp_id = NULL;
_cleanup_(erase_and_freep) void *decrypted_key = NULL;
_cleanup_(erase_and_freep) char *base64_encoded = NULL;
_cleanup_strv_free_erase_ char **pins = NULL;
ssize_t base64_encoded_size;
assert(ret_keyslot_passphrase);
assert(ret_keyslot_passphrase_size);
r = parse_luks2_fido2_data(cd, json, &rp_id, &salt, &salt_size, &cid, &cid_size, &required);
if (r < 0)
return r;
if (pin) {
pins = strv_new(pin);
if (!pins)
return crypt_log_oom(cd);
}
/* configured to use pin but none was provided */
if ((required & FIDO2ENROLL_PIN) && strv_isempty(pins))
return -ENOANO;
r = fido2_use_hmac_hash(
device,
rp_id ?: "io.systemd.cryptsetup",
salt, salt_size,
cid, cid_size,
pins,
required,
&decrypted_key,
&decrypted_key_size);
if (r == -ENOLCK) /* libcryptsetup returns -ENOANO also on wrong PIN */
r = -ENOANO;
if (r < 0)
return r;
/* Before using this key as passphrase we base64 encode it, for compat with homed */
base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
if (base64_encoded_size < 0)
return crypt_log_error_errno(cd, (int) base64_encoded_size, "Failed to base64 encode key: %m");
*ret_keyslot_passphrase = TAKE_PTR(base64_encoded);
*ret_keyslot_passphrase_size = base64_encoded_size;
return 0;
}
/* this function expects valid "systemd-fido2" in json */
int parse_luks2_fido2_data(
struct crypt_device *cd,
const char *json,
char **ret_rp_id,
void **ret_salt,
size_t *ret_salt_size,
void **ret_cid,
size_t *ret_cid_size,
Fido2EnrollFlags *ret_required) {
_cleanup_free_ void *cid = NULL, *salt = NULL;
size_t cid_size = 0, salt_size = 0;
_cleanup_free_ char *rp = NULL;
int r;
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
JsonVariant *w;
Fido2EnrollFlags required = 0;
assert(json);
assert(ret_rp_id);
assert(ret_salt);
assert(ret_salt_size);
assert(ret_cid);
assert(ret_cid_size);
assert(ret_required);
r = json_parse(json, 0, &v, NULL, NULL);
if (r < 0)
return crypt_log_error_errno(cd, r, "Failed to parse JSON token data: %m");
w = json_variant_by_key(v, "fido2-credential");
if (!w)
return -EINVAL;
r = unbase64mem(json_variant_string(w), SIZE_MAX, &cid, &cid_size);
if (r < 0)
return crypt_log_error_errno(cd, r, "Failed to parse 'fido2-credentials' field: %m");
w = json_variant_by_key(v, "fido2-salt");
if (!w)
return -EINVAL;
r = unbase64mem(json_variant_string(w), SIZE_MAX, &salt, &salt_size);
if (r < 0)
return crypt_log_error_errno(cd, r, "Failed to parse 'fido2-salt' field: %m");
w = json_variant_by_key(v, "fido2-rp");
if (w) {
/* The "rp" field is optional. */
rp = strdup(json_variant_string(w));
if (!rp) {
crypt_log_error(cd, "Not enough memory.");
return -ENOMEM;
}
}
w = json_variant_by_key(v, "fido2-clientPin-required");
if (w)
/* The "fido2-clientPin-required" field is optional. */
SET_FLAG(required, FIDO2ENROLL_PIN, json_variant_boolean(w));
else
required |= FIDO2ENROLL_PIN_IF_NEEDED; /* compat with 248, where the field was unset */
w = json_variant_by_key(v, "fido2-up-required");
if (w)
/* The "fido2-up-required" field is optional. */
SET_FLAG(required, FIDO2ENROLL_UP, json_variant_boolean(w));
else
required |= FIDO2ENROLL_UP_IF_NEEDED; /* compat with 248 */
w = json_variant_by_key(v, "fido2-uv-required");
if (w)
/* The "fido2-uv-required" field is optional. */
SET_FLAG(required, FIDO2ENROLL_UV, json_variant_boolean(w));
else
required |= FIDO2ENROLL_UV_OMIT; /* compat with 248 */
*ret_rp_id = TAKE_PTR(rp);
*ret_cid = TAKE_PTR(cid);
*ret_cid_size = cid_size;
*ret_salt = TAKE_PTR(salt);
*ret_salt_size = salt_size;
*ret_required = required;
return 0;
}
| 5,562 | 33.987421 | 111 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/luks2-fido2.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "libfido2-util.h"
struct crypt_device;
int acquire_luks2_key(
struct crypt_device *cd,
const char *json,
const char *device,
const char *pin,
char **ret_keyslot_passphrase,
size_t *ret_keyslot_passphrase_size);
int parse_luks2_fido2_data(
struct crypt_device *cd,
const char *json,
char **ret_rp_id,
void **ret_salt,
size_t *ret_salt_size,
void **ret_cid,
size_t *ret_cid_size,
Fido2EnrollFlags *ret_required);
| 710 | 27.44 | 53 |
h
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/luks2-pkcs11.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <p11-kit/p11-kit.h>
#include <p11-kit/uri.h>
#include "cryptsetup-token-util.h"
#include "escape.h"
#include "hexdecoct.h"
#include "json.h"
#include "luks2-pkcs11.h"
#include "memory-util.h"
#include "pkcs11-util.h"
#include "time-util.h"
struct luks2_pkcs11_callback_data {
struct crypt_device *cd;
const char *pin;
size_t pin_size;
void *encrypted_key;
size_t encrypted_key_size;
void *decrypted_key;
size_t decrypted_key_size;
};
static int luks2_pkcs11_callback(
CK_FUNCTION_LIST *m,
CK_SESSION_HANDLE session,
CK_SLOT_ID slot_id,
const CK_SLOT_INFO *slot_info,
const CK_TOKEN_INFO *token_info,
P11KitUri *uri,
void *userdata) {
CK_OBJECT_HANDLE object;
CK_RV rv;
CK_TOKEN_INFO updated_token_info;
int r;
_cleanup_free_ char *token_label = NULL;
struct luks2_pkcs11_callback_data *data = ASSERT_PTR(userdata);
assert(m);
assert(slot_info);
assert(token_info);
assert(uri);
token_label = pkcs11_token_label(token_info);
if (!token_label)
return -ENOMEM;
/* Called for every token matching our URI */
r = pkcs11_token_login_by_pin(m, session, token_info, token_label, data->pin, data->pin_size);
if (r == -ENOLCK) {
/* Referesh the token info, so that we can prompt knowing the new flags if they changed. */
rv = m->C_GetTokenInfo(slot_id, &updated_token_info);
if (rv != CKR_OK) {
crypt_log_error(data->cd,
"Failed to acquire updated security token information for slot %lu: %s",
slot_id, p11_kit_strerror(rv));
return -EIO;
}
token_info = &updated_token_info;
r = -ENOANO;
}
if (r == -ENOANO) {
if (FLAGS_SET(token_info->flags, CKF_USER_PIN_FINAL_TRY))
crypt_log_error(data->cd, "Please enter correct PIN for security token "
"'%s' in order to unlock it (final try).", token_label);
else if (FLAGS_SET(token_info->flags, CKF_USER_PIN_COUNT_LOW))
crypt_log_error(data->cd, "PIN has been entered incorrectly previously, "
"please enter correct PIN for security token '%s' in order to unlock it.",
token_label);
}
if (r == -EPERM) /* pin is locked, but map it to -ENOANO anyway */
r = -ENOANO;
if (r < 0)
return r;
r = pkcs11_token_find_private_key(m, session, uri, &object);
if (r < 0)
return r;
r = pkcs11_token_decrypt_data(
m,
session,
object,
data->encrypted_key,
data->encrypted_key_size,
&data->decrypted_key,
&data->decrypted_key_size);
if (r < 0)
return r;
return 0;
}
static void luks2_pkcs11_callback_data_release(struct luks2_pkcs11_callback_data *data) {
erase_and_free(data->decrypted_key);
}
static int acquire_luks2_key_by_pin(
struct crypt_device *cd,
const char *pkcs11_uri,
const void *pin,
size_t pin_size,
void *encrypted_key,
size_t encrypted_key_size,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size) {
int r;
_cleanup_(luks2_pkcs11_callback_data_release) struct luks2_pkcs11_callback_data data = {
.cd = cd,
.pin = pin,
.pin_size = pin_size,
.encrypted_key = encrypted_key,
.encrypted_key_size = encrypted_key_size,
};
assert(pkcs11_uri);
assert(encrypted_key);
assert(ret_decrypted_key);
assert(ret_decrypted_key_size);
r = pkcs11_find_token(pkcs11_uri, luks2_pkcs11_callback, &data);
if (r < 0)
return r;
*ret_decrypted_key = TAKE_PTR(data.decrypted_key);
*ret_decrypted_key_size = data.decrypted_key_size;
return 0;
}
/* called from within systemd utilities */
static int acquire_luks2_key_systemd(
const char *pkcs11_uri,
systemd_pkcs11_plugin_params *params,
void *encrypted_key,
size_t encrypted_key_size,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size) {
int r;
_cleanup_(pkcs11_crypt_device_callback_data_release) pkcs11_crypt_device_callback_data data = {
.encrypted_key = encrypted_key,
.encrypted_key_size = encrypted_key_size,
.free_encrypted_key = false
};
assert(pkcs11_uri);
assert(encrypted_key);
assert(ret_decrypted_key);
assert(ret_decrypted_key_size);
assert(params);
data.friendly_name = params->friendly_name;
data.headless = params->headless;
data.until = params->until;
/* The functions called here log about all errors, except for EAGAIN which means "token not found right now" */
r = pkcs11_find_token(pkcs11_uri, pkcs11_crypt_device_callback, &data);
if (r < 0)
return r;
*ret_decrypted_key = TAKE_PTR(data.decrypted_key);
*ret_decrypted_key_size = data.decrypted_key_size;
return 0;
}
int acquire_luks2_key(
struct crypt_device *cd,
const char *json,
void *userdata,
const void *pin,
size_t pin_size,
char **ret_password,
size_t *ret_password_size) {
int r;
size_t decrypted_key_size, encrypted_key_size;
_cleanup_(erase_and_freep) void *decrypted_key = NULL;
_cleanup_(erase_and_freep) char *base64_encoded = NULL;
_cleanup_free_ char *pkcs11_uri = NULL;
_cleanup_free_ void *encrypted_key = NULL;
systemd_pkcs11_plugin_params *pkcs11_params = userdata;
ssize_t base64_encoded_size;
assert(json);
assert(ret_password);
assert(ret_password_size);
r = parse_luks2_pkcs11_data(cd, json, &pkcs11_uri, &encrypted_key, &encrypted_key_size);
if (r < 0)
return r;
if (pkcs11_params && pin)
crypt_log_verbose(cd, "PIN parameter ignored in interactive mode.");
if (pkcs11_params) /* systemd based activation with interactive pin query callbacks */
r = acquire_luks2_key_systemd(
pkcs11_uri,
pkcs11_params,
encrypted_key, encrypted_key_size,
&decrypted_key, &decrypted_key_size);
else /* default activation that provides single PIN if needed */
r = acquire_luks2_key_by_pin(
cd, pkcs11_uri, pin, pin_size,
encrypted_key, encrypted_key_size,
&decrypted_key, &decrypted_key_size);
if (r < 0)
return r;
base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
if (base64_encoded_size < 0)
return crypt_log_error_errno(cd, (int) base64_encoded_size, "Can not base64 encode key: %m");
*ret_password = TAKE_PTR(base64_encoded);
*ret_password_size = base64_encoded_size;
return 0;
}
int parse_luks2_pkcs11_data(
struct crypt_device *cd,
const char *json,
char **ret_uri,
void **ret_encrypted_key,
size_t *ret_encrypted_key_size) {
int r;
size_t key_size;
_cleanup_free_ char *uri = NULL;
_cleanup_free_ void *key = NULL;
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
JsonVariant *w;
assert(json);
assert(ret_uri);
assert(ret_encrypted_key);
assert(ret_encrypted_key_size);
r = json_parse(json, 0, &v, NULL, NULL);
if (r < 0)
return r;
w = json_variant_by_key(v, "pkcs11-uri");
if (!w)
return -EINVAL;
uri = strdup(json_variant_string(w));
if (!uri)
return -ENOMEM;
w = json_variant_by_key(v, "pkcs11-key");
if (!w)
return -EINVAL;
r = unbase64mem(json_variant_string(w), SIZE_MAX, &key, &key_size);
if (r < 0)
return crypt_log_debug_errno(cd, r, "Failed to decode base64 encoded key: %m.");
*ret_uri = TAKE_PTR(uri);
*ret_encrypted_key = TAKE_PTR(key);
*ret_encrypted_key_size = key_size;
return 0;
}
| 9,260 | 33.047794 | 119 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/luks2-pkcs11.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
struct crypt_device;
int acquire_luks2_key(
struct crypt_device *cd,
const char *json,
void *userdata,
const void *pin,
size_t pin_size,
char **password,
size_t *password_size);
int parse_luks2_pkcs11_data(
struct crypt_device *cd,
const char *json,
char **ret_uri,
void **ret_encrypted_key,
size_t *ret_encrypted_key_size);
| 583 | 25.545455 | 48 |
h
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/luks2-tpm2.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "ask-password-api.h"
#include "env-util.h"
#include "hexdecoct.h"
#include "json.h"
#include "log.h"
#include "luks2-tpm2.h"
#include "parse-util.h"
#include "random-util.h"
#include "sha256.h"
#include "strv.h"
#include "tpm2-util.h"
int acquire_luks2_key(
const char *device,
uint32_t hash_pcr_mask,
uint16_t pcr_bank,
const void *pubkey,
size_t pubkey_size,
uint32_t pubkey_pcr_mask,
const char *signature_path,
const char *pin,
uint16_t primary_alg,
const void *key_data,
size_t key_data_size,
const void *policy_hash,
size_t policy_hash_size,
const void *salt,
size_t salt_size,
const void *srk_buf,
size_t srk_buf_size,
TPM2Flags flags,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size) {
_cleanup_(json_variant_unrefp) JsonVariant *signature_json = NULL;
_cleanup_free_ char *auto_device = NULL;
_cleanup_(erase_and_freep) char *b64_salted_pin = NULL;
int r;
assert(salt || salt_size == 0);
assert(ret_decrypted_key);
assert(ret_decrypted_key_size);
if (!device) {
r = tpm2_find_device_auto(LOG_DEBUG, &auto_device);
if (r == -ENODEV)
return -EAGAIN; /* Tell the caller to wait for a TPM2 device to show up */
if (r < 0)
return r;
device = auto_device;
}
if ((flags & TPM2_FLAGS_USE_PIN) && !pin)
return -ENOANO;
/* If we're using a PIN, and the luks header has a salt, it better have a pin too */
if ((flags & TPM2_FLAGS_USE_PIN) && salt_size > 0 && !pin)
return -ENOANO;
if (pin && salt_size > 0) {
uint8_t salted_pin[SHA256_DIGEST_SIZE] = {};
CLEANUP_ERASE(salted_pin);
r = tpm2_util_pbkdf2_hmac_sha256(pin, strlen(pin), salt, salt_size, salted_pin);
if (r < 0)
return log_error_errno(r, "Failed to perform PBKDF2: %m");
r = base64mem(salted_pin, sizeof(salted_pin), &b64_salted_pin);
if (r < 0)
return log_error_errno(r, "Failed to base64 encode salted pin: %m");
pin = b64_salted_pin;
}
if (pubkey_pcr_mask != 0) {
r = tpm2_load_pcr_signature(signature_path, &signature_json);
if (r < 0)
return r;
}
return tpm2_unseal(
device,
hash_pcr_mask,
pcr_bank,
pubkey, pubkey_size,
pubkey_pcr_mask,
signature_json,
pin,
primary_alg,
key_data, key_data_size,
policy_hash, policy_hash_size,
srk_buf, srk_buf_size,
ret_decrypted_key, ret_decrypted_key_size);
}
| 3,368 | 33.731959 | 98 |
c
|
null |
systemd-main/src/cryptsetup/cryptsetup-tokens/luks2-tpm2.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "tpm2-util.h"
struct crypt_device;
int acquire_luks2_key(
const char *device,
uint32_t pcr_mask,
uint16_t pcr_bank,
const void *pubkey,
size_t pubkey_size,
uint32_t pubkey_pcr_mask,
const char *signature_path,
const char *pin,
uint16_t primary_alg,
const void *key_data,
size_t key_data_size,
const void *policy_hash,
size_t policy_hash_size,
const void *salt,
size_t salt_size,
const void *srk_buf,
size_t srk_buf_size,
TPM2Flags flags,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size);
| 892 | 28.766667 | 48 |
h
|
null |
systemd-main/src/debug-generator/debug-generator.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "alloc-util.h"
#include "dropin.h"
#include "generator.h"
#include "initrd-util.h"
#include "mkdir-label.h"
#include "parse-util.h"
#include "path-util.h"
#include "proc-cmdline.h"
#include "special.h"
#include "string-util.h"
#include "strv.h"
#include "unit-file.h"
#include "unit-name.h"
static const char *arg_dest = NULL;
static char *arg_default_unit = NULL;
static char **arg_mask = NULL;
static char **arg_wants = NULL;
static char *arg_debug_shell = NULL;
STATIC_DESTRUCTOR_REGISTER(arg_default_unit, freep);
STATIC_DESTRUCTOR_REGISTER(arg_mask, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_wants, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_debug_shell, freep);
static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
int r;
assert(key);
if (streq(key, "systemd.mask")) {
char *n;
if (proc_cmdline_value_missing(key, value))
return 0;
r = unit_name_mangle(value, UNIT_NAME_MANGLE_WARN, &n);
if (r < 0)
return log_error_errno(r, "Failed to glob unit name: %m");
r = strv_consume(&arg_mask, n);
if (r < 0)
return log_oom();
} else if (streq(key, "systemd.wants")) {
char *n;
if (proc_cmdline_value_missing(key, value))
return 0;
r = unit_name_mangle(value, UNIT_NAME_MANGLE_WARN, &n);
if (r < 0)
return log_error_errno(r, "Failed to glob unit name: %m");
r = strv_consume(&arg_wants, n);
if (r < 0)
return log_oom();
} else if (proc_cmdline_key_streq(key, "systemd.debug_shell")) {
const char *t = NULL;
r = value ? parse_boolean(value) : 1;
if (r < 0)
t = skip_dev_prefix(value);
else if (r > 0)
t = skip_dev_prefix(DEBUGTTY);
return free_and_strdup_warn(&arg_debug_shell, t);
} else if (streq(key, "systemd.unit")) {
if (proc_cmdline_value_missing(key, value))
return 0;
return free_and_strdup_warn(&arg_default_unit, value);
} else if (!value) {
const char *target;
target = runlevel_to_target(key);
if (target)
return free_and_strdup_warn(&arg_default_unit, target);
}
return 0;
}
static int generate_mask_symlinks(void) {
int r = 0;
STRV_FOREACH(u, arg_mask) {
_cleanup_free_ char *p = NULL;
p = path_join(empty_to_root(arg_dest), *u);
if (!p)
return log_oom();
if (symlink("/dev/null", p) < 0)
r = log_error_errno(errno,
"Failed to create mask symlink %s: %m",
p);
}
return r;
}
static int generate_wants_symlinks(void) {
int r = 0;
STRV_FOREACH(u, arg_wants) {
_cleanup_free_ char *p = NULL, *f = NULL;
const char *target;
/* This should match what do_queue_default_job() in core/main.c does. */
if (arg_default_unit)
target = arg_default_unit;
else if (in_initrd())
target = SPECIAL_INITRD_TARGET;
else
target = SPECIAL_DEFAULT_TARGET;
p = strjoin(arg_dest, "/", target, ".wants/", *u);
if (!p)
return log_oom();
f = path_join(SYSTEM_DATA_UNIT_DIR, *u);
if (!f)
return log_oom();
(void) mkdir_parents_label(p, 0755);
if (symlink(f, p) < 0)
r = log_error_errno(errno,
"Failed to create wants symlink %s: %m",
p);
}
return r;
}
static void install_debug_shell_dropin(const char *dir) {
int r;
if (streq(arg_debug_shell, skip_dev_prefix(DEBUGTTY)))
return;
r = write_drop_in_format(dir, "debug-shell.service", 50, "tty",
"[Unit]\n"
"Description=Early root shell on /dev/%s FOR DEBUGGING ONLY\n"
"ConditionPathExists=\n"
"[Service]\n"
"TTYPath=/dev/%s",
arg_debug_shell, arg_debug_shell);
if (r < 0)
log_warning_errno(r, "Failed to write drop-in for debug-shell.service, ignoring: %m");
}
static int run(const char *dest, const char *dest_early, const char *dest_late) {
int r, q;
assert_se(arg_dest = dest_early);
r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_RD_STRICT | PROC_CMDLINE_STRIP_RD_PREFIX);
if (r < 0)
log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
if (arg_debug_shell) {
r = strv_extend(&arg_wants, "debug-shell.service");
if (r < 0)
return log_oom();
install_debug_shell_dropin(arg_dest);
}
r = generate_mask_symlinks();
q = generate_wants_symlinks();
return r < 0 ? r : q;
}
DEFINE_MAIN_GENERATOR_FUNCTION(run);
| 5,762 | 29.983871 | 117 |
c
|
null |
systemd-main/src/delta/delta.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <getopt.h>
#include <sys/prctl.h>
#include <unistd.h>
#include "alloc-util.h"
#include "build.h"
#include "chase.h"
#include "dirent-util.h"
#include "fd-util.h"
#include "fs-util.h"
#include "glyph-util.h"
#include "hashmap.h"
#include "log.h"
#include "main-func.h"
#include "nulstr-util.h"
#include "pager.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-util.h"
#include "pretty-print.h"
#include "process-util.h"
#include "signal-util.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
static const char prefixes[] =
"/etc\0"
"/run\0"
"/usr/local/lib\0"
"/usr/local/share\0"
"/usr/lib\0"
"/usr/share\0"
#if HAVE_SPLIT_USR
"/lib\0"
#endif
;
static const char suffixes[] =
"sysctl.d\0"
"tmpfiles.d\0"
"modules-load.d\0"
"binfmt.d\0"
"systemd/system\0"
"systemd/user\0"
"systemd/system-preset\0"
"systemd/user-preset\0"
"udev/rules.d\0"
"modprobe.d\0";
static const char have_dropins[] =
"systemd/system\0"
"systemd/user\0";
static PagerFlags arg_pager_flags = 0;
static int arg_diff = -1;
static enum {
SHOW_MASKED = 1 << 0,
SHOW_EQUIVALENT = 1 << 1,
SHOW_REDIRECTED = 1 << 2,
SHOW_OVERRIDDEN = 1 << 3,
SHOW_UNCHANGED = 1 << 4,
SHOW_EXTENDED = 1 << 5,
SHOW_DEFAULTS =
(SHOW_MASKED | SHOW_EQUIVALENT | SHOW_REDIRECTED | SHOW_OVERRIDDEN | SHOW_EXTENDED)
} arg_flags = 0;
static int equivalent(const char *a, const char *b) {
_cleanup_free_ char *x = NULL, *y = NULL;
int r;
r = chase(a, NULL, CHASE_TRAIL_SLASH, &x, NULL);
if (r < 0)
return r;
r = chase(b, NULL, CHASE_TRAIL_SLASH, &y, NULL);
if (r < 0)
return r;
return path_equal(x, y);
}
static int notify_override_masked(const char *top, const char *bottom) {
if (!(arg_flags & SHOW_MASKED))
return 0;
printf("%s%s%s %s %s %s\n",
ansi_highlight_red(), "[MASKED]", ansi_normal(),
top, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), bottom);
return 1;
}
static int notify_override_equivalent(const char *top, const char *bottom) {
if (!(arg_flags & SHOW_EQUIVALENT))
return 0;
printf("%s%s%s %s %s %s\n",
ansi_highlight_green(), "[EQUIVALENT]", ansi_normal(),
top, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), bottom);
return 1;
}
static int notify_override_redirected(const char *top, const char *bottom) {
if (!(arg_flags & SHOW_REDIRECTED))
return 0;
printf("%s%s%s %s %s %s\n",
ansi_highlight(), "[REDIRECTED]", ansi_normal(),
top, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), bottom);
return 1;
}
static int notify_override_overridden(const char *top, const char *bottom) {
if (!(arg_flags & SHOW_OVERRIDDEN))
return 0;
printf("%s%s%s %s %s %s\n",
ansi_highlight(), "[OVERRIDDEN]", ansi_normal(),
top, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), bottom);
return 1;
}
static int notify_override_extended(const char *top, const char *bottom) {
if (!(arg_flags & SHOW_EXTENDED))
return 0;
printf("%s%s%s %s %s %s\n",
ansi_highlight(), "[EXTENDED]", ansi_normal(),
top, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), bottom);
return 1;
}
static int notify_override_unchanged(const char *f) {
if (!(arg_flags & SHOW_UNCHANGED))
return 0;
printf("[UNCHANGED] %s\n", f);
return 1;
}
static int found_override(const char *top, const char *bottom) {
_cleanup_free_ char *dest = NULL;
pid_t pid;
int r;
assert(top);
assert(bottom);
if (null_or_empty_path(top) > 0)
return notify_override_masked(top, bottom);
r = readlink_malloc(top, &dest);
if (r >= 0) {
if (equivalent(dest, bottom) > 0)
return notify_override_equivalent(top, bottom);
else
return notify_override_redirected(top, bottom);
}
r = notify_override_overridden(top, bottom);
if (!arg_diff)
return r;
putchar('\n');
fflush(stdout);
r = safe_fork("(diff)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
if (r < 0)
return r;
if (r == 0) {
execlp("diff", "diff", "-us", "--", bottom, top, NULL);
log_open();
log_error_errno(errno, "Failed to execute diff: %m");
_exit(EXIT_FAILURE);
}
(void) wait_for_terminate_and_check("diff", pid, WAIT_LOG_ABNORMAL);
putchar('\n');
return r;
}
static int enumerate_dir_d(
OrderedHashmap *top,
OrderedHashmap *bottom,
OrderedHashmap *drops,
const char *toppath, const char *drop) {
_cleanup_free_ char *unit = NULL;
_cleanup_free_ char *path = NULL;
_cleanup_strv_free_ char **list = NULL;
char *c;
int r;
assert(!endswith(drop, "/"));
path = path_join(toppath, drop);
if (!path)
return -ENOMEM;
log_debug("Looking at %s", path);
unit = strdup(drop);
if (!unit)
return -ENOMEM;
c = strrchr(unit, '.');
if (!c)
return -EINVAL;
*c = 0;
r = get_files_in_directory(path, &list);
if (r < 0)
return log_error_errno(r, "Failed to enumerate %s: %m", path);
strv_sort(list);
STRV_FOREACH(file, list) {
OrderedHashmap *h;
int k;
char *p;
char *d;
if (!endswith(*file, ".conf"))
continue;
p = path_join(path, *file);
if (!p)
return -ENOMEM;
d = p + strlen(toppath) + 1;
log_debug("Adding at top: %s %s %s", d, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), p);
k = ordered_hashmap_put(top, d, p);
if (k >= 0) {
p = strdup(p);
if (!p)
return -ENOMEM;
d = p + strlen(toppath) + 1;
} else if (k != -EEXIST) {
free(p);
return k;
}
log_debug("Adding at bottom: %s %s %s", d, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), p);
free(ordered_hashmap_remove(bottom, d));
k = ordered_hashmap_put(bottom, d, p);
if (k < 0) {
free(p);
return k;
}
h = ordered_hashmap_get(drops, unit);
if (!h) {
h = ordered_hashmap_new(&string_hash_ops);
if (!h)
return -ENOMEM;
ordered_hashmap_put(drops, unit, h);
unit = strdup(unit);
if (!unit)
return -ENOMEM;
}
p = strdup(p);
if (!p)
return -ENOMEM;
log_debug("Adding to drops: %s %s %s %s %s",
unit, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), basename(p), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), p);
k = ordered_hashmap_put(h, basename(p), p);
if (k < 0) {
free(p);
if (k != -EEXIST)
return k;
}
}
return 0;
}
static int enumerate_dir(
OrderedHashmap *top,
OrderedHashmap *bottom,
OrderedHashmap *drops,
const char *path, bool dropins) {
_cleanup_closedir_ DIR *d = NULL;
_cleanup_strv_free_ char **files = NULL, **dirs = NULL;
size_t n_files = 0, n_dirs = 0;
int r;
assert(top);
assert(bottom);
assert(drops);
assert(path);
log_debug("Looking at %s", path);
d = opendir(path);
if (!d) {
if (errno == ENOENT)
return 0;
return log_error_errno(errno, "Failed to open %s: %m", path);
}
FOREACH_DIRENT_ALL(de, d, return -errno) {
if (dropins && de->d_type == DT_DIR && endswith(de->d_name, ".d")) {
if (!GREEDY_REALLOC0(dirs, n_dirs + 2))
return -ENOMEM;
dirs[n_dirs] = strdup(de->d_name);
if (!dirs[n_dirs])
return -ENOMEM;
n_dirs ++;
}
if (!dirent_is_file(de))
continue;
if (!GREEDY_REALLOC0(files, n_files + 2))
return -ENOMEM;
files[n_files] = strdup(de->d_name);
if (!files[n_files])
return -ENOMEM;
n_files ++;
}
strv_sort(dirs);
strv_sort(files);
STRV_FOREACH(t, dirs) {
r = enumerate_dir_d(top, bottom, drops, path, *t);
if (r < 0)
return r;
}
STRV_FOREACH(t, files) {
_cleanup_free_ char *p = NULL;
p = path_join(path, *t);
if (!p)
return -ENOMEM;
log_debug("Adding at top: %s %s %s", basename(p), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), p);
r = ordered_hashmap_put(top, basename(p), p);
if (r >= 0) {
p = strdup(p);
if (!p)
return -ENOMEM;
} else if (r != -EEXIST)
return r;
log_debug("Adding at bottom: %s %s %s", basename(p), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), p);
free(ordered_hashmap_remove(bottom, basename(p)));
r = ordered_hashmap_put(bottom, basename(p), p);
if (r < 0)
return r;
p = NULL;
}
return 0;
}
static int should_skip_path(const char *prefix, const char *suffix) {
#if HAVE_SPLIT_USR
_cleanup_free_ char *target = NULL, *dirname = NULL;
dirname = path_join(prefix, suffix);
if (!dirname)
return -ENOMEM;
if (chase(dirname, NULL, 0, &target, NULL) < 0)
return false;
NULSTR_FOREACH(p, prefixes) {
_cleanup_free_ char *tmp = NULL;
if (path_startswith(dirname, p))
continue;
tmp = path_join(p, suffix);
if (!tmp)
return -ENOMEM;
if (path_equal(target, tmp)) {
log_debug("%s redirects to %s, skipping.", dirname, target);
return true;
}
}
#endif
return false;
}
static int process_suffix(const char *suffix, const char *onlyprefix) {
char *f, *key;
OrderedHashmap *top, *bottom, *drops, *h;
int r = 0, k, n_found = 0;
bool dropins;
assert(suffix);
assert(!startswith(suffix, "/"));
assert(!strstr(suffix, "//"));
dropins = nulstr_contains(have_dropins, suffix);
top = ordered_hashmap_new(&string_hash_ops);
bottom = ordered_hashmap_new(&string_hash_ops);
drops = ordered_hashmap_new(&string_hash_ops);
if (!top || !bottom || !drops) {
r = -ENOMEM;
goto finish;
}
NULSTR_FOREACH(p, prefixes) {
_cleanup_free_ char *t = NULL;
if (should_skip_path(p, suffix) > 0)
continue;
t = path_join(p, suffix);
if (!t) {
r = -ENOMEM;
goto finish;
}
k = enumerate_dir(top, bottom, drops, t, dropins);
if (r == 0)
r = k;
}
ORDERED_HASHMAP_FOREACH_KEY(f, key, top) {
char *o;
o = ordered_hashmap_get(bottom, key);
assert(o);
if (!onlyprefix || startswith(o, onlyprefix)) {
if (path_equal(o, f)) {
notify_override_unchanged(f);
} else {
k = found_override(f, o);
if (k < 0)
r = k;
else
n_found += k;
}
}
h = ordered_hashmap_get(drops, key);
if (h)
ORDERED_HASHMAP_FOREACH(o, h)
if (!onlyprefix || startswith(o, onlyprefix))
n_found += notify_override_extended(f, o);
}
finish:
ordered_hashmap_free_free(top);
ordered_hashmap_free_free(bottom);
ORDERED_HASHMAP_FOREACH_KEY(h, key, drops) {
ordered_hashmap_free_free(ordered_hashmap_remove(drops, key));
ordered_hashmap_remove(drops, key);
free(key);
}
ordered_hashmap_free(drops);
return r < 0 ? r : n_found;
}
static int process_suffixes(const char *onlyprefix) {
int n_found = 0, r;
NULSTR_FOREACH(n, suffixes) {
r = process_suffix(n, onlyprefix);
if (r < 0)
return r;
n_found += r;
}
return n_found;
}
static int process_suffix_chop(const char *arg) {
assert(arg);
if (!path_is_absolute(arg))
return process_suffix(arg, NULL);
/* Strip prefix from the suffix */
NULSTR_FOREACH(p, prefixes) {
const char *suffix;
suffix = startswith(arg, p);
if (suffix) {
suffix += strspn(suffix, "/");
if (*suffix)
return process_suffix(suffix, p);
else
return process_suffixes(arg);
}
}
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Invalid suffix specification %s.", arg);
}
static int help(void) {
_cleanup_free_ char *link = NULL;
int r;
r = terminal_urlify_man("systemd-delta", "1", &link);
if (r < 0)
return log_oom();
printf("%s [OPTIONS...] [SUFFIX...]\n\n"
"Find overridden configuration files.\n\n"
" -h --help Show this help\n"
" --version Show package version\n"
" --no-pager Do not pipe output into a pager\n"
" --diff[=1|0] Show a diff when overridden files differ\n"
" -t --type=LIST... Only display a selected set of override types\n"
"\nSee the %s for details.\n",
program_invocation_short_name,
link);
return 0;
}
static int parse_flags(const char *flag_str, int flags) {
for (;;) {
_cleanup_free_ char *word = NULL;
int r;
r = extract_first_word(&flag_str, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS);
if (r < 0)
return r;
if (r == 0)
return flags;
if (streq(word, "masked"))
flags |= SHOW_MASKED;
else if (streq(word, "equivalent"))
flags |= SHOW_EQUIVALENT;
else if (streq(word, "redirected"))
flags |= SHOW_REDIRECTED;
else if (streq(word, "overridden"))
flags |= SHOW_OVERRIDDEN;
else if (streq(word, "unchanged"))
flags |= SHOW_UNCHANGED;
else if (streq(word, "extended"))
flags |= SHOW_EXTENDED;
else if (streq(word, "default"))
flags |= SHOW_DEFAULTS;
else
return -EINVAL;
}
}
static int parse_argv(int argc, char *argv[]) {
enum {
ARG_NO_PAGER = 0x100,
ARG_DIFF,
ARG_VERSION
};
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, ARG_VERSION },
{ "no-pager", no_argument, NULL, ARG_NO_PAGER },
{ "diff", optional_argument, NULL, ARG_DIFF },
{ "type", required_argument, NULL, 't' },
{}
};
int c, r;
assert(argc >= 1);
assert(argv);
while ((c = getopt_long(argc, argv, "ht:", options, NULL)) >= 0)
switch (c) {
case 'h':
return help();
case ARG_VERSION:
return version();
case ARG_NO_PAGER:
arg_pager_flags |= PAGER_DISABLE;
break;
case 't': {
int f;
f = parse_flags(optarg, arg_flags);
if (f < 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Failed to parse flags field.");
arg_flags = f;
break;
}
case ARG_DIFF:
r = parse_boolean_argument("--diff", optarg, NULL);
if (r < 0)
return r;
arg_diff = r;
break;
case '?':
return -EINVAL;
default:
assert_not_reached();
}
return 1;
}
static int run(int argc, char *argv[]) {
int r, k, n_found = 0;
log_setup();
r = parse_argv(argc, argv);
if (r <= 0)
return r;
if (arg_flags == 0)
arg_flags = SHOW_DEFAULTS;
if (arg_diff < 0)
arg_diff = !!(arg_flags & SHOW_OVERRIDDEN);
else if (arg_diff)
arg_flags |= SHOW_OVERRIDDEN;
pager_open(arg_pager_flags);
if (optind < argc) {
int i;
for (i = optind; i < argc; i++) {
path_simplify(argv[i]);
k = process_suffix_chop(argv[i]);
if (k < 0)
r = k;
else
n_found += k;
}
} else {
k = process_suffixes(NULL);
if (k < 0)
r = k;
else
n_found += k;
}
if (r >= 0)
printf("%s%i overridden configuration files found.\n", n_found ? "\n" : "", n_found);
return r;
}
DEFINE_MAIN_FUNCTION(run);
| 20,287 | 29.011834 | 132 |
c
|
null |
systemd-main/src/detect-virt/detect-virt.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <getopt.h>
#include <stdbool.h>
#include <stdlib.h>
#include "alloc-util.h"
#include "build.h"
#include "confidential-virt.h"
#include "main-func.h"
#include "pretty-print.h"
#include "string-table.h"
#include "virt.h"
static bool arg_quiet = false;
static enum {
ANY_VIRTUALIZATION,
ONLY_VM,
ONLY_CONTAINER,
ONLY_CHROOT,
ONLY_PRIVATE_USERS,
ONLY_CVM,
} arg_mode = ANY_VIRTUALIZATION;
static int help(void) {
_cleanup_free_ char *link = NULL;
int r;
r = terminal_urlify_man("systemd-detect-virt", "1", &link);
if (r < 0)
return log_oom();
printf("%s [OPTIONS...]\n\n"
"Detect execution in a virtualized environment.\n\n"
" -h --help Show this help\n"
" --version Show package version\n"
" -c --container Only detect whether we are run in a container\n"
" -v --vm Only detect whether we are run in a VM\n"
" -r --chroot Detect whether we are run in a chroot() environment\n"
" --private-users Only detect whether we are running in a user namespace\n"
" --cvm Only detect whether we are run in a confidential VM\n"
" -q --quiet Don't output anything, just set return value\n"
" --list List all known and detectable types of virtualization\n"
" --list-cvm List all known and detectable types of confidential \n"
" virtualization\n"
"\nSee the %s for details.\n",
program_invocation_short_name,
link);
return 0;
}
static int parse_argv(int argc, char *argv[]) {
enum {
ARG_VERSION = 0x100,
ARG_PRIVATE_USERS,
ARG_LIST,
ARG_CVM,
ARG_LIST_CVM,
};
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, ARG_VERSION },
{ "container", no_argument, NULL, 'c' },
{ "vm", no_argument, NULL, 'v' },
{ "chroot", no_argument, NULL, 'r' },
{ "private-users", no_argument, NULL, ARG_PRIVATE_USERS },
{ "quiet", no_argument, NULL, 'q' },
{ "cvm", no_argument, NULL, ARG_CVM },
{ "list", no_argument, NULL, ARG_LIST },
{ "list-cvm", no_argument, NULL, ARG_LIST_CVM },
{}
};
int c;
assert(argc >= 0);
assert(argv);
while ((c = getopt_long(argc, argv, "hqcvr", options, NULL)) >= 0)
switch (c) {
case 'h':
return help();
case ARG_VERSION:
return version();
case 'q':
arg_quiet = true;
break;
case 'c':
arg_mode = ONLY_CONTAINER;
break;
case ARG_PRIVATE_USERS:
arg_mode = ONLY_PRIVATE_USERS;
break;
case 'v':
arg_mode = ONLY_VM;
break;
case 'r':
arg_mode = ONLY_CHROOT;
break;
case ARG_LIST:
DUMP_STRING_TABLE(virtualization, Virtualization, _VIRTUALIZATION_MAX);
return 0;
case ARG_CVM:
arg_mode = ONLY_CVM;
return 1;
case ARG_LIST_CVM:
DUMP_STRING_TABLE(confidential_virtualization, ConfidentialVirtualization, _CONFIDENTIAL_VIRTUALIZATION_MAX);
return 0;
case '?':
return -EINVAL;
default:
assert_not_reached();
}
if (optind < argc)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"%s takes no arguments.",
program_invocation_short_name);
return 1;
}
static int run(int argc, char *argv[]) {
Virtualization v;
ConfidentialVirtualization c;
int r;
/* This is mostly intended to be used for scripts which want
* to detect whether we are being run in a virtualized
* environment or not */
log_setup();
r = parse_argv(argc, argv);
if (r <= 0)
return r;
switch (arg_mode) {
case ONLY_VM:
v = detect_vm();
if (v < 0)
return log_error_errno(v, "Failed to check for VM: %m");
break;
case ONLY_CONTAINER:
v = detect_container();
if (v < 0)
return log_error_errno(v, "Failed to check for container: %m");
break;
case ONLY_CHROOT:
r = running_in_chroot();
if (r < 0)
return log_error_errno(r, "Failed to check for chroot() environment: %m");
return !r;
case ONLY_PRIVATE_USERS:
r = running_in_userns();
if (r < 0)
return log_error_errno(r, "Failed to check for user namespace: %m");
return !r;
case ONLY_CVM:
c = detect_confidential_virtualization();
if (c < 0)
return log_error_errno(c, "Failed to check for confidential virtualization: %m");
if (!arg_quiet)
puts(confidential_virtualization_to_string(c));
return c == CONFIDENTIAL_VIRTUALIZATION_NONE;
case ANY_VIRTUALIZATION:
default:
v = detect_virtualization();
if (v < 0)
return log_error_errno(v, "Failed to check for virtualization: %m");
break;
}
if (!arg_quiet)
puts(virtualization_to_string(v));
return v == VIRTUALIZATION_NONE;
}
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
| 6,736 | 32.187192 | 133 |
c
|
null |
systemd-main/src/environment-d-generator/environment-d-generator.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "sd-path.h"
#include "conf-files.h"
#include "constants.h"
#include "env-file.h"
#include "escape.h"
#include "glyph-util.h"
#include "log.h"
#include "main-func.h"
#include "path-lookup.h"
#include "strv.h"
static int environment_dirs(char ***ret) {
_cleanup_strv_free_ char **dirs = NULL;
_cleanup_free_ char *c = NULL;
int r;
dirs = strv_new(CONF_PATHS_USR("environment.d"), NULL);
if (!dirs)
return -ENOMEM;
/* ~/.config/systemd/environment.d */
r = sd_path_lookup(SD_PATH_USER_CONFIGURATION, "environment.d", &c);
if (r < 0)
return r;
r = strv_extend_front(&dirs, c);
if (r < 0)
return r;
if (DEBUG_LOGGING) {
_cleanup_free_ char *t = NULL;
t = strv_join(dirs, "\n\t");
log_debug("Looking for environment.d files in (higher priority first):\n\t%s", strna(t));
}
*ret = TAKE_PTR(dirs);
return 0;
}
static int load_and_print(void) {
_cleanup_strv_free_ char **dirs = NULL, **files = NULL, **env = NULL;
int r;
r = environment_dirs(&dirs);
if (r < 0)
return r;
r = conf_files_list_strv(&files, ".conf", NULL, 0, (const char **) dirs);
if (r < 0)
return r;
/* This will mutate the existing environment, based on the presumption
* that in case of failure, a partial update is better than none. */
STRV_FOREACH(i, files) {
log_debug("Reading %s%s", *i, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
r = merge_env_file(&env, NULL, *i);
if (r == -ENOMEM)
return r;
}
STRV_FOREACH(i, env) {
char *t;
_cleanup_free_ char *q = NULL;
t = strchr(*i, '=');
assert(t);
q = shell_maybe_quote(t + 1, 0);
if (!q)
return log_oom();
printf("%.*s=%s\n", (int) (t - *i), *i, q);
}
return 0;
}
static int run(int argc, char *argv[]) {
int r;
log_parse_environment();
log_open();
if (argc > 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes no arguments.");
r = load_and_print();
if (r < 0)
return log_error_errno(r, "Failed to load environment.d: %m");
return 0;
}
DEFINE_MAIN_FUNCTION(run);
| 2,613 | 25.14 | 105 |
c
|
null |
systemd-main/src/fundamental/bootspec-fundamental.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bootspec-fundamental.h"
bool bootspec_pick_name_version_sort_key(
const sd_char *os_pretty_name,
const sd_char *os_image_id,
const sd_char *os_name,
const sd_char *os_id,
const sd_char *os_image_version,
const sd_char *os_version,
const sd_char *os_version_id,
const sd_char *os_build_id,
const sd_char **ret_name,
const sd_char **ret_version,
const sd_char **ret_sort_key) {
const sd_char *good_name, *good_version, *good_sort_key;
/* Find the best human readable title, version string and sort key for a boot entry (using the
* os-release(5) fields). Precise is preferred over vague, and human readable over machine
* readable. Thus:
*
* 1. First priority gets the PRETTY_NAME field, which is the primary string intended for display,
* and should already contain both a nice description and a version indication (if that concept
* applies).
*
* 2. Otherwise we go for IMAGE_ID and IMAGE_VERSION (thus we show details about the image,
* i.e. specific combination of packages and configuration), if that concept applies.
*
* 3. Otherwise we go for NAME and VERSION (i.e. human readable OS name and version)
*
* 4. Otherwise we go for ID and VERSION_ID (i.e. machine readable OS name and version)
*
* 5. Finally, for the version we'll use BUILD_ID (i.e. a machine readable version that identifies
* the original OS build used during installation)
*
* Note that the display logic will show only the name by default, except if that isn't unique in
* which case the version is shown too.
*
* Note that name/version determined here are used only for display purposes. Boot entry preference
* sorting (i.e. algorithmic ordering of boot entries) is done based on the order of the sort key (if
* defined) or entry "id" string (i.e. entry file name) otherwise. */
good_name = os_pretty_name ?: (os_image_id ?: (os_name ?: os_id));
good_version = os_image_version ?: (os_version ?: (os_version_id ?: os_build_id));
good_sort_key = os_image_id ?: os_id;
if (!good_name)
return false;
if (ret_name)
*ret_name = good_name;
if (ret_version)
*ret_version = good_version;
if (ret_sort_key)
*ret_sort_key = good_sort_key;
return true;
}
| 2,728 | 42.31746 | 109 |
c
|
null |
systemd-main/src/fundamental/bootspec-fundamental.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "string-util-fundamental.h"
bool bootspec_pick_name_version_sort_key(
const sd_char *os_pretty_name,
const sd_char *os_image_id,
const sd_char *os_name,
const sd_char *os_id,
const sd_char *os_image_version,
const sd_char *os_version,
const sd_char *os_version_id,
const sd_char *os_build_id,
const sd_char **ret_name,
const sd_char **ret_version,
const sd_char **ret_sort_key);
| 628 | 33.944444 | 48 |
h
|
null |
systemd-main/src/fundamental/confidential-virt-fundamental.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdint.h>
/* Keep CVM detection logic in this file at feature parity with
* that in src/efi/boot/vmm.c */
#define CPUID_PROCESSOR_INFO_AND_FEATURE_BITS UINT32_C(0x1)
/*
* AMD64 Architecture Programmer’s Manual Volume 3:
* General-Purpose and System Instructions.
* Chapter: E4.1 - Maximum Extended Function Number and Vendor String
* https://www.amd.com/system/files/TechDocs/24594.pdf
*/
#define CPUID_GET_HIGHEST_FUNCTION UINT32_C(0x80000000)
/*
* AMD64 Architecture Programmer’s Manual Volume 3:
* General-Purpose and System Instructions.
* Chapter: E4.17 - Encrypted Memory Capabilities
* https://www.amd.com/system/files/TechDocs/24594.pdf
*/
#define CPUID_AMD_GET_ENCRYPTED_MEMORY_CAPABILITIES UINT32_C(0x8000001f)
/*
* AMD64 Architecture Programmer’s Manual Volume 3:
* General-Purpose and System Instructions.
* Chapter: 15.34.10 - SEV_STATUS MSR
* https://www.amd.com/system/files/TechDocs/24593.pdf
*/
#define MSR_AMD64_SEV UINT32_C(0xc0010131)
/*
* Intel® TDX Module v1.5 Base Architecture Specification
* Chapter: 11.2
* https://www.intel.com/content/www/us/en/content-details/733575/intel-tdx-module-v1-5-base-architecture-specification.html
*/
#define CPUID_INTEL_TDX_ENUMERATION UINT32_C(0x21)
/* Requirements for Implementing the Microsoft Hypervisor Interface
* https://learn.microsoft.com/en-us/virtualization/hyper-v-on-windows/tlfs/tlfs
*/
#define CPUID_HYPERV_VENDOR_AND_MAX_FUNCTIONS UINT32_C(0x40000000)
#define CPUID_HYPERV_FEATURES UINT32_C(0x40000003)
#define CPUID_HYPERV_ISOLATION_CONFIG UINT32_C(0x4000000C)
#define CPUID_HYPERV_MIN UINT32_C(0x40000005)
#define CPUID_HYPERV_MAX UINT32_C(0x4000ffff)
#define CPUID_SIG_AMD "AuthenticAMD"
#define CPUID_SIG_INTEL "GenuineIntel"
#define CPUID_SIG_INTEL_TDX "IntelTDX "
#define CPUID_SIG_HYPERV "Microsoft Hv"
/* ecx bit 31: set => hyperpvisor, unset => bare metal */
#define CPUID_FEATURE_HYPERVISOR (UINT32_C(1) << 31)
/* Linux include/asm-generic/hyperv-tlfs.h */
#define CPUID_HYPERV_CPU_MANAGEMENT (UINT32_C(1) << 12) /* root partition */
#define CPUID_HYPERV_ISOLATION (UINT32_C(1) << 22) /* confidential VM partition */
#define CPUID_HYPERV_ISOLATION_TYPE_MASK UINT32_C(0xf)
#define CPUID_HYPERV_ISOLATION_TYPE_SNP 2
#define EAX_SEV (UINT32_C(1) << 1)
#define MSR_SEV (UINT64_C(1) << 0)
#define MSR_SEV_ES (UINT64_C(1) << 1)
#define MSR_SEV_SNP (UINT64_C(1) << 2)
| 2,476 | 32.931507 | 124 |
h
|
null |
systemd-main/src/fundamental/efivars-fundamental.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "efivars-fundamental.h"
static const sd_char * const table[_SECURE_BOOT_MAX] = {
[SECURE_BOOT_UNSUPPORTED] = STR_C("unsupported"),
[SECURE_BOOT_DISABLED] = STR_C("disabled"),
[SECURE_BOOT_UNKNOWN] = STR_C("unknown"),
[SECURE_BOOT_AUDIT] = STR_C("audit"),
[SECURE_BOOT_DEPLOYED] = STR_C("deployed"),
[SECURE_BOOT_SETUP] = STR_C("setup"),
[SECURE_BOOT_USER] = STR_C("user"),
};
const sd_char *secure_boot_mode_to_string(SecureBootMode m) {
return (m >= 0 && m < _SECURE_BOOT_MAX) ? table[m] : NULL;
}
SecureBootMode decode_secure_boot_mode(bool secure, bool audit, bool deployed, bool setup) {
/* See figure 32-4 Secure Boot Modes from UEFI Specification 2.9 */
if (secure && deployed && !audit && !setup)
return SECURE_BOOT_DEPLOYED;
if (secure && !deployed && !audit && !setup)
return SECURE_BOOT_USER;
if (!secure && !deployed && audit && setup)
return SECURE_BOOT_AUDIT;
if (!secure && !deployed && !audit && setup)
return SECURE_BOOT_SETUP;
/* Some firmware allows disabling secure boot while not being in
* setup mode unless the PK is cleared. */
if (!secure && !deployed && !audit && !setup)
return SECURE_BOOT_DISABLED;
/* Well, this should not happen. */
return SECURE_BOOT_UNKNOWN;
}
| 1,510 | 38.763158 | 92 |
c
|
null |
systemd-main/src/fundamental/efivars-fundamental.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#ifdef SD_BOOT
# define EINVAL 22
#else
# include <errno.h>
#endif
#include "string-util-fundamental.h"
/* Features of the loader, i.e. systemd-boot */
#define EFI_LOADER_FEATURE_CONFIG_TIMEOUT (UINT64_C(1) << 0)
#define EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT (UINT64_C(1) << 1)
#define EFI_LOADER_FEATURE_ENTRY_DEFAULT (UINT64_C(1) << 2)
#define EFI_LOADER_FEATURE_ENTRY_ONESHOT (UINT64_C(1) << 3)
#define EFI_LOADER_FEATURE_BOOT_COUNTING (UINT64_C(1) << 4)
#define EFI_LOADER_FEATURE_XBOOTLDR (UINT64_C(1) << 5)
#define EFI_LOADER_FEATURE_RANDOM_SEED (UINT64_C(1) << 6)
#define EFI_LOADER_FEATURE_LOAD_DRIVER (UINT64_C(1) << 7)
#define EFI_LOADER_FEATURE_SORT_KEY (UINT64_C(1) << 8)
#define EFI_LOADER_FEATURE_SAVED_ENTRY (UINT64_C(1) << 9)
#define EFI_LOADER_FEATURE_DEVICETREE (UINT64_C(1) << 10)
#define EFI_LOADER_FEATURE_SECUREBOOT_ENROLL (UINT64_C(1) << 11)
#define EFI_LOADER_FEATURE_RETAIN_SHIM (UINT64_C(1) << 12)
/* Features of the stub, i.e. systemd-stub */
#define EFI_STUB_FEATURE_REPORT_BOOT_PARTITION (UINT64_C(1) << 0)
#define EFI_STUB_FEATURE_PICK_UP_CREDENTIALS (UINT64_C(1) << 1)
#define EFI_STUB_FEATURE_PICK_UP_SYSEXTS (UINT64_C(1) << 2)
#define EFI_STUB_FEATURE_THREE_PCRS (UINT64_C(1) << 3)
#define EFI_STUB_FEATURE_RANDOM_SEED (UINT64_C(1) << 4)
#define EFI_STUB_FEATURE_CMDLINE_ADDONS (UINT64_C(1) << 5)
#define EFI_STUB_FEATURE_CMDLINE_SMBIOS (UINT64_C(1) << 6)
typedef enum SecureBootMode {
SECURE_BOOT_UNSUPPORTED,
SECURE_BOOT_DISABLED,
SECURE_BOOT_UNKNOWN,
SECURE_BOOT_AUDIT,
SECURE_BOOT_DEPLOYED,
SECURE_BOOT_SETUP,
SECURE_BOOT_USER,
_SECURE_BOOT_MAX,
_SECURE_BOOT_INVALID = -EINVAL,
} SecureBootMode;
const sd_char *secure_boot_mode_to_string(SecureBootMode m);
SecureBootMode decode_secure_boot_mode(bool secure, bool audit, bool deployed, bool setup);
| 2,139 | 42.673469 | 91 |
h
|
null |
systemd-main/src/fundamental/logarithm.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdint.h>
/* Note: log2(0) == log2(1) == 0 here and below. */
#define CONST_LOG2ULL(x) ((x) > 1 ? (unsigned) __builtin_clzll(x) ^ 63U : 0)
#define NONCONST_LOG2ULL(x) ({ \
unsigned long long _x = (x); \
_x > 1 ? (unsigned) __builtin_clzll(_x) ^ 63U : 0; \
})
#define LOG2ULL(x) __builtin_choose_expr(__builtin_constant_p(x), CONST_LOG2ULL(x), NONCONST_LOG2ULL(x))
static inline unsigned log2u64(uint64_t x) {
#if __SIZEOF_LONG_LONG__ == 8
return LOG2ULL(x);
#else
# error "Wut?"
#endif
}
static inline unsigned u32ctz(uint32_t n) {
#if __SIZEOF_INT__ == 4
return n != 0 ? __builtin_ctz(n) : 32;
#else
# error "Wut?"
#endif
}
#define popcount(n) \
_Generic((n), \
unsigned char: __builtin_popcount(n), \
unsigned short: __builtin_popcount(n), \
unsigned: __builtin_popcount(n), \
unsigned long: __builtin_popcountl(n), \
unsigned long long: __builtin_popcountll(n))
#define CONST_LOG2U(x) ((x) > 1 ? __SIZEOF_INT__ * 8 - __builtin_clz(x) - 1 : 0)
#define NONCONST_LOG2U(x) ({ \
unsigned _x = (x); \
_x > 1 ? __SIZEOF_INT__ * 8 - __builtin_clz(_x) - 1 : 0; \
})
#define LOG2U(x) __builtin_choose_expr(__builtin_constant_p(x), CONST_LOG2U(x), NONCONST_LOG2U(x))
static inline unsigned log2i(int x) {
return LOG2U(x);
}
static inline unsigned log2u(unsigned x) {
return LOG2U(x);
}
static inline unsigned log2u_round_up(unsigned x) {
if (x <= 1)
return 0;
return log2u(x - 1) + 1;
}
| 1,966 | 31.783333 | 104 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.