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/nspawn/test-patch-uid.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdlib.h>
#include "log.h"
#include "nspawn-patch-uid.h"
#include "user-util.h"
#include "string-util.h"
#include "tests.h"
int main(int argc, char *argv[]) {
uid_t shift, range;
int r;
test_setup_logging(LOG_DEBUG);
if (argc != 4) {
log_error("Expected PATH SHIFT RANGE parameters.");
return EXIT_FAILURE;
}
r = parse_uid(argv[2], &shift);
if (r < 0) {
log_error_errno(r, "Failed to parse UID shift %s.", argv[2]);
return EXIT_FAILURE;
}
r = parse_gid(argv[3], &range);
if (r < 0) {
log_error_errno(r, "Failed to parse UID range %s.", argv[3]);
return EXIT_FAILURE;
}
r = path_patch_uid(argv[1], shift, range);
if (r < 0) {
log_error_errno(r, "Failed to patch directory tree: %m");
return EXIT_FAILURE;
}
log_info("Changed: %s", yes_no(r));
return EXIT_SUCCESS;
}
| 1,090 | 23.795455 | 77 |
c
|
null |
systemd-main/src/nss-myhostname/nss-myhostname.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <net/if.h>
#include <netdb.h>
#include <nss.h>
#include <stdlib.h>
#include "alloc-util.h"
#include "errno-util.h"
#include "hostname-util.h"
#include "local-addresses.h"
#include "macro.h"
#include "nss-util.h"
#include "resolve-util.h"
#include "signal-util.h"
#include "socket-util.h"
#include "string-util.h"
/* We use 127.0.0.2 as IPv4 address. This has the advantage over
* 127.0.0.1 that it can be translated back to the local hostname. For
* IPv6 we use ::1 which unfortunately will not translate back to the
* hostname but instead something like "localhost" or so. */
#define LOCALADDRESS_IPV4 (htobe32(INADDR_LOCALADDRESS))
#define LOCALADDRESS_IPV6 &in6addr_loopback
NSS_GETHOSTBYNAME_PROTOTYPES(myhostname);
NSS_GETHOSTBYADDR_PROTOTYPES(myhostname);
enum nss_status _nss_myhostname_gethostbyname4_r(
const char *name,
struct gaih_addrtuple **pat,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp) {
struct gaih_addrtuple *r_tuple, *r_tuple_prev = NULL;
_cleanup_free_ struct local_address *addresses = NULL;
_cleanup_free_ char *hn = NULL;
const char *canonical = NULL;
int n_addresses = 0;
uint32_t local_address_ipv4;
size_t l, idx, ms;
char *r_name;
PROTECT_ERRNO;
BLOCK_SIGNALS(NSS_SIGNALS_BLOCK);
assert(name);
assert(pat);
assert(buffer);
assert(errnop);
assert(h_errnop);
if (is_localhost(name)) {
/* We respond to 'localhost', so that /etc/hosts is optional */
canonical = "localhost";
local_address_ipv4 = htobe32(INADDR_LOOPBACK);
} else if (is_gateway_hostname(name)) {
n_addresses = local_gateways(NULL, 0, AF_UNSPEC, &addresses);
if (n_addresses <= 0)
goto not_found;
canonical = "_gateway";
} else if (is_outbound_hostname(name)) {
n_addresses = local_outbounds(NULL, 0, AF_UNSPEC, &addresses);
if (n_addresses <= 0)
goto not_found;
canonical = "_outbound";
} else {
hn = gethostname_malloc();
if (!hn) {
UNPROTECT_ERRNO;
*errnop = ENOMEM;
*h_errnop = NO_RECOVERY;
return NSS_STATUS_TRYAGAIN;
}
/* We respond to our local hostname, our hostname suffixed with a single dot. */
if (!streq(name, hn) && !streq_ptr(startswith(name, hn), "."))
goto not_found;
n_addresses = local_addresses(NULL, 0, AF_UNSPEC, &addresses);
if (n_addresses < 0)
n_addresses = 0;
canonical = hn;
local_address_ipv4 = LOCALADDRESS_IPV4;
}
l = strlen(canonical);
ms = ALIGN(l+1) + ALIGN(sizeof(struct gaih_addrtuple)) * (n_addresses > 0 ? n_addresses : 1 + socket_ipv6_is_enabled());
if (buflen < ms) {
UNPROTECT_ERRNO;
*errnop = ERANGE;
*h_errnop = NETDB_INTERNAL;
return NSS_STATUS_TRYAGAIN;
}
/* First, fill in hostname */
r_name = buffer;
memcpy(r_name, canonical, l+1);
idx = ALIGN(l+1);
assert(n_addresses >= 0);
if (n_addresses == 0) {
/* Second, fill in IPv6 tuple */
if (socket_ipv6_is_enabled()) {
r_tuple = (struct gaih_addrtuple*) (buffer + idx);
r_tuple->next = r_tuple_prev;
r_tuple->name = r_name;
r_tuple->family = AF_INET6;
memcpy(r_tuple->addr, LOCALADDRESS_IPV6, 16);
r_tuple->scopeid = 0;
idx += ALIGN(sizeof(struct gaih_addrtuple));
r_tuple_prev = r_tuple;
}
/* Third, fill in IPv4 tuple */
r_tuple = (struct gaih_addrtuple*) (buffer + idx);
r_tuple->next = r_tuple_prev;
r_tuple->name = r_name;
r_tuple->family = AF_INET;
*(uint32_t*) r_tuple->addr = local_address_ipv4;
r_tuple->scopeid = 0;
idx += ALIGN(sizeof(struct gaih_addrtuple));
r_tuple_prev = r_tuple;
}
/* Fourth, fill actual addresses in, but in backwards order */
for (int i = n_addresses; i > 0; i--) {
struct local_address *a = addresses + i - 1;
r_tuple = (struct gaih_addrtuple*) (buffer + idx);
r_tuple->next = r_tuple_prev;
r_tuple->name = r_name;
r_tuple->family = a->family;
r_tuple->scopeid = a->family == AF_INET6 && in6_addr_is_link_local(&a->address.in6) ? a->ifindex : 0;
memcpy(r_tuple->addr, &a->address, 16);
idx += ALIGN(sizeof(struct gaih_addrtuple));
r_tuple_prev = r_tuple;
}
/* Verify the size matches */
assert(idx == ms);
/* Nscd expects us to store the first record in **pat. */
if (*pat)
**pat = *r_tuple_prev;
else
*pat = r_tuple_prev;
if (ttlp)
*ttlp = 0;
/* Explicitly reset both *h_errnop and h_errno to work around
* https://bugzilla.redhat.com/show_bug.cgi?id=1125975 */
*h_errnop = NETDB_SUCCESS;
h_errno = 0;
return NSS_STATUS_SUCCESS;
not_found:
*h_errnop = HOST_NOT_FOUND;
return NSS_STATUS_NOTFOUND;
}
static enum nss_status fill_in_hostent(
const char *canonical, const char *additional,
int af,
struct local_address *addresses, unsigned n_addresses,
uint32_t local_address_ipv4,
struct hostent *result,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp,
char **canonp) {
size_t l_canonical, l_additional, idx, ms, alen;
char *r_addr, *r_name, *r_aliases, *r_alias = NULL, *r_addr_list;
struct local_address *a;
unsigned n, c;
assert(canonical);
assert(IN_SET(af, AF_INET, AF_INET6));
assert(result);
assert(buffer);
assert(errnop);
assert(h_errnop);
PROTECT_ERRNO;
alen = FAMILY_ADDRESS_SIZE(af);
for (a = addresses, n = 0, c = 0; n < n_addresses; a++, n++)
if (af == a->family)
c++;
l_canonical = strlen(canonical);
l_additional = strlen_ptr(additional);
ms = ALIGN(l_canonical+1)+
(additional ? ALIGN(l_additional+1) : 0) +
sizeof(char*) +
(additional ? sizeof(char*) : 0) +
(c > 0 ? c : af == AF_INET ? 1 : socket_ipv6_is_enabled()) * ALIGN(alen) +
(c > 0 ? c+1 : af == AF_INET ? 2 : (unsigned) socket_ipv6_is_enabled() + 1) * sizeof(char*);
if (buflen < ms) {
UNPROTECT_ERRNO;
*errnop = ERANGE;
*h_errnop = NETDB_INTERNAL;
return NSS_STATUS_TRYAGAIN;
}
/* First, fill in hostnames */
r_name = buffer;
memcpy(r_name, canonical, l_canonical+1);
idx = ALIGN(l_canonical+1);
if (additional) {
r_alias = buffer + idx;
memcpy(r_alias, additional, l_additional+1);
idx += ALIGN(l_additional+1);
}
/* Second, create aliases array */
r_aliases = buffer + idx;
if (additional) {
((char**) r_aliases)[0] = r_alias;
((char**) r_aliases)[1] = NULL;
idx += 2*sizeof(char*);
} else {
((char**) r_aliases)[0] = NULL;
idx += sizeof(char*);
}
/* Third, add addresses */
r_addr = buffer + idx;
if (c > 0) {
unsigned i = 0;
for (a = addresses, n = 0; n < n_addresses; a++, n++) {
if (af != a->family)
continue;
memcpy(r_addr + i*ALIGN(alen), &a->address, alen);
i++;
}
assert(i == c);
idx += c*ALIGN(alen);
} else if (af == AF_INET) {
*(uint32_t*) r_addr = local_address_ipv4;
idx += ALIGN(alen);
} else if (socket_ipv6_is_enabled()) {
memcpy(r_addr, LOCALADDRESS_IPV6, 16);
idx += ALIGN(alen);
}
/* Fourth, add address pointer array */
r_addr_list = buffer + idx;
if (c > 0) {
unsigned i;
for (i = 0; i < c; i++)
((char**) r_addr_list)[i] = r_addr + i*ALIGN(alen);
((char**) r_addr_list)[i] = NULL;
idx += (c+1) * sizeof(char*);
} else if (af == AF_INET || socket_ipv6_is_enabled()) {
((char**) r_addr_list)[0] = r_addr;
((char**) r_addr_list)[1] = NULL;
idx += 2 * sizeof(char*);
} else {
((char**) r_addr_list)[0] = NULL;
idx += sizeof(char*);
}
/* Verify the size matches */
assert(idx == ms);
result->h_name = r_name;
result->h_aliases = (char**) r_aliases;
result->h_addrtype = af;
result->h_length = alen;
result->h_addr_list = (char**) r_addr_list;
if (ttlp)
*ttlp = 0;
if (canonp)
*canonp = r_name;
/* Explicitly reset both *h_errnop and h_errno to work around
* https://bugzilla.redhat.com/show_bug.cgi?id=1125975 */
*h_errnop = NETDB_SUCCESS;
h_errno = 0;
return NSS_STATUS_SUCCESS;
}
enum nss_status _nss_myhostname_gethostbyname3_r(
const char *name,
int af,
struct hostent *host,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp,
char **canonp) {
_cleanup_free_ struct local_address *addresses = NULL;
const char *canonical, *additional = NULL;
_cleanup_free_ char *hn = NULL;
uint32_t local_address_ipv4 = 0;
int n_addresses = 0;
PROTECT_ERRNO;
BLOCK_SIGNALS(NSS_SIGNALS_BLOCK);
assert(name);
assert(host);
assert(buffer);
assert(errnop);
assert(h_errnop);
if (af == AF_UNSPEC)
af = AF_INET;
if (!IN_SET(af, AF_INET, AF_INET6)) {
UNPROTECT_ERRNO;
*errnop = EAFNOSUPPORT;
*h_errnop = NO_DATA;
return NSS_STATUS_UNAVAIL;
}
if (af == AF_INET6 && !socket_ipv6_is_enabled())
goto not_found;
if (is_localhost(name)) {
canonical = "localhost";
local_address_ipv4 = htobe32(INADDR_LOOPBACK);
} else if (is_gateway_hostname(name)) {
n_addresses = local_gateways(NULL, 0, af, &addresses);
if (n_addresses <= 0)
goto not_found;
canonical = "_gateway";
} else if (is_outbound_hostname(name)) {
n_addresses = local_outbounds(NULL, 0, af, &addresses);
if (n_addresses <= 0)
goto not_found;
canonical = "_outbound";
} else {
hn = gethostname_malloc();
if (!hn) {
UNPROTECT_ERRNO;
*errnop = ENOMEM;
*h_errnop = NO_RECOVERY;
return NSS_STATUS_TRYAGAIN;
}
if (!streq(name, hn) && !streq_ptr(startswith(name, hn), "."))
goto not_found;
n_addresses = local_addresses(NULL, 0, af, &addresses);
if (n_addresses < 0)
n_addresses = 0;
canonical = hn;
additional = n_addresses <= 0 && af == AF_INET6 ? "localhost" : NULL;
local_address_ipv4 = LOCALADDRESS_IPV4;
}
UNPROTECT_ERRNO;
return fill_in_hostent(
canonical, additional,
af,
addresses, n_addresses,
local_address_ipv4,
host,
buffer, buflen,
errnop, h_errnop,
ttlp,
canonp);
not_found:
*h_errnop = HOST_NOT_FOUND;
return NSS_STATUS_NOTFOUND;
}
enum nss_status _nss_myhostname_gethostbyaddr2_r(
const void* addr, socklen_t len,
int af,
struct hostent *host,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp) {
const char *canonical = NULL, *additional = NULL;
uint32_t local_address_ipv4 = LOCALADDRESS_IPV4;
_cleanup_free_ struct local_address *addresses = NULL;
_cleanup_free_ char *hn = NULL;
int n_addresses = 0;
struct local_address *a;
bool additional_from_hostname = false;
unsigned n;
PROTECT_ERRNO;
BLOCK_SIGNALS(NSS_SIGNALS_BLOCK);
assert(addr);
assert(host);
assert(buffer);
assert(errnop);
assert(h_errnop);
if (!IN_SET(af, AF_INET, AF_INET6)) {
UNPROTECT_ERRNO;
*errnop = EAFNOSUPPORT;
*h_errnop = NO_DATA;
return NSS_STATUS_UNAVAIL;
}
if (len != FAMILY_ADDRESS_SIZE(af)) {
UNPROTECT_ERRNO;
*errnop = EINVAL;
*h_errnop = NO_RECOVERY;
return NSS_STATUS_UNAVAIL;
}
if (af == AF_INET) {
if ((*(uint32_t*) addr) == LOCALADDRESS_IPV4)
goto found;
if ((*(uint32_t*) addr) == htobe32(INADDR_LOOPBACK)) {
canonical = "localhost";
local_address_ipv4 = htobe32(INADDR_LOOPBACK);
goto found;
}
} else {
assert(af == AF_INET6);
if (!socket_ipv6_is_enabled())
goto not_found;
if (memcmp(addr, LOCALADDRESS_IPV6, 16) == 0) {
canonical = "localhost";
additional_from_hostname = true;
goto found;
}
}
n_addresses = local_addresses(NULL, 0, af, &addresses);
for (a = addresses, n = 0; (int) n < n_addresses; n++, a++)
if (memcmp(addr, &a->address, FAMILY_ADDRESS_SIZE(af)) == 0)
goto found;
addresses = mfree(addresses);
n_addresses = local_gateways(NULL, 0, af, &addresses);
for (a = addresses, n = 0; (int) n < n_addresses; n++, a++)
if (memcmp(addr, &a->address, FAMILY_ADDRESS_SIZE(af)) == 0) {
canonical = "_gateway";
goto found;
}
not_found:
*h_errnop = HOST_NOT_FOUND;
return NSS_STATUS_NOTFOUND;
found:
if (!canonical || additional_from_hostname) {
hn = gethostname_malloc();
if (!hn) {
UNPROTECT_ERRNO;
*errnop = ENOMEM;
*h_errnop = NO_RECOVERY;
return NSS_STATUS_TRYAGAIN;
}
if (!canonical)
canonical = hn;
else
additional = hn;
}
UNPROTECT_ERRNO;
return fill_in_hostent(
canonical, additional,
af,
addresses, n_addresses,
local_address_ipv4,
host,
buffer, buflen,
errnop, h_errnop,
ttlp,
NULL);
}
NSS_GETHOSTBYNAME_FALLBACKS(myhostname);
NSS_GETHOSTBYADDR_FALLBACKS(myhostname);
| 16,870 | 31.196565 | 128 |
c
|
null |
systemd-main/src/nss-mymachines/nss-mymachines.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <netdb.h>
#include <nss.h>
#include <pthread.h>
#include "sd-bus.h"
#include "sd-login.h"
#include "alloc-util.h"
#include "bus-common-errors.h"
#include "bus-locator.h"
#include "env-util.h"
#include "errno-util.h"
#include "format-util.h"
#include "hostname-util.h"
#include "in-addr-util.h"
#include "log.h"
#include "macro.h"
#include "memory-util.h"
#include "nss-util.h"
#include "signal-util.h"
#include "string-util.h"
static void setup_logging_once(void) {
static pthread_once_t once = PTHREAD_ONCE_INIT;
assert_se(pthread_once(&once, log_parse_environment_variables) == 0);
}
#define NSS_ENTRYPOINT_BEGIN \
BLOCK_SIGNALS(NSS_SIGNALS_BLOCK); \
setup_logging_once()
NSS_GETHOSTBYNAME_PROTOTYPES(mymachines);
NSS_GETPW_PROTOTYPES(mymachines);
NSS_GETGR_PROTOTYPES(mymachines);
static int count_addresses(sd_bus_message *m, int af, unsigned *ret) {
unsigned c = 0;
int r;
assert(m);
assert(ret);
while ((r = sd_bus_message_enter_container(m, 'r', "iay")) > 0) {
int family;
r = sd_bus_message_read(m, "i", &family);
if (r < 0)
return r;
r = sd_bus_message_skip(m, "ay");
if (r < 0)
return r;
r = sd_bus_message_exit_container(m);
if (r < 0)
return r;
if (af != AF_UNSPEC && family != af)
continue;
c++;
}
if (r < 0)
return r;
r = sd_bus_message_rewind(m, false);
if (r < 0)
return r;
*ret = c;
return 0;
}
static bool avoid_deadlock(void) {
/* Check whether this lookup might have a chance of deadlocking because we are called from the service manager
* code activating systemd-machined.service. After all, we shouldn't synchronously do lookups to
* systemd-machined if we are required to finish before it can be started. This of course won't detect all
* possible dead locks of this kind, but it should work for the most obvious cases. */
if (geteuid() != 0) /* Ignore the env vars unless we are privileged. */
return false;
return streq_ptr(getenv("SYSTEMD_ACTIVATION_UNIT"), "systemd-machined.service") &&
streq_ptr(getenv("SYSTEMD_ACTIVATION_SCOPE"), "system");
}
enum nss_status _nss_mymachines_gethostbyname4_r(
const char *name,
struct gaih_addrtuple **pat,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp) {
struct gaih_addrtuple *r_tuple, *r_tuple_first = NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message* reply = NULL;
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
_cleanup_free_ int *ifindices = NULL;
_cleanup_free_ char *class = NULL;
size_t l, ms, idx;
unsigned i = 0, c = 0;
char *r_name;
int n_ifindices, r;
PROTECT_ERRNO;
NSS_ENTRYPOINT_BEGIN;
assert(name);
assert(pat);
assert(buffer);
assert(errnop);
assert(h_errnop);
r = sd_machine_get_class(name, &class);
if (r < 0)
goto fail;
if (!streq(class, "container")) {
r = -ENOTTY;
goto fail;
}
n_ifindices = sd_machine_get_ifindices(name, &ifindices);
if (n_ifindices < 0) {
r = n_ifindices;
goto fail;
}
if (avoid_deadlock()) {
r = -EDEADLK;
goto fail;
}
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = bus_call_method(bus, bus_machine_mgr, "GetMachineAddresses", NULL, &reply, "s", name);
if (r < 0)
goto fail;
r = sd_bus_message_enter_container(reply, 'a', "(iay)");
if (r < 0)
goto fail;
r = count_addresses(reply, AF_UNSPEC, &c);
if (r < 0)
goto fail;
if (c <= 0) {
*h_errnop = HOST_NOT_FOUND;
return NSS_STATUS_NOTFOUND;
}
l = strlen(name);
ms = ALIGN(l+1) + ALIGN(sizeof(struct gaih_addrtuple)) * c;
if (buflen < ms) {
UNPROTECT_ERRNO;
*errnop = ERANGE;
*h_errnop = NETDB_INTERNAL;
return NSS_STATUS_TRYAGAIN;
}
/* First, append name */
r_name = buffer;
memcpy(r_name, name, l+1);
idx = ALIGN(l+1);
/* Second, append addresses */
r_tuple_first = (struct gaih_addrtuple*) (buffer + idx);
while ((r = sd_bus_message_enter_container(reply, 'r', "iay")) > 0) {
int family;
const void *a;
size_t sz;
r = sd_bus_message_read(reply, "i", &family);
if (r < 0)
goto fail;
r = sd_bus_message_read_array(reply, 'y', &a, &sz);
if (r < 0)
goto fail;
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto fail;
if (!IN_SET(family, AF_INET, AF_INET6)) {
r = -EAFNOSUPPORT;
goto fail;
}
if (sz != FAMILY_ADDRESS_SIZE(family)) {
r = -EINVAL;
goto fail;
}
r_tuple = (struct gaih_addrtuple*) (buffer + idx);
r_tuple->next = i == c-1 ? NULL : (struct gaih_addrtuple*) ((char*) r_tuple + ALIGN(sizeof(struct gaih_addrtuple)));
r_tuple->name = r_name;
r_tuple->family = family;
r_tuple->scopeid = n_ifindices == 1 ? ifindices[0] : 0;
memcpy(r_tuple->addr, a, sz);
idx += ALIGN(sizeof(struct gaih_addrtuple));
i++;
}
assert(i == c);
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto fail;
assert(idx == ms);
if (*pat)
**pat = *r_tuple_first;
else
*pat = r_tuple_first;
if (ttlp)
*ttlp = 0;
/* Explicitly reset both *h_errnop and h_errno to work around
* https://bugzilla.redhat.com/show_bug.cgi?id=1125975 */
*h_errnop = NETDB_SUCCESS;
h_errno = 0;
return NSS_STATUS_SUCCESS;
fail:
UNPROTECT_ERRNO;
*errnop = -r;
*h_errnop = NO_RECOVERY;
return NSS_STATUS_UNAVAIL;
}
enum nss_status _nss_mymachines_gethostbyname3_r(
const char *name,
int af,
struct hostent *result,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp,
char **canonp) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message* reply = NULL;
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
_cleanup_free_ char *class = NULL;
unsigned c = 0, i = 0;
char *r_name, *r_aliases, *r_addr, *r_addr_list;
size_t l, idx, ms, alen;
int r;
PROTECT_ERRNO;
NSS_ENTRYPOINT_BEGIN;
assert(name);
assert(result);
assert(buffer);
assert(errnop);
assert(h_errnop);
if (af == AF_UNSPEC)
af = AF_INET;
if (af != AF_INET && af != AF_INET6) {
r = -EAFNOSUPPORT;
goto fail;
}
r = sd_machine_get_class(name, &class);
if (r < 0)
goto fail;
if (!streq(class, "container")) {
r = -ENOTTY;
goto fail;
}
if (avoid_deadlock()) {
r = -EDEADLK;
goto fail;
}
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = bus_call_method(bus, bus_machine_mgr, "GetMachineAddresses", NULL, &reply, "s", name);
if (r < 0)
goto fail;
r = sd_bus_message_enter_container(reply, 'a', "(iay)");
if (r < 0)
goto fail;
r = count_addresses(reply, af, &c);
if (r < 0)
goto fail;
if (c <= 0) {
*h_errnop = HOST_NOT_FOUND;
return NSS_STATUS_NOTFOUND;
}
alen = FAMILY_ADDRESS_SIZE(af);
l = strlen(name);
ms = ALIGN(l+1) + c * ALIGN(alen) + (c+2) * sizeof(char*);
if (buflen < ms) {
UNPROTECT_ERRNO;
*errnop = ERANGE;
*h_errnop = NETDB_INTERNAL;
return NSS_STATUS_TRYAGAIN;
}
/* First, append name */
r_name = buffer;
memcpy(r_name, name, l+1);
idx = ALIGN(l+1);
/* Second, create aliases array */
r_aliases = buffer + idx;
((char**) r_aliases)[0] = NULL;
idx += sizeof(char*);
/* Third, append addresses */
r_addr = buffer + idx;
while ((r = sd_bus_message_enter_container(reply, 'r', "iay")) > 0) {
int family;
const void *a;
size_t sz;
r = sd_bus_message_read(reply, "i", &family);
if (r < 0)
goto fail;
r = sd_bus_message_read_array(reply, 'y', &a, &sz);
if (r < 0)
goto fail;
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto fail;
if (family != af)
continue;
if (sz != alen) {
r = -EINVAL;
goto fail;
}
memcpy(r_addr + i*ALIGN(alen), a, alen);
i++;
}
assert(i == c);
idx += c * ALIGN(alen);
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto fail;
/* Third, append address pointer array */
r_addr_list = buffer + idx;
for (i = 0; i < c; i++)
((char**) r_addr_list)[i] = r_addr + i*ALIGN(alen);
((char**) r_addr_list)[i] = NULL;
idx += (c+1) * sizeof(char*);
assert(idx == ms);
result->h_name = r_name;
result->h_aliases = (char**) r_aliases;
result->h_addrtype = af;
result->h_length = alen;
result->h_addr_list = (char**) r_addr_list;
if (ttlp)
*ttlp = 0;
if (canonp)
*canonp = r_name;
/* Explicitly reset both *h_errnop and h_errno to work around
* https://bugzilla.redhat.com/show_bug.cgi?id=1125975 */
*h_errnop = NETDB_SUCCESS;
h_errno = 0;
return NSS_STATUS_SUCCESS;
fail:
UNPROTECT_ERRNO;
*errnop = -r;
*h_errnop = NO_RECOVERY;
return NSS_STATUS_UNAVAIL;
}
NSS_GETHOSTBYNAME_FALLBACKS(mymachines);
enum nss_status _nss_mymachines_getpwnam_r(
const char *name,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
return NSS_STATUS_NOTFOUND;
}
enum nss_status _nss_mymachines_getpwuid_r(
uid_t uid,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
return NSS_STATUS_NOTFOUND;
}
enum nss_status _nss_mymachines_getgrnam_r(
const char *name,
struct group *gr,
char *buffer, size_t buflen,
int *errnop) {
return NSS_STATUS_NOTFOUND;
}
enum nss_status _nss_mymachines_getgrgid_r(
gid_t gid,
struct group *gr,
char *buffer, size_t buflen,
int *errnop) {
return NSS_STATUS_NOTFOUND;
}
| 12,283 | 26.854875 | 132 |
c
|
null |
systemd-main/src/nss-systemd/userdb-glue.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <nss.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include "userdb.h"
UserDBFlags nss_glue_userdb_flags(void);
int nss_pack_user_record(UserRecord *hr, struct passwd *pwd, char *buffer, size_t buflen);
int nss_pack_group_record(GroupRecord *g, char **extra_members, struct group *gr, char *buffer, size_t buflen);
int nss_pack_user_record_shadow(UserRecord *hr, struct spwd *spwd, char *buffer, size_t buflen);
int nss_pack_group_record_shadow(GroupRecord *hr, struct sgrp *sgrp, char *buffer,size_t buflen);
enum nss_status userdb_getpwnam(const char *name, struct passwd *pwd, char *buffer, size_t buflen, int *errnop);
enum nss_status userdb_getpwuid(uid_t uid, struct passwd *pwd, char *buffer, size_t buflen, int *errnop);
enum nss_status userdb_getspnam(const char *name, struct spwd *spwd, char *buffer, size_t buflen, int *errnop);
enum nss_status userdb_getgrnam(const char *name, struct group *gr, char *buffer, size_t buflen, int *errnop);
enum nss_status userdb_getgrgid(gid_t gid, struct group *gr, char *buffer, size_t buflen, int *errnop);
enum nss_status userdb_getsgnam(const char *name, struct sgrp *sgrp, char *buffer, size_t buflen, int *errnop);
| 1,262 | 44.107143 | 112 |
h
|
null |
systemd-main/src/oom/oomctl.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <getopt.h>
#include <unistd.h>
#include "build.h"
#include "bus-error.h"
#include "bus-locator.h"
#include "copy.h"
#include "main-func.h"
#include "pretty-print.h"
#include "terminal-util.h"
#include "verbs.h"
static PagerFlags arg_pager_flags = 0;
static int help(int argc, char *argv[], void *userdata) {
_cleanup_free_ char *link = NULL;
int r;
pager_open(arg_pager_flags);
r = terminal_urlify_man("oomctl", "1", &link);
if (r < 0)
return log_oom();
printf("%1$s [OPTIONS...] COMMAND ...\n\n"
"%2$sManage or inspect the userspace OOM killer.%3$s\n"
"\n%4$sCommands:%5$s\n"
" dump Output the current state of systemd-oomd\n"
"\n%4$sOptions:%5$s\n"
" -h --help Show this help\n"
" --version Show package version\n"
" --no-pager Do not pipe output into a pager\n"
"\nSee the %6$s for details.\n",
program_invocation_short_name,
ansi_highlight(),
ansi_normal(),
ansi_underline(),
ansi_normal(),
link);
return 0;
}
static int dump_state(int argc, char *argv[], void *userdata) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
int fd = -EBADF;
int r;
r = sd_bus_open_system(&bus);
if (r < 0)
return log_error_errno(r, "Failed to connect system bus: %m");
pager_open(arg_pager_flags);
r = bus_call_method(bus, bus_oom_mgr, "DumpByFileDescriptor", &error, &reply, NULL);
if (r < 0)
return log_error_errno(r, "Failed to dump context: %s", bus_error_message(&error, r));
r = sd_bus_message_read(reply, "h", &fd);
if (r < 0)
return bus_log_parse_error(r);
fflush(stdout);
return copy_bytes(fd, STDOUT_FILENO, UINT64_MAX, 0);
}
static int parse_argv(int argc, char *argv[]) {
enum {
ARG_VERSION = 0x100,
ARG_NO_PAGER,
};
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, ARG_VERSION },
{ "no-pager", no_argument, NULL, ARG_NO_PAGER },
{}
};
int c;
assert(argc >= 0);
assert(argv);
while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
switch (c) {
case 'h':
return help(0, NULL, NULL);
case ARG_VERSION:
return version();
case ARG_NO_PAGER:
arg_pager_flags |= PAGER_DISABLE;
break;
case '?':
return -EINVAL;
default:
assert_not_reached();
}
return 1;
}
static int run(int argc, char* argv[]) {
static const Verb verbs[] = {
{ "help", VERB_ANY, VERB_ANY, 0, help },
{ "dump", VERB_ANY, 1, VERB_DEFAULT, dump_state },
{}
};
int r;
log_show_color(true);
log_parse_environment();
log_open();
r = parse_argv(argc, argv);
if (r <= 0)
return r;
return dispatch_verb(argc, argv, verbs, NULL);
}
DEFINE_MAIN_FUNCTION(run);
| 3,915 | 28.223881 | 102 |
c
|
null |
systemd-main/src/oom/oomd-manager-bus.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <linux/capability.h>
#include "bus-common-errors.h"
#include "bus-polkit.h"
#include "data-fd-util.h"
#include "fd-util.h"
#include "oomd-manager-bus.h"
#include "oomd-manager.h"
#include "user-util.h"
static int bus_method_dump_by_fd(sd_bus_message *message, void *userdata, sd_bus_error *error) {
_cleanup_free_ char *dump = NULL;
_cleanup_close_ int fd = -EBADF;
Manager *m = ASSERT_PTR(userdata);
int r;
assert(message);
r = manager_get_dump_string(m, &dump);
if (r < 0)
return r;
fd = acquire_data_fd(dump, strlen(dump), 0);
if (fd < 0)
return fd;
return sd_bus_reply_method_return(message, "h", fd);
}
static const sd_bus_vtable manager_vtable[] = {
SD_BUS_VTABLE_START(0),
SD_BUS_METHOD_WITH_NAMES("DumpByFileDescriptor",
NULL,,
"h",
SD_BUS_PARAM(fd),
bus_method_dump_by_fd,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_SIGNAL_WITH_NAMES("Killed",
"ss",
SD_BUS_PARAM(cgroup)
SD_BUS_PARAM(reason),
0),
SD_BUS_VTABLE_END
};
const BusObjectImplementation manager_object = {
"/org/freedesktop/oom1",
"org.freedesktop.oom1.Manager",
.vtables = BUS_VTABLES(manager_vtable),
};
| 1,601 | 29.226415 | 96 |
c
|
null |
systemd-main/src/oom/oomd.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <getopt.h>
#include "build.h"
#include "bus-log-control-api.h"
#include "bus-object.h"
#include "cgroup-util.h"
#include "conf-parser.h"
#include "daemon-util.h"
#include "fileio.h"
#include "log.h"
#include "main-func.h"
#include "oomd-manager-bus.h"
#include "oomd-manager.h"
#include "parse-util.h"
#include "pretty-print.h"
#include "psi-util.h"
#include "signal-util.h"
static bool arg_dry_run = false;
static int arg_swap_used_limit_permyriad = -1;
static int arg_mem_pressure_limit_permyriad = -1;
static usec_t arg_mem_pressure_usec = 0;
static int parse_config(void) {
static const ConfigTableItem items[] = {
{ "OOM", "SwapUsedLimit", config_parse_permyriad, 0, &arg_swap_used_limit_permyriad },
{ "OOM", "DefaultMemoryPressureLimit", config_parse_permyriad, 0, &arg_mem_pressure_limit_permyriad },
{ "OOM", "DefaultMemoryPressureDurationSec", config_parse_sec, 0, &arg_mem_pressure_usec },
{}
};
return config_parse_config_file("oomd.conf", "OOM\0",
config_item_table_lookup, items,
CONFIG_PARSE_WARN, NULL);
}
static int help(void) {
_cleanup_free_ char *link = NULL;
int r;
r = terminal_urlify_man("systemd-oomd", "8", &link);
if (r < 0)
return log_oom();
printf("%s [OPTIONS...]\n\n"
"Run the userspace out-of-memory (OOM) killer.\n\n"
" -h --help Show this help\n"
" --version Show package version\n"
" --dry-run Only print destructive actions instead of doing them\n"
" --bus-introspect=PATH Write D-Bus XML introspection data\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_DRY_RUN,
ARG_BUS_INTROSPECT,
};
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, ARG_VERSION },
{ "dry-run", no_argument, NULL, ARG_DRY_RUN },
{ "bus-introspect", required_argument, NULL, ARG_BUS_INTROSPECT },
{}
};
int c;
assert(argc >= 0);
assert(argv);
while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
switch (c) {
case 'h':
return help();
case ARG_VERSION:
return version();
case ARG_DRY_RUN:
arg_dry_run = true;
break;
case ARG_BUS_INTROSPECT:
return bus_introspect_implementations(
stdout,
optarg,
BUS_IMPLEMENTATIONS(&manager_object,
&log_control_object));
case '?':
return -EINVAL;
default:
assert_not_reached();
}
if (optind < argc)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"This program takes no arguments.");
return 1;
}
static int run(int argc, char *argv[]) {
_unused_ _cleanup_(notify_on_cleanup) const char *notify_msg = NULL;
_cleanup_(manager_freep) Manager *m = NULL;
_cleanup_free_ char *swap = NULL;
unsigned long long s = 0;
CGroupMask mask;
int r;
log_setup();
r = parse_argv(argc, argv);
if (r <= 0)
return r;
r = parse_config();
if (r < 0)
return r;
/* Do some basic requirement checks for running systemd-oomd. It's not exhaustive as some of the other
* requirements do not have a reliable means to check for in code. */
int n = sd_listen_fds(0);
if (n > 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Received too many file descriptors");
int fd = n == 1 ? SD_LISTEN_FDS_START : -1;
/* SwapTotal is always available in /proc/meminfo and defaults to 0, even on swap-disabled kernels. */
r = get_proc_field("/proc/meminfo", "SwapTotal", WHITESPACE, &swap);
if (r < 0)
return log_error_errno(r, "Failed to get SwapTotal from /proc/meminfo: %m");
r = safe_atollu(swap, &s);
if (r < 0 || s == 0)
log_warning("No swap; memory pressure usage will be degraded");
if (!is_pressure_supported())
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Pressure Stall Information (PSI) is not supported");
r = cg_all_unified();
if (r < 0)
return log_error_errno(r, "Failed to determine whether the unified cgroups hierarchy is used: %m");
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Requires the unified cgroups hierarchy");
r = cg_mask_supported(&mask);
if (r < 0)
return log_error_errno(r, "Failed to get supported cgroup controllers: %m");
if (!FLAGS_SET(mask, CGROUP_MASK_MEMORY))
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Requires the cgroup memory controller.");
assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
if (arg_mem_pressure_usec > 0 && arg_mem_pressure_usec < 1 * USEC_PER_SEC)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "DefaultMemoryPressureDurationSec= must be 0 or at least 1s");
r = manager_new(&m);
if (r < 0)
return log_error_errno(r, "Failed to create manager: %m");
r = manager_start(
m,
arg_dry_run,
arg_swap_used_limit_permyriad,
arg_mem_pressure_limit_permyriad,
arg_mem_pressure_usec,
fd);
if (r < 0)
return log_error_errno(r, "Failed to start up daemon: %m");
notify_msg = notify_start(NOTIFY_READY, NOTIFY_STOPPING);
log_debug("systemd-oomd started%s.", arg_dry_run ? " in dry run mode" : "");
r = sd_event_loop(m->event);
if (r < 0)
return log_error_errno(r, "Event loop failed: %m");
return 0;
}
DEFINE_MAIN_FUNCTION(run);
| 6,966 | 34.186869 | 126 |
c
|
null |
systemd-main/src/oom/test-oomd-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "alloc-util.h"
#include "cgroup-setup.h"
#include "cgroup-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "oomd-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "string-util.h"
#include "strv.h"
#include "tests.h"
#include "tmpfile-util.h"
static int fork_and_sleep(unsigned sleep_min) {
usec_t n, timeout, ts;
pid_t pid = fork();
assert_se(pid >= 0);
if (pid == 0) {
timeout = sleep_min * USEC_PER_MINUTE;
ts = now(CLOCK_MONOTONIC);
for (;;) {
n = now(CLOCK_MONOTONIC);
if (ts + timeout < n) {
log_error("Child timed out waiting to be killed");
abort();
}
sleep(1);
}
}
return pid;
}
static void test_oomd_cgroup_kill(void) {
_cleanup_free_ char *cgroup_root = NULL, *cgroup = NULL;
int pid[2];
int r;
if (geteuid() != 0)
return (void) log_tests_skipped("not root");
if (cg_all_unified() <= 0)
return (void) log_tests_skipped("cgroups are not running in unified mode");
assert_se(cg_pid_get_path(NULL, 0, &cgroup_root) >= 0);
/* Create another cgroup below this one for the pids we forked off. We need this to be managed
* by the test so that pid1 doesn't delete it before we can read the xattrs. */
cgroup = path_join(cgroup_root, "oomdkilltest");
assert_se(cgroup);
assert_se(cg_create(SYSTEMD_CGROUP_CONTROLLER, cgroup) >= 0);
/* If we don't have permissions to set xattrs we're likely in a userns or missing capabilities */
r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, cgroup, "user.oomd_test", "test", 4, 0);
if (ERRNO_IS_PRIVILEGE(r) || ERRNO_IS_NOT_SUPPORTED(r))
return (void) log_tests_skipped("Cannot set user xattrs");
/* Do this twice to also check the increment behavior on the xattrs */
for (int i = 0; i < 2; i++) {
_cleanup_free_ char *v = NULL;
for (int j = 0; j < 2; j++) {
pid[j] = fork_and_sleep(5);
assert_se(cg_attach(SYSTEMD_CGROUP_CONTROLLER, cgroup, pid[j]) >= 0);
}
r = oomd_cgroup_kill(cgroup, false /* recurse */, false /* dry run */);
if (r <= 0) {
log_debug_errno(r, "Failed to kill processes under %s: %m", cgroup);
abort();
}
assert_se(cg_get_xattr_malloc(SYSTEMD_CGROUP_CONTROLLER, cgroup, "user.oomd_ooms", &v) >= 0);
assert_se(streq(v, i == 0 ? "1" : "2"));
v = mfree(v);
/* Wait a bit since processes may take some time to be cleaned up. */
sleep(2);
assert_se(cg_is_empty(SYSTEMD_CGROUP_CONTROLLER, cgroup) == true);
assert_se(cg_get_xattr_malloc(SYSTEMD_CGROUP_CONTROLLER, cgroup, "user.oomd_kill", &v) >= 0);
assert_se(streq(v, i == 0 ? "2" : "4"));
}
}
static void test_oomd_cgroup_context_acquire_and_insert(void) {
_cleanup_hashmap_free_ Hashmap *h1 = NULL, *h2 = NULL;
_cleanup_(oomd_cgroup_context_freep) OomdCGroupContext *ctx = NULL;
_cleanup_free_ char *cgroup = NULL;
OomdCGroupContext *c1, *c2;
CGroupMask mask;
if (geteuid() != 0)
return (void) log_tests_skipped("not root");
if (!is_pressure_supported())
return (void) log_tests_skipped("system does not support pressure");
if (cg_all_unified() <= 0)
return (void) log_tests_skipped("cgroups are not running in unified mode");
assert_se(cg_mask_supported(&mask) >= 0);
if (!FLAGS_SET(mask, CGROUP_MASK_MEMORY))
return (void) log_tests_skipped("cgroup memory controller is not available");
assert_se(cg_pid_get_path(NULL, 0, &cgroup) >= 0);
assert_se(oomd_cgroup_context_acquire(cgroup, &ctx) == 0);
assert_se(streq(ctx->path, cgroup));
assert_se(ctx->current_memory_usage > 0);
assert_se(ctx->memory_min == 0);
assert_se(ctx->memory_low == 0);
assert_se(ctx->swap_usage == 0);
assert_se(ctx->last_pgscan == 0);
assert_se(ctx->pgscan == 0);
ctx = oomd_cgroup_context_free(ctx);
assert_se(oomd_cgroup_context_acquire("", &ctx) == 0);
assert_se(streq(ctx->path, "/"));
assert_se(ctx->current_memory_usage > 0);
/* Test hashmap inserts */
assert_se(h1 = hashmap_new(&oomd_cgroup_ctx_hash_ops));
assert_se(oomd_insert_cgroup_context(NULL, h1, cgroup) == 0);
c1 = hashmap_get(h1, cgroup);
assert_se(c1);
assert_se(oomd_insert_cgroup_context(NULL, h1, cgroup) == -EEXIST);
/* make sure certain values from h1 get updated in h2 */
c1->pgscan = UINT64_MAX;
c1->mem_pressure_limit = 6789;
c1->mem_pressure_limit_hit_start = 42;
c1->last_had_mem_reclaim = 888;
assert_se(h2 = hashmap_new(&oomd_cgroup_ctx_hash_ops));
assert_se(oomd_insert_cgroup_context(h1, h2, cgroup) == 0);
c1 = hashmap_get(h1, cgroup);
c2 = hashmap_get(h2, cgroup);
assert_se(c1);
assert_se(c2);
assert_se(c1 != c2);
assert_se(c2->last_pgscan == UINT64_MAX);
assert_se(c2->mem_pressure_limit == 6789);
assert_se(c2->mem_pressure_limit_hit_start == 42);
assert_se(c2->last_had_mem_reclaim == 888); /* assumes the live pgscan is less than UINT64_MAX */
}
static void test_oomd_update_cgroup_contexts_between_hashmaps(void) {
_cleanup_hashmap_free_ Hashmap *h_old = NULL, *h_new = NULL;
OomdCGroupContext *c_old, *c_new;
char **paths = STRV_MAKE("/0.slice",
"/1.slice");
OomdCGroupContext ctx_old[2] = {
{ .path = paths[0],
.mem_pressure_limit = 5,
.mem_pressure_limit_hit_start = 777,
.last_had_mem_reclaim = 888,
.pgscan = 57 },
{ .path = paths[1],
.mem_pressure_limit = 6,
.mem_pressure_limit_hit_start = 888,
.last_had_mem_reclaim = 888,
.pgscan = 42 },
};
OomdCGroupContext ctx_new[2] = {
{ .path = paths[0],
.pgscan = 57 },
{ .path = paths[1],
.pgscan = 101 },
};
assert_se(h_old = hashmap_new(&string_hash_ops));
assert_se(hashmap_put(h_old, paths[0], &ctx_old[0]) >= 0);
assert_se(hashmap_put(h_old, paths[1], &ctx_old[1]) >= 0);
assert_se(h_new = hashmap_new(&string_hash_ops));
assert_se(hashmap_put(h_new, paths[0], &ctx_new[0]) >= 0);
assert_se(hashmap_put(h_new, paths[1], &ctx_new[1]) >= 0);
oomd_update_cgroup_contexts_between_hashmaps(h_old, h_new);
assert_se(c_old = hashmap_get(h_old, "/0.slice"));
assert_se(c_new = hashmap_get(h_new, "/0.slice"));
assert_se(c_old->pgscan == c_new->last_pgscan);
assert_se(c_old->mem_pressure_limit == c_new->mem_pressure_limit);
assert_se(c_old->mem_pressure_limit_hit_start == c_new->mem_pressure_limit_hit_start);
assert_se(c_old->last_had_mem_reclaim == c_new->last_had_mem_reclaim);
assert_se(c_old = hashmap_get(h_old, "/1.slice"));
assert_se(c_new = hashmap_get(h_new, "/1.slice"));
assert_se(c_old->pgscan == c_new->last_pgscan);
assert_se(c_old->mem_pressure_limit == c_new->mem_pressure_limit);
assert_se(c_old->mem_pressure_limit_hit_start == c_new->mem_pressure_limit_hit_start);
assert_se(c_new->last_had_mem_reclaim > c_old->last_had_mem_reclaim);
}
static void test_oomd_system_context_acquire(void) {
_cleanup_(unlink_tempfilep) char path[] = "/tmp/oomdgetsysctxtestXXXXXX";
_cleanup_close_ int fd = -EBADF;
OomdSystemContext ctx;
if (geteuid() != 0)
return (void) log_tests_skipped("not root");
assert_se((fd = mkostemp_safe(path)) >= 0);
assert_se(oomd_system_context_acquire("/verylikelynonexistentpath", &ctx) == -ENOENT);
assert_se(oomd_system_context_acquire(path, &ctx) == -EINVAL);
assert_se(write_string_file(path, "some\nwords\nacross\nmultiple\nlines", WRITE_STRING_FILE_CREATE) == 0);
assert_se(oomd_system_context_acquire(path, &ctx) == -EINVAL);
assert_se(write_string_file(path, "MemTotal: 32495256 kB trailing\n"
"MemFree: 9880512 kB data\n"
"SwapTotal: 8388604 kB is\n"
"SwapFree: 7604 kB bad\n", WRITE_STRING_FILE_CREATE) == 0);
assert_se(oomd_system_context_acquire(path, &ctx) == -EINVAL);
assert_se(write_string_file(path, "MemTotal: 32495256 kB\n"
"MemFree: 9880512 kB\n"
"MemAvailable: 21777088 kB\n"
"Buffers: 5968 kB\n"
"Cached: 14344796 kB\n"
"Unevictable: 740004 kB\n"
"Mlocked: 4484 kB\n"
"SwapTotal: 8388604 kB\n"
"SwapFree: 7604 kB\n", WRITE_STRING_FILE_CREATE) == 0);
assert_se(oomd_system_context_acquire(path, &ctx) == 0);
assert_se(ctx.mem_total == 33275142144);
assert_se(ctx.mem_used == 10975404032);
assert_se(ctx.swap_total == 8589930496);
assert_se(ctx.swap_used == 8582144000);
}
static void test_oomd_pressure_above(void) {
_cleanup_hashmap_free_ Hashmap *h1 = NULL, *h2 = NULL;
_cleanup_set_free_ Set *t1 = NULL, *t2 = NULL, *t3 = NULL;
OomdCGroupContext ctx[2] = {}, *c;
loadavg_t threshold;
assert_se(store_loadavg_fixed_point(80, 0, &threshold) == 0);
/* /herp.slice */
assert_se(store_loadavg_fixed_point(99, 99, &(ctx[0].memory_pressure.avg10)) == 0);
assert_se(store_loadavg_fixed_point(99, 99, &(ctx[0].memory_pressure.avg60)) == 0);
assert_se(store_loadavg_fixed_point(99, 99, &(ctx[0].memory_pressure.avg300)) == 0);
ctx[0].mem_pressure_limit = threshold;
/* /derp.slice */
assert_se(store_loadavg_fixed_point(1, 11, &(ctx[1].memory_pressure.avg10)) == 0);
assert_se(store_loadavg_fixed_point(1, 11, &(ctx[1].memory_pressure.avg60)) == 0);
assert_se(store_loadavg_fixed_point(1, 11, &(ctx[1].memory_pressure.avg300)) == 0);
ctx[1].mem_pressure_limit = threshold;
/* High memory pressure */
assert_se(h1 = hashmap_new(&string_hash_ops));
assert_se(hashmap_put(h1, "/herp.slice", &ctx[0]) >= 0);
assert_se(oomd_pressure_above(h1, 0 /* duration */, &t1) == 1);
assert_se(set_contains(t1, &ctx[0]));
assert_se(c = hashmap_get(h1, "/herp.slice"));
assert_se(c->mem_pressure_limit_hit_start > 0);
/* Low memory pressure */
assert_se(h2 = hashmap_new(&string_hash_ops));
assert_se(hashmap_put(h2, "/derp.slice", &ctx[1]) >= 0);
assert_se(oomd_pressure_above(h2, 0 /* duration */, &t2) == 0);
assert_se(!t2);
assert_se(c = hashmap_get(h2, "/derp.slice"));
assert_se(c->mem_pressure_limit_hit_start == 0);
/* High memory pressure w/ multiple cgroups */
assert_se(hashmap_put(h1, "/derp.slice", &ctx[1]) >= 0);
assert_se(oomd_pressure_above(h1, 0 /* duration */, &t3) == 1);
assert_se(set_contains(t3, &ctx[0]));
assert_se(set_size(t3) == 1);
assert_se(c = hashmap_get(h1, "/herp.slice"));
assert_se(c->mem_pressure_limit_hit_start > 0);
assert_se(c = hashmap_get(h1, "/derp.slice"));
assert_se(c->mem_pressure_limit_hit_start == 0);
}
static void test_oomd_mem_and_swap_free_below(void) {
OomdSystemContext ctx = (OomdSystemContext) {
.mem_total = 20971512 * 1024U,
.mem_used = 3310136 * 1024U,
.swap_total = 20971512 * 1024U,
.swap_used = 20971440 * 1024U,
};
assert_se(oomd_mem_available_below(&ctx, 2000) == false);
assert_se(oomd_swap_free_below(&ctx, 2000) == true);
ctx = (OomdSystemContext) {
.mem_total = 20971512 * 1024U,
.mem_used = 20971440 * 1024U,
.swap_total = 20971512 * 1024U,
.swap_used = 3310136 * 1024U,
};
assert_se(oomd_mem_available_below(&ctx, 2000) == true);
assert_se(oomd_swap_free_below(&ctx, 2000) == false);
ctx = (OomdSystemContext) {
.mem_total = 0,
.mem_used = 0,
.swap_total = 0,
.swap_used = 0,
};
assert_se(oomd_mem_available_below(&ctx, 2000) == false);
assert_se(oomd_swap_free_below(&ctx, 2000) == false);
}
static void test_oomd_sort_cgroups(void) {
_cleanup_hashmap_free_ Hashmap *h = NULL;
_cleanup_free_ OomdCGroupContext **sorted_cgroups;
char **paths = STRV_MAKE("/herp.slice",
"/herp.slice/derp.scope",
"/herp.slice/derp.scope/sheep.service",
"/zupa.slice",
"/boop.slice",
"/omitted.slice",
"/avoid.slice");
OomdCGroupContext ctx[7] = {
{ .path = paths[0],
.swap_usage = 20,
.last_pgscan = 0,
.pgscan = 33,
.current_memory_usage = 10 },
{ .path = paths[1],
.swap_usage = 60,
.last_pgscan = 33,
.pgscan = 1,
.current_memory_usage = 20 },
{ .path = paths[2],
.swap_usage = 40,
.last_pgscan = 1,
.pgscan = 33,
.current_memory_usage = 40 },
{ .path = paths[3],
.swap_usage = 10,
.last_pgscan = 33,
.pgscan = 2,
.current_memory_usage = 10 },
{ .path = paths[4],
.swap_usage = 11,
.last_pgscan = 33,
.pgscan = 33,
.current_memory_usage = 10 },
{ .path = paths[5],
.swap_usage = 90,
.last_pgscan = 0,
.pgscan = UINT64_MAX,
.preference = MANAGED_OOM_PREFERENCE_OMIT },
{ .path = paths[6],
.swap_usage = 99,
.last_pgscan = 0,
.pgscan = UINT64_MAX,
.preference = MANAGED_OOM_PREFERENCE_AVOID },
};
assert_se(h = hashmap_new(&string_hash_ops));
assert_se(hashmap_put(h, "/herp.slice", &ctx[0]) >= 0);
assert_se(hashmap_put(h, "/herp.slice/derp.scope", &ctx[1]) >= 0);
assert_se(hashmap_put(h, "/herp.slice/derp.scope/sheep.service", &ctx[2]) >= 0);
assert_se(hashmap_put(h, "/zupa.slice", &ctx[3]) >= 0);
assert_se(hashmap_put(h, "/boop.slice", &ctx[4]) >= 0);
assert_se(hashmap_put(h, "/omitted.slice", &ctx[5]) >= 0);
assert_se(hashmap_put(h, "/avoid.slice", &ctx[6]) >= 0);
assert_se(oomd_sort_cgroup_contexts(h, compare_swap_usage, NULL, &sorted_cgroups) == 6);
assert_se(sorted_cgroups[0] == &ctx[1]);
assert_se(sorted_cgroups[1] == &ctx[2]);
assert_se(sorted_cgroups[2] == &ctx[0]);
assert_se(sorted_cgroups[3] == &ctx[4]);
assert_se(sorted_cgroups[4] == &ctx[3]);
assert_se(sorted_cgroups[5] == &ctx[6]);
sorted_cgroups = mfree(sorted_cgroups);
assert_se(oomd_sort_cgroup_contexts(h, compare_pgscan_rate_and_memory_usage, NULL, &sorted_cgroups) == 6);
assert_se(sorted_cgroups[0] == &ctx[0]);
assert_se(sorted_cgroups[1] == &ctx[2]);
assert_se(sorted_cgroups[2] == &ctx[3]);
assert_se(sorted_cgroups[3] == &ctx[1]);
assert_se(sorted_cgroups[4] == &ctx[4]);
assert_se(sorted_cgroups[5] == &ctx[6]);
sorted_cgroups = mfree(sorted_cgroups);
assert_se(oomd_sort_cgroup_contexts(h, compare_pgscan_rate_and_memory_usage, "/herp.slice/derp.scope", &sorted_cgroups) == 2);
assert_se(sorted_cgroups[0] == &ctx[2]);
assert_se(sorted_cgroups[1] == &ctx[1]);
assert_se(sorted_cgroups[2] == 0);
assert_se(sorted_cgroups[3] == 0);
assert_se(sorted_cgroups[4] == 0);
assert_se(sorted_cgroups[5] == 0);
assert_se(sorted_cgroups[6] == 0);
sorted_cgroups = mfree(sorted_cgroups);
}
static void test_oomd_fetch_cgroup_oom_preference(void) {
_cleanup_(oomd_cgroup_context_freep) OomdCGroupContext *ctx = NULL;
_cleanup_free_ char *cgroup = NULL;
ManagedOOMPreference root_pref;
CGroupMask mask;
bool test_xattrs;
int root_xattrs, r;
if (geteuid() != 0)
return (void) log_tests_skipped("not root");
if (!is_pressure_supported())
return (void) log_tests_skipped("system does not support pressure");
if (cg_all_unified() <= 0)
return (void) log_tests_skipped("cgroups are not running in unified mode");
assert_se(cg_mask_supported(&mask) >= 0);
if (!FLAGS_SET(mask, CGROUP_MASK_MEMORY))
return (void) log_tests_skipped("cgroup memory controller is not available");
assert_se(cg_pid_get_path(NULL, 0, &cgroup) >= 0);
assert_se(oomd_cgroup_context_acquire(cgroup, &ctx) == 0);
/* If we don't have permissions to set xattrs we're likely in a userns or missing capabilities
* so skip the xattr portions of the test. */
r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, cgroup, "user.oomd_test", "1", 1, 0);
test_xattrs = !ERRNO_IS_PRIVILEGE(r) && !ERRNO_IS_NOT_SUPPORTED(r);
if (test_xattrs) {
assert_se(oomd_fetch_cgroup_oom_preference(ctx, NULL) == 0);
assert_se(cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, cgroup, "user.oomd_omit", "1", 1, 0) >= 0);
assert_se(cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, cgroup, "user.oomd_avoid", "1", 1, 0) >= 0);
/* omit takes precedence over avoid when both are set to true */
assert_se(oomd_fetch_cgroup_oom_preference(ctx, NULL) == 0);
assert_se(ctx->preference == MANAGED_OOM_PREFERENCE_OMIT);
} else {
assert_se(oomd_fetch_cgroup_oom_preference(ctx, NULL) < 0);
assert_se(ctx->preference == MANAGED_OOM_PREFERENCE_NONE);
}
ctx = oomd_cgroup_context_free(ctx);
/* also check when only avoid is set to true */
if (test_xattrs) {
assert_se(cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, cgroup, "user.oomd_omit", "0", 1, 0) >= 0);
assert_se(cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, cgroup, "user.oomd_avoid", "1", 1, 0) >= 0);
assert_se(oomd_cgroup_context_acquire(cgroup, &ctx) == 0);
assert_se(oomd_fetch_cgroup_oom_preference(ctx, NULL) == 0);
assert_se(ctx->preference == MANAGED_OOM_PREFERENCE_AVOID);
ctx = oomd_cgroup_context_free(ctx);
}
/* Test the root cgroup */
/* Root cgroup is live and not made on demand like the cgroup the test runs in. It can have varying
* xattrs set already so let's read in the booleans first to get the final preference value. */
assert_se(oomd_cgroup_context_acquire("", &ctx) == 0);
root_xattrs = cg_get_xattr_bool(SYSTEMD_CGROUP_CONTROLLER, "", "user.oomd_omit");
root_pref = root_xattrs > 0 ? MANAGED_OOM_PREFERENCE_OMIT : MANAGED_OOM_PREFERENCE_NONE;
root_xattrs = cg_get_xattr_bool(SYSTEMD_CGROUP_CONTROLLER, "", "user.oomd_avoid");
root_pref = root_xattrs > 0 ? MANAGED_OOM_PREFERENCE_AVOID : MANAGED_OOM_PREFERENCE_NONE;
assert_se(oomd_fetch_cgroup_oom_preference(ctx, NULL) == 0);
assert_se(ctx->preference == root_pref);
assert_se(oomd_fetch_cgroup_oom_preference(ctx, "/herp.slice/derp.scope") == -EINVAL);
/* Assert that avoid/omit are not set if the cgroup and prefix are not
* owned by the same user. */
if (test_xattrs && !empty_or_root(cgroup)) {
ctx = oomd_cgroup_context_free(ctx);
assert_se(cg_set_access(SYSTEMD_CGROUP_CONTROLLER, cgroup, 61183, 0) >= 0);
assert_se(oomd_cgroup_context_acquire(cgroup, &ctx) == 0);
assert_se(oomd_fetch_cgroup_oom_preference(ctx, NULL) == 0);
assert_se(ctx->preference == MANAGED_OOM_PREFERENCE_NONE);
assert_se(oomd_fetch_cgroup_oom_preference(ctx, ctx->path) == 0);
assert_se(ctx->preference == MANAGED_OOM_PREFERENCE_AVOID);
}
}
int main(void) {
int r;
test_setup_logging(LOG_DEBUG);
test_oomd_update_cgroup_contexts_between_hashmaps();
test_oomd_system_context_acquire();
test_oomd_pressure_above();
test_oomd_mem_and_swap_free_below();
test_oomd_sort_cgroups();
/* The following tests operate on live cgroups */
r = enter_cgroup_root(NULL);
if (r < 0)
return log_tests_skipped_errno(r, "failed to enter a test cgroup scope");
test_oomd_cgroup_kill();
test_oomd_cgroup_context_acquire_and_insert();
test_oomd_fetch_cgroup_oom_preference();
return 0;
}
| 22,408 | 42.597276 | 134 |
c
|
null |
systemd-main/src/partition/growfs.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <linux/magic.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/vfs.h>
/* This needs to be included after sys/mount.h, as since [0] linux/btrfs.h
* includes linux/fs.h causing build errors
* See: https://github.com/systemd/systemd/issues/8507
* [0] https://github.com/torvalds/linux/commit/a28135303a669917002f569aecebd5758263e4aa
*/
#include <linux/btrfs.h>
#include "sd-device.h"
#include "blockdev-util.h"
#include "btrfs-util.h"
#include "build.h"
#include "cryptsetup-util.h"
#include "device-nodes.h"
#include "device-util.h"
#include "devnum-util.h"
#include "dissect-image.h"
#include "escape.h"
#include "fd-util.h"
#include "format-util.h"
#include "log.h"
#include "main-func.h"
#include "mountpoint-util.h"
#include "parse-util.h"
#include "pretty-print.h"
#include "resize-fs.h"
static const char *arg_target = NULL;
static bool arg_dry_run = false;
#if HAVE_LIBCRYPTSETUP
static int resize_crypt_luks_device(dev_t devno, const char *fstype, dev_t main_devno) {
_cleanup_free_ char *devpath = NULL, *main_devpath = NULL;
_cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
_cleanup_close_ int main_devfd = -EBADF;
uint64_t size;
int r;
r = dlopen_cryptsetup();
if (r < 0)
return log_error_errno(r, "Cannot resize LUKS device: %m");
main_devfd = r = device_open_from_devnum(S_IFBLK, main_devno, O_RDONLY|O_CLOEXEC, &main_devpath);
if (r < 0)
return log_error_errno(r, "Failed to open main block device " DEVNUM_FORMAT_STR ": %m",
DEVNUM_FORMAT_VAL(main_devno));
if (ioctl(main_devfd, BLKGETSIZE64, &size) != 0)
return log_error_errno(errno, "Failed to query size of \"%s\" (before resize): %m",
main_devpath);
log_debug("%s is %"PRIu64" bytes", main_devpath, size);
r = devname_from_devnum(S_IFBLK, devno, &devpath);
if (r < 0)
return log_error_errno(r, "Failed to get devpath of " DEVNUM_FORMAT_STR ": %m",
DEVNUM_FORMAT_VAL(devno));
r = sym_crypt_init(&cd, devpath);
if (r < 0)
return log_error_errno(r, "crypt_init(\"%s\") failed: %m", devpath);
cryptsetup_enable_logging(cd);
r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
if (r < 0)
return log_debug_errno(r, "Failed to load LUKS metadata for %s: %m", devpath);
if (arg_dry_run)
return 0;
r = sym_crypt_resize(cd, main_devpath, 0);
if (r < 0)
return log_error_errno(r, "crypt_resize() of %s failed: %m", devpath);
if (ioctl(main_devfd, BLKGETSIZE64, &size) != 0)
log_warning_errno(errno, "Failed to query size of \"%s\" (after resize): %m",
devpath);
else
log_debug("%s is now %"PRIu64" bytes", main_devpath, size);
return 1;
}
#endif
static int maybe_resize_underlying_device(
int mountfd,
const char *mountpath,
dev_t main_devno) {
_cleanup_free_ char *devpath = NULL, *fstype = NULL;
dev_t devno;
int r;
assert(mountfd >= 0);
assert(mountpath);
#if HAVE_LIBCRYPTSETUP
cryptsetup_enable_logging(NULL);
#endif
r = get_block_device_harder_fd(mountfd, &devno);
if (r < 0)
return log_error_errno(r, "Failed to determine underlying block device of \"%s\": %m",
mountpath);
if (devno == 0)
return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "File system \"%s\" not backed by block device.", arg_target);
log_debug("Underlying device " DEVNUM_FORMAT_STR ", main dev " DEVNUM_FORMAT_STR ", %s",
DEVNUM_FORMAT_VAL(devno),
DEVNUM_FORMAT_VAL(main_devno),
devno == main_devno ? "same" : "different");
if (devno == main_devno)
return 0;
r = devname_from_devnum(S_IFBLK, devno, &devpath);
if (r < 0)
return log_error_errno(r, "Failed to get devpath for block device " DEVNUM_FORMAT_STR ": %m",
DEVNUM_FORMAT_VAL(devno));
r = probe_filesystem(devpath, &fstype);
if (r == -EUCLEAN)
return log_warning_errno(r, "Cannot reliably determine probe \"%s\", refusing to proceed.", devpath);
if (r < 0)
return log_warning_errno(r, "Failed to probe \"%s\": %m", devpath);
#if HAVE_LIBCRYPTSETUP
if (streq_ptr(fstype, "crypto_LUKS"))
return resize_crypt_luks_device(devno, fstype, main_devno);
#endif
log_debug("Don't know how to resize %s of type %s, ignoring.", devpath, strnull(fstype));
return 0;
}
static int help(void) {
_cleanup_free_ char *link = NULL;
int r;
r = terminal_urlify_man("[email protected]", "8", &link);
if (r < 0)
return log_oom();
printf("%s [OPTIONS...] /path/to/mountpoint\n\n"
"Grow filesystem or encrypted payload to device size.\n\n"
"Options:\n"
" -h --help Show this help and exit\n"
" --version Print version string and exit\n"
" -n --dry-run Just print what would be done\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,
};
int c;
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version" , no_argument, NULL, ARG_VERSION },
{ "dry-run", no_argument, NULL, 'n' },
{}
};
assert(argc >= 0);
assert(argv);
while ((c = getopt_long(argc, argv, "hn", options, NULL)) >= 0)
switch (c) {
case 'h':
return help();
case ARG_VERSION:
return version();
case 'n':
arg_dry_run = true;
break;
case '?':
return -EINVAL;
default:
assert_not_reached();
}
if (optind + 1 != argc)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"%s excepts exactly one argument (the mount point).",
program_invocation_short_name);
arg_target = argv[optind];
return 1;
}
static int run(int argc, char *argv[]) {
_cleanup_close_ int mountfd = -EBADF, devfd = -EBADF;
_cleanup_free_ char *devpath = NULL;
uint64_t size, newsize;
dev_t devno;
int r;
log_setup();
r = parse_argv(argc, argv);
if (r <= 0)
return r;
r = path_is_mount_point(arg_target, NULL, 0);
if (r < 0)
return log_error_errno(r, "Failed to check if \"%s\" is a mount point: %m", arg_target);
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a mount point: %m", arg_target);
mountfd = open(arg_target, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
if (mountfd < 0)
return log_error_errno(errno, "Failed to open \"%s\": %m", arg_target);
r = get_block_device_fd(mountfd, &devno);
if (r == -EUCLEAN)
return btrfs_log_dev_root(LOG_ERR, r, arg_target);
if (r < 0)
return log_error_errno(r, "Failed to determine block device of \"%s\": %m", arg_target);
if (devno == 0)
return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "File system \"%s\" not backed by block device.", arg_target);
r = maybe_resize_underlying_device(mountfd, arg_target, devno);
if (r < 0)
log_warning_errno(r, "Unable to resize underlying device of \"%s\", proceeding anyway: %m", arg_target);
devfd = r = device_open_from_devnum(S_IFBLK, devno, O_RDONLY|O_CLOEXEC, &devpath);
if (r < 0)
return log_error_errno(r, "Failed to open block device " DEVNUM_FORMAT_STR ": %m",
DEVNUM_FORMAT_VAL(devno));
if (ioctl(devfd, BLKGETSIZE64, &size) != 0)
return log_error_errno(errno, "Failed to query size of \"%s\": %m", devpath);
log_debug("Resizing \"%s\" to %"PRIu64" bytes...", arg_target, size);
if (arg_dry_run)
return 0;
r = resize_fs(mountfd, size, &newsize);
if (r < 0)
return log_error_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m",
arg_target, size);
if (newsize == size)
log_info("Successfully resized \"%s\" to %s bytes.",
arg_target,
FORMAT_BYTES(newsize));
else
log_info("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
arg_target,
FORMAT_BYTES(newsize),
size - newsize);
return 0;
}
DEFINE_MAIN_FUNCTION(run);
| 9,789 | 34.215827 | 126 |
c
|
null |
systemd-main/src/partition/makefs.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <sys/file.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "alloc-util.h"
#include "blockdev-util.h"
#include "dissect-image.h"
#include "fd-util.h"
#include "main-func.h"
#include "mkfs-util.h"
#include "path-util.h"
#include "process-util.h"
#include "signal-util.h"
#include "string-util.h"
static int run(int argc, char *argv[]) {
_cleanup_free_ char *device = NULL, *fstype = NULL, *detected = NULL, *label = NULL;
_cleanup_close_ int lock_fd = -EBADF;
sd_id128_t uuid;
struct stat st;
int r;
log_setup();
if (argc != 3)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"This program expects two arguments.");
/* type and device must be copied because makefs calls safe_fork, which clears argv[] */
fstype = strdup(argv[1]);
if (!fstype)
return log_oom();
device = strdup(argv[2]);
if (!device)
return log_oom();
if (stat(device, &st) < 0)
return log_error_errno(errno, "Failed to stat \"%s\": %m", device);
if (S_ISBLK(st.st_mode)) {
/* Lock the device so that udev doesn't interfere with our work */
lock_fd = lock_whole_block_device(st.st_rdev, LOCK_EX);
if (lock_fd < 0)
return log_error_errno(lock_fd, "Failed to lock whole block device of \"%s\": %m", device);
} else
log_debug("%s is not a block device, no need to lock.", device);
r = probe_filesystem(device, &detected);
if (r == -EUCLEAN)
return log_error_errno(r, "Ambiguous results of probing for file system on \"%s\", refusing to proceed.", device);
if (r < 0)
return log_error_errno(r, "Failed to probe \"%s\": %m", device);
if (detected) {
log_info("'%s' is not empty (contains file system of type %s), exiting.", device, detected);
return 0;
}
r = sd_id128_randomize(&uuid);
if (r < 0)
return log_error_errno(r, "Failed to generate UUID for file system: %m");
r = path_extract_filename(device, &label);
if (r < 0)
return log_error_errno(r, "Failed to extract file name from '%s': %m", device);
return make_filesystem(device,
fstype,
label,
/* root = */ NULL,
uuid,
/* discard = */ true,
/* quiet = */ true,
/* sector_size = */ 0,
/* extra_mkfs_options = */ NULL);
}
DEFINE_MAIN_FUNCTION(run);
| 2,942 | 33.623529 | 130 |
c
|
null |
systemd-main/src/path/path.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include "sd-path.h"
#include "alloc-util.h"
#include "build.h"
#include "log.h"
#include "macro.h"
#include "main-func.h"
#include "pretty-print.h"
#include "string-util.h"
static const char *arg_suffix = NULL;
static const char* const path_table[_SD_PATH_MAX] = {
[SD_PATH_TEMPORARY] = "temporary",
[SD_PATH_TEMPORARY_LARGE] = "temporary-large",
[SD_PATH_SYSTEM_BINARIES] = "system-binaries",
[SD_PATH_SYSTEM_INCLUDE] = "system-include",
[SD_PATH_SYSTEM_LIBRARY_PRIVATE] = "system-library-private",
[SD_PATH_SYSTEM_LIBRARY_ARCH] = "system-library-arch",
[SD_PATH_SYSTEM_SHARED] = "system-shared",
[SD_PATH_SYSTEM_CONFIGURATION_FACTORY] = "system-configuration-factory",
[SD_PATH_SYSTEM_STATE_FACTORY] = "system-state-factory",
[SD_PATH_SYSTEM_CONFIGURATION] = "system-configuration",
[SD_PATH_SYSTEM_RUNTIME] = "system-runtime",
[SD_PATH_SYSTEM_RUNTIME_LOGS] = "system-runtime-logs",
[SD_PATH_SYSTEM_STATE_PRIVATE] = "system-state-private",
[SD_PATH_SYSTEM_STATE_LOGS] = "system-state-logs",
[SD_PATH_SYSTEM_STATE_CACHE] = "system-state-cache",
[SD_PATH_SYSTEM_STATE_SPOOL] = "system-state-spool",
[SD_PATH_USER_BINARIES] = "user-binaries",
[SD_PATH_USER_LIBRARY_PRIVATE] = "user-library-private",
[SD_PATH_USER_LIBRARY_ARCH] = "user-library-arch",
[SD_PATH_USER_SHARED] = "user-shared",
[SD_PATH_USER_CONFIGURATION] = "user-configuration",
[SD_PATH_USER_RUNTIME] = "user-runtime",
[SD_PATH_USER_STATE_CACHE] = "user-state-cache",
[SD_PATH_USER_STATE_PRIVATE] = "user-state-private",
[SD_PATH_USER] = "user",
[SD_PATH_USER_DOCUMENTS] = "user-documents",
[SD_PATH_USER_MUSIC] = "user-music",
[SD_PATH_USER_PICTURES] = "user-pictures",
[SD_PATH_USER_VIDEOS] = "user-videos",
[SD_PATH_USER_DOWNLOAD] = "user-download",
[SD_PATH_USER_PUBLIC] = "user-public",
[SD_PATH_USER_TEMPLATES] = "user-templates",
[SD_PATH_USER_DESKTOP] = "user-desktop",
[SD_PATH_SEARCH_BINARIES] = "search-binaries",
[SD_PATH_SEARCH_BINARIES_DEFAULT] = "search-binaries-default",
[SD_PATH_SEARCH_LIBRARY_PRIVATE] = "search-library-private",
[SD_PATH_SEARCH_LIBRARY_ARCH] = "search-library-arch",
[SD_PATH_SEARCH_SHARED] = "search-shared",
[SD_PATH_SEARCH_CONFIGURATION_FACTORY] = "search-configuration-factory",
[SD_PATH_SEARCH_STATE_FACTORY] = "search-state-factory",
[SD_PATH_SEARCH_CONFIGURATION] = "search-configuration",
[SD_PATH_SYSTEMD_UTIL] = "systemd-util",
[SD_PATH_SYSTEMD_SYSTEM_UNIT] = "systemd-system-unit",
[SD_PATH_SYSTEMD_SYSTEM_PRESET] = "systemd-system-preset",
[SD_PATH_SYSTEMD_SYSTEM_CONF] = "systemd-system-conf",
[SD_PATH_SYSTEMD_USER_UNIT] = "systemd-user-unit",
[SD_PATH_SYSTEMD_USER_PRESET] = "systemd-user-preset",
[SD_PATH_SYSTEMD_USER_CONF] = "systemd-user-conf",
[SD_PATH_SYSTEMD_SEARCH_SYSTEM_UNIT] = "systemd-search-system-unit",
[SD_PATH_SYSTEMD_SEARCH_USER_UNIT] = "systemd-search-user-unit",
[SD_PATH_SYSTEMD_SYSTEM_GENERATOR] = "systemd-system-generator",
[SD_PATH_SYSTEMD_USER_GENERATOR] = "systemd-user-generator",
[SD_PATH_SYSTEMD_SEARCH_SYSTEM_GENERATOR] = "systemd-search-system-generator",
[SD_PATH_SYSTEMD_SEARCH_USER_GENERATOR] = "systemd-search-user-generator",
[SD_PATH_SYSTEMD_SLEEP] = "systemd-sleep",
[SD_PATH_SYSTEMD_SHUTDOWN] = "systemd-shutdown",
[SD_PATH_TMPFILES] = "tmpfiles",
[SD_PATH_SYSUSERS] = "sysusers",
[SD_PATH_SYSCTL] = "sysctl",
[SD_PATH_BINFMT] = "binfmt",
[SD_PATH_MODULES_LOAD] = "modules-load",
[SD_PATH_CATALOG] = "catalog",
[SD_PATH_SYSTEMD_SEARCH_NETWORK] = "systemd-search-network",
[SD_PATH_SYSTEMD_SYSTEM_ENVIRONMENT_GENERATOR] = "systemd-system-environment-generator",
[SD_PATH_SYSTEMD_USER_ENVIRONMENT_GENERATOR] = "systemd-user-environment-generator",
[SD_PATH_SYSTEMD_SEARCH_SYSTEM_ENVIRONMENT_GENERATOR] = "systemd-search-system-environment-generator",
[SD_PATH_SYSTEMD_SEARCH_USER_ENVIRONMENT_GENERATOR] = "systemd-search-user-environment-generator",
};
static int list_homes(void) {
uint64_t i = 0;
int r = 0;
for (i = 0; i < ELEMENTSOF(path_table); i++) {
_cleanup_free_ char *p = NULL;
int q;
q = sd_path_lookup(i, arg_suffix, &p);
if (q < 0) {
log_full_errno(q == -ENXIO ? LOG_DEBUG : LOG_ERR,
q, "Failed to query %s: %m", path_table[i]);
if (q != -ENXIO)
r = q;
continue;
}
printf("%s%s:%s %s\n", ansi_highlight(), path_table[i], ansi_normal(), p);
}
return r;
}
static int print_home(const char *n) {
uint64_t i = 0;
int r;
for (i = 0; i < ELEMENTSOF(path_table); i++) {
if (streq(path_table[i], n)) {
_cleanup_free_ char *p = NULL;
r = sd_path_lookup(i, arg_suffix, &p);
if (r < 0)
return log_error_errno(r, "Failed to query %s: %m", n);
printf("%s\n", p);
return 0;
}
}
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Path %s not known.", n);
}
static int help(void) {
_cleanup_free_ char *link = NULL;
int r;
r = terminal_urlify_man("systemd-path", "1", &link);
if (r < 0)
return log_oom();
printf("%s [OPTIONS...] [NAME...]\n\n"
"Show system and user paths.\n\n"
" -h --help Show this help\n"
" --version Show package version\n"
" --suffix=SUFFIX Suffix to append to paths\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_SUFFIX,
};
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, ARG_VERSION },
{ "suffix", required_argument, NULL, ARG_SUFFIX },
{}
};
int c;
assert(argc >= 0);
assert(argv);
while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
switch (c) {
case 'h':
return help();
case ARG_VERSION:
return version();
case ARG_SUFFIX:
arg_suffix = optarg;
break;
case '?':
return -EINVAL;
default:
assert_not_reached();
}
return 1;
}
static int run(int argc, char* argv[]) {
int r;
log_show_color(true);
log_parse_environment();
log_open();
r = parse_argv(argc, argv);
if (r <= 0)
return r;
if (argc > optind) {
int i, q;
for (i = optind; i < argc; i++) {
q = print_home(argv[i]);
if (q < 0)
r = q;
}
return r;
} else
return list_homes();
}
DEFINE_MAIN_FUNCTION(run);
| 9,758 | 40.351695 | 110 |
c
|
null |
systemd-main/src/portable/portabled-bus.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "btrfs-util.h"
#include "bus-common-errors.h"
#include "bus-object.h"
#include "bus-polkit.h"
#include "discover-image.h"
#include "fd-util.h"
#include "io-util.h"
#include "missing_capability.h"
#include "portable.h"
#include "portabled-bus.h"
#include "portabled-image-bus.h"
#include "portabled-image.h"
#include "portabled.h"
#include "strv.h"
#include "user-util.h"
static int property_get_pool_path(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
assert(bus);
assert(reply);
return sd_bus_message_append(reply, "s", "/var/lib/portables");
}
static int property_get_pool_usage(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
_cleanup_close_ int fd = -EBADF;
uint64_t usage = UINT64_MAX;
assert(bus);
assert(reply);
fd = open("/var/lib/portables", O_RDONLY|O_CLOEXEC|O_DIRECTORY);
if (fd >= 0) {
BtrfsQuotaInfo q;
if (btrfs_subvol_get_subtree_quota_fd(fd, 0, &q) >= 0)
usage = q.referenced;
}
return sd_bus_message_append(reply, "t", usage);
}
static int property_get_pool_limit(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
_cleanup_close_ int fd = -EBADF;
uint64_t size = UINT64_MAX;
assert(bus);
assert(reply);
fd = open("/var/lib/portables", O_RDONLY|O_CLOEXEC|O_DIRECTORY);
if (fd >= 0) {
BtrfsQuotaInfo q;
if (btrfs_subvol_get_subtree_quota_fd(fd, 0, &q) >= 0)
size = q.referenced_max;
}
return sd_bus_message_append(reply, "t", size);
}
static int property_get_profiles(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
_cleanup_strv_free_ char **l = NULL;
int r;
assert(bus);
assert(reply);
r = portable_get_profiles(&l);
if (r < 0)
return r;
return sd_bus_message_append_strv(reply, l);
}
static int method_get_image(sd_bus_message *message, void *userdata, sd_bus_error *error) {
_cleanup_free_ char *p = NULL;
Manager *m = ASSERT_PTR(userdata);
const char *name;
Image *image;
int r;
assert(message);
r = sd_bus_message_read(message, "s", &name);
if (r < 0)
return r;
r = bus_image_acquire(m, message, name, NULL, BUS_IMAGE_REFUSE_BY_PATH, NULL, &image, error);
if (r < 0)
return r;
r = bus_image_path(image, &p);
if (r < 0)
return r;
return sd_bus_reply_method_return(message, "o", p);
}
static int method_list_images(sd_bus_message *message, void *userdata, sd_bus_error *error) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
_cleanup_hashmap_free_ Hashmap *images = NULL;
Manager *m = ASSERT_PTR(userdata);
Image *image;
int r;
assert(message);
images = hashmap_new(&image_hash_ops);
if (!images)
return -ENOMEM;
r = manager_image_cache_discover(m, images, error);
if (r < 0)
return r;
r = sd_bus_message_new_method_return(message, &reply);
if (r < 0)
return r;
r = sd_bus_message_open_container(reply, 'a', "(ssbtttso)");
if (r < 0)
return r;
HASHMAP_FOREACH(image, images) {
_cleanup_(sd_bus_error_free) sd_bus_error error_state = SD_BUS_ERROR_NULL;
PortableState state = _PORTABLE_STATE_INVALID;
_cleanup_free_ char *p = NULL;
r = bus_image_path(image, &p);
if (r < 0)
return r;
r = portable_get_state(
sd_bus_message_get_bus(message),
image->path,
NULL,
0,
&state,
&error_state);
if (r < 0)
log_debug_errno(r, "Failed to get state of image '%s', ignoring: %s",
image->path, bus_error_message(&error_state, r));
r = sd_bus_message_append(reply, "(ssbtttso)",
image->name,
image_type_to_string(image->type),
image->read_only,
image->crtime,
image->mtime,
image->usage,
portable_state_to_string(state),
p);
if (r < 0)
return r;
}
r = sd_bus_message_close_container(reply);
if (r < 0)
return r;
return sd_bus_send(NULL, reply, NULL);
}
static int redirect_method_to_image(
Manager *m,
sd_bus_message *message,
sd_bus_error *error,
int (*method)(Manager *m, sd_bus_message *message, const char *name_or_path, Image *image, sd_bus_error* error)) {
const char *name_or_path;
int r;
assert(m);
assert(message);
assert(method);
r = sd_bus_message_read(message, "s", &name_or_path);
if (r < 0)
return r;
return method(m, message, name_or_path, NULL, error);
}
static int method_get_image_os_release(sd_bus_message *message, void *userdata, sd_bus_error *error) {
return redirect_method_to_image(userdata, message, error, bus_image_common_get_os_release);
}
static int method_get_image_metadata(sd_bus_message *message, void *userdata, sd_bus_error *error) {
return redirect_method_to_image(userdata, message, error, bus_image_common_get_metadata);
}
static int method_get_image_state(sd_bus_message *message, void *userdata, sd_bus_error *error) {
_cleanup_strv_free_ char **extension_images = NULL;
const char *name_or_path;
PortableState state;
int r;
assert(message);
r = sd_bus_message_read(message, "s", &name_or_path);
if (r < 0)
return r;
if (sd_bus_message_is_method_call(message, NULL, "GetImageStateWithExtensions")) {
uint64_t input_flags = 0;
r = sd_bus_message_read_strv(message, &extension_images);
if (r < 0)
return r;
r = sd_bus_message_read(message, "t", &input_flags);
if (r < 0)
return r;
/* No flags are supported by this method for now. */
if (input_flags != 0)
return sd_bus_reply_method_errorf(message, SD_BUS_ERROR_INVALID_ARGS,
"Invalid 'flags' parameter '%" PRIu64 "'",
input_flags);
}
r = portable_get_state(
sd_bus_message_get_bus(message),
name_or_path,
extension_images,
0,
&state,
error);
if (r < 0)
return r;
return sd_bus_reply_method_return(message, "s", portable_state_to_string(state));
}
static int method_attach_image(sd_bus_message *message, void *userdata, sd_bus_error *error) {
return redirect_method_to_image(userdata, message, error, bus_image_common_attach);
}
static int method_detach_image(sd_bus_message *message, void *userdata, sd_bus_error *error) {
_cleanup_strv_free_ char **extension_images = NULL;
PortableChange *changes = NULL;
PortableFlags flags = 0;
Manager *m = ASSERT_PTR(userdata);
size_t n_changes = 0;
const char *name_or_path;
int r;
assert(message);
CLEANUP_ARRAY(changes, n_changes, portable_changes_free);
/* Note that we do not redirect detaching to the image object here, because we want to allow that users can
* detach already deleted images too, in case the user already deleted an image before properly detaching
* it. */
r = sd_bus_message_read(message, "s", &name_or_path);
if (r < 0)
return r;
if (sd_bus_message_is_method_call(message, NULL, "DetachImageWithExtensions")) {
uint64_t input_flags = 0;
r = sd_bus_message_read_strv(message, &extension_images);
if (r < 0)
return r;
r = sd_bus_message_read(message, "t", &input_flags);
if (r < 0)
return r;
if ((input_flags & ~_PORTABLE_MASK_PUBLIC) != 0)
return sd_bus_reply_method_errorf(message, SD_BUS_ERROR_INVALID_ARGS,
"Invalid 'flags' parameter '%" PRIu64 "'",
input_flags);
flags |= input_flags;
} else {
int runtime;
r = sd_bus_message_read(message, "b", &runtime);
if (r < 0)
return r;
if (runtime)
flags |= PORTABLE_RUNTIME;
}
r = bus_verify_polkit_async(
message,
CAP_SYS_ADMIN,
"org.freedesktop.portable1.attach-images",
NULL,
false,
UID_INVALID,
&m->polkit_registry,
error);
if (r < 0)
return r;
if (r == 0)
return 1; /* Will call us back */
r = portable_detach(
sd_bus_message_get_bus(message),
name_or_path,
extension_images,
flags,
&changes,
&n_changes,
error);
if (r < 0)
return r;
return reply_portable_changes(message, changes, n_changes);
}
static int method_reattach_image(sd_bus_message *message, void *userdata, sd_bus_error *error) {
return redirect_method_to_image(userdata, message, error, bus_image_common_reattach);
}
static int method_remove_image(sd_bus_message *message, void *userdata, sd_bus_error *error) {
return redirect_method_to_image(userdata, message, error, bus_image_common_remove);
}
static int method_mark_image_read_only(sd_bus_message *message, void *userdata, sd_bus_error *error) {
return redirect_method_to_image(userdata, message, error, bus_image_common_mark_read_only);
}
static int method_set_image_limit(sd_bus_message *message, void *userdata, sd_bus_error *error) {
return redirect_method_to_image(userdata, message, error, bus_image_common_set_limit);
}
static int method_set_pool_limit(sd_bus_message *message, void *userdata, sd_bus_error *error) {
Manager *m = userdata;
uint64_t limit;
int r;
assert(message);
r = sd_bus_message_read(message, "t", &limit);
if (r < 0)
return r;
if (!FILE_SIZE_VALID_OR_INFINITY(limit))
return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "New limit out of range");
r = bus_verify_polkit_async(
message,
CAP_SYS_ADMIN,
"org.freedesktop.portable1.manage-images",
NULL,
false,
UID_INVALID,
&m->polkit_registry,
error);
if (r < 0)
return r;
if (r == 0)
return 1; /* Will call us back */
(void) btrfs_qgroup_set_limit("/var/lib/portables", 0, limit);
r = btrfs_subvol_set_subtree_quota_limit("/var/lib/portables", 0, limit);
if (r == -ENOTTY)
return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Quota is only supported on btrfs.");
if (r < 0)
return sd_bus_error_set_errnof(error, r, "Failed to adjust quota limit: %m");
return sd_bus_reply_method_return(message, NULL);
}
const sd_bus_vtable manager_vtable[] = {
SD_BUS_VTABLE_START(0),
SD_BUS_PROPERTY("PoolPath", "s", property_get_pool_path, 0, 0),
SD_BUS_PROPERTY("PoolUsage", "t", property_get_pool_usage, 0, 0),
SD_BUS_PROPERTY("PoolLimit", "t", property_get_pool_limit, 0, 0),
SD_BUS_PROPERTY("Profiles", "as", property_get_profiles, 0, 0),
SD_BUS_METHOD_WITH_ARGS("GetImage",
SD_BUS_ARGS("s", image),
SD_BUS_RESULT("o", object),
method_get_image,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("ListImages",
SD_BUS_NO_ARGS,
SD_BUS_RESULT("a(ssbtttso)", images),
method_list_images,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("GetImageOSRelease",
SD_BUS_ARGS("s", image),
SD_BUS_RESULT("a{ss}", os_release),
method_get_image_os_release,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("GetImageMetadata",
SD_BUS_ARGS("s", image,
"as", matches),
SD_BUS_RESULT("s", image,
"ay", os_release,
"a{say}", units),
method_get_image_metadata,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("GetImageMetadataWithExtensions",
SD_BUS_ARGS("s", image,
"as", extensions,
"as", matches,
"t", flags),
SD_BUS_RESULT("s", image,
"ay", os_release,
"a{say}", extensions,
"a{say}", units),
method_get_image_metadata,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("GetImageState",
SD_BUS_ARGS("s", image),
SD_BUS_RESULT("s", state),
method_get_image_state,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("GetImageStateWithExtensions",
SD_BUS_ARGS("s", image,
"as", extensions,
"t", flags),
SD_BUS_RESULT("s", state),
method_get_image_state,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("AttachImage",
SD_BUS_ARGS("s", image,
"as", matches,
"s", profile,
"b", runtime,
"s", copy_mode),
SD_BUS_RESULT("a(sss)", changes),
method_attach_image,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("AttachImageWithExtensions",
SD_BUS_ARGS("s", image,
"as", extensions,
"as", matches,
"s", profile,
"s", copy_mode,
"t", flags),
SD_BUS_RESULT("a(sss)", changes),
method_attach_image,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("DetachImage",
SD_BUS_ARGS("s", image,
"b", runtime),
SD_BUS_RESULT("a(sss)", changes),
method_detach_image,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("DetachImageWithExtensions",
SD_BUS_ARGS("s", image,
"as", extensions,
"t", flags),
SD_BUS_RESULT("a(sss)", changes),
method_detach_image,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("ReattachImage",
SD_BUS_ARGS("s", image,
"as", matches,
"s", profile,
"b", runtime,
"s", copy_mode),
SD_BUS_RESULT("a(sss)", changes_removed,
"a(sss)", changes_updated),
method_reattach_image,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("ReattachImageWithExtensions",
SD_BUS_ARGS("s", image,
"as", extensions,
"as", matches,
"s", profile,
"s", copy_mode,
"t", flags),
SD_BUS_RESULT("a(sss)", changes_removed,
"a(sss)", changes_updated),
method_reattach_image,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("RemoveImage",
SD_BUS_ARGS("s", image),
SD_BUS_NO_RESULT,
method_remove_image,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("MarkImageReadOnly",
SD_BUS_ARGS("s", image,
"b", read_only),
SD_BUS_NO_RESULT,
method_mark_image_read_only,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("SetImageLimit",
SD_BUS_ARGS("s", image,
"t", limit),
SD_BUS_NO_RESULT,
method_set_image_limit,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD_WITH_ARGS("SetPoolLimit",
SD_BUS_ARGS("t", limit),
SD_BUS_NO_RESULT,
method_set_pool_limit,
SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_VTABLE_END
};
const BusObjectImplementation manager_object = {
"/org/freedesktop/portable1",
"org.freedesktop.portable1.Manager",
.vtables = BUS_VTABLES(manager_vtable),
.children = BUS_IMPLEMENTATIONS(&image_object),
};
static int reply_portable_compose_message(sd_bus_message *reply, const PortableChange *changes, size_t n_changes) {
size_t i;
int r;
assert(reply);
assert(changes || n_changes == 0);
r = sd_bus_message_open_container(reply, 'a', "(sss)");
if (r < 0)
return r;
for (i = 0; i < n_changes; i++) {
if (changes[i].type_or_errno < 0)
continue;
r = sd_bus_message_append(reply, "(sss)",
portable_change_type_to_string(changes[i].type_or_errno),
changes[i].path,
changes[i].source);
if (r < 0)
return r;
}
r = sd_bus_message_close_container(reply);
if (r < 0)
return r;
return 0;
}
int reply_portable_changes(sd_bus_message *m, const PortableChange *changes, size_t n_changes) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
int r;
assert(m);
r = sd_bus_message_new_method_return(m, &reply);
if (r < 0)
return r;
r = reply_portable_compose_message(reply, changes, n_changes);
if (r < 0)
return r;
return sd_bus_send(NULL, reply, NULL);
}
int reply_portable_changes_pair(
sd_bus_message *m,
const PortableChange *changes_first,
size_t n_changes_first,
const PortableChange *changes_second,
size_t n_changes_second) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
int r;
assert(m);
r = sd_bus_message_new_method_return(m, &reply);
if (r < 0)
return r;
r = reply_portable_compose_message(reply, changes_first, n_changes_first);
if (r < 0)
return r;
r = reply_portable_compose_message(reply, changes_second, n_changes_second);
if (r < 0)
return r;
return sd_bus_send(NULL, reply, NULL);
}
| 23,380 | 37.141925 | 130 |
c
|
null |
systemd-main/src/portable/portabled-image.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "portable.h"
#include "portabled-image.h"
#include "portabled.h"
Image *manager_image_cache_get(Manager *m, const char *name_or_path) {
assert(m);
return hashmap_get(m->image_cache, name_or_path);
}
static int image_cache_flush(sd_event_source *s, void *userdata) {
Manager *m = ASSERT_PTR(userdata);
assert(s);
hashmap_clear(m->image_cache);
return 0;
}
static int manager_image_cache_initialize(Manager *m) {
int r;
assert(m);
r = hashmap_ensure_allocated(&m->image_cache, &image_hash_ops);
if (r < 0)
return r;
/* We flush the cache as soon as we are idle again */
if (!m->image_cache_defer_event) {
r = sd_event_add_defer(m->event, &m->image_cache_defer_event, image_cache_flush, m);
if (r < 0)
return r;
r = sd_event_source_set_priority(m->image_cache_defer_event, SD_EVENT_PRIORITY_IDLE);
if (r < 0)
return r;
}
r = sd_event_source_set_enabled(m->image_cache_defer_event, SD_EVENT_ONESHOT);
if (r < 0)
return r;
return 0;
}
int manager_image_cache_add(Manager *m, Image *image) {
int r;
assert(m);
/* We add the specified image to the cache under two keys.
*
* 1. Always under its path
*
* 2. If the image was discovered in the search path (i.e. its discoverable boolean set) we'll also add it
* under its short name.
*/
r = manager_image_cache_initialize(m);
if (r < 0)
return r;
image->userdata = m;
r = hashmap_put(m->image_cache, image->path, image);
if (r < 0)
return r;
image_ref(image);
if (image->discoverable) {
r = hashmap_put(m->image_cache, image->name, image);
if (r < 0)
return r;
image_ref(image);
}
return 0;
}
int manager_image_cache_discover(Manager *m, Hashmap *images, sd_bus_error *error) {
Image *image;
int r;
assert(m);
/* A wrapper around image_discover() (for finding images in search path) and portable_discover_attached() (for
* finding attached images). */
r = image_discover(IMAGE_PORTABLE, NULL, images);
if (r < 0)
return r;
HASHMAP_FOREACH(image, images)
(void) manager_image_cache_add(m, image);
return 0;
}
| 2,669 | 24.92233 | 118 |
c
|
null |
systemd-main/src/portable/portabled-operation.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "alloc-util.h"
#include "fd-util.h"
#include "portabled-operation.h"
#include "process-util.h"
static int operation_done(sd_event_source *s, const siginfo_t *si, void *userdata) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
Operation *o = ASSERT_PTR(userdata);
int r;
assert(si);
log_debug("Operation " PID_FMT " is now complete with code=%s status=%i",
o->pid,
sigchld_code_to_string(si->si_code), si->si_status);
o->pid = 0;
if (si->si_code != CLD_EXITED) {
r = sd_bus_error_set(&error, SD_BUS_ERROR_FAILED, "Child died abnormally.");
goto fail;
}
if (si->si_status == EXIT_SUCCESS)
r = 0;
else if (read(o->errno_fd, &r, sizeof(r)) != sizeof(r)) { /* Try to acquire error code for failed operation */
r = sd_bus_error_set(&error, SD_BUS_ERROR_FAILED, "Child failed.");
goto fail;
}
if (o->done) {
/* A completion routine is set for this operation, call it. */
r = o->done(o, r, &error);
if (r < 0) {
if (!sd_bus_error_is_set(&error))
sd_bus_error_set_errno(&error, r);
goto fail;
}
} else {
/* The default operation when done is to simply return an error on failure or an empty success
* message on success. */
if (r < 0) {
sd_bus_error_set_errno(&error, r);
goto fail;
}
r = sd_bus_reply_method_return(o->message, NULL);
if (r < 0)
log_error_errno(r, "Failed to reply to message: %m");
}
operation_free(o);
return 0;
fail:
r = sd_bus_reply_method_error(o->message, &error);
if (r < 0)
log_error_errno(r, "Failed to reply to message: %m");
operation_free(o);
return 0;
}
int operation_new(Manager *manager, pid_t child, sd_bus_message *message, int errno_fd, Operation **ret) {
Operation *o;
int r;
assert(manager);
assert(child > 1);
assert(message);
assert(errno_fd >= 0);
o = new0(Operation, 1);
if (!o)
return -ENOMEM;
o->extra_fd = -EBADF;
r = sd_event_add_child(manager->event, &o->event_source, child, WEXITED, operation_done, o);
if (r < 0) {
free(o);
return r;
}
o->pid = child;
o->message = sd_bus_message_ref(message);
o->errno_fd = errno_fd;
LIST_PREPEND(operations, manager->operations, o);
manager->n_operations++;
o->manager = manager;
log_debug("Started new operation " PID_FMT ".", child);
/* At this point we took ownership of both the child and the errno file descriptor! */
if (ret)
*ret = o;
return 0;
}
Operation *operation_free(Operation *o) {
if (!o)
return NULL;
sd_event_source_unref(o->event_source);
safe_close(o->errno_fd);
safe_close(o->extra_fd);
if (o->pid > 1)
(void) sigkill_wait(o->pid);
sd_bus_message_unref(o->message);
if (o->manager) {
LIST_REMOVE(operations, o->manager->operations, o);
o->manager->n_operations--;
}
return mfree(o);
}
| 3,695 | 27.430769 | 118 |
c
|
null |
systemd-main/src/portable/portabled-operation.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
#include "sd-bus.h"
#include "sd-event.h"
#include "list.h"
typedef struct Operation Operation;
#include "portabled.h"
#define OPERATIONS_MAX 64
struct Operation {
Manager *manager;
pid_t pid;
sd_bus_message *message;
int errno_fd;
int extra_fd;
sd_event_source *event_source;
int (*done)(Operation *o, int ret, sd_bus_error *error);
LIST_FIELDS(Operation, operations);
};
int operation_new(Manager *manager, pid_t child, sd_bus_message *message, int errno_fd, Operation **ret);
Operation *operation_free(Operation *o);
| 677 | 21.6 | 105 |
h
|
null |
systemd-main/src/portable/portabled.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/stat.h>
#include <sys/types.h>
#include "sd-bus.h"
#include "alloc-util.h"
#include "bus-log-control-api.h"
#include "bus-polkit.h"
#include "common-signal.h"
#include "constants.h"
#include "daemon-util.h"
#include "main-func.h"
#include "portabled-bus.h"
#include "portabled-image-bus.h"
#include "portabled.h"
#include "process-util.h"
#include "service-util.h"
#include "signal-util.h"
static Manager* manager_unref(Manager *m);
DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_unref);
static int manager_new(Manager **ret) {
_cleanup_(manager_unrefp) Manager *m = NULL;
int r;
assert(ret);
m = new0(Manager, 1);
if (!m)
return -ENOMEM;
r = sd_event_default(&m->event);
if (r < 0)
return r;
r = sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
if (r < 0)
return r;
r = sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
if (r < 0)
return r;
r = sd_event_add_signal(m->event, NULL, SIGRTMIN+18, sigrtmin18_handler, NULL);
if (r < 0)
return r;
r = sd_event_add_memory_pressure(m->event, NULL, NULL, NULL);
if (r < 0)
log_debug_errno(r, "Failed allocate memory pressure event source, ignoring: %m");
(void) sd_event_set_watchdog(m->event, true);
*ret = TAKE_PTR(m);
return 0;
}
static Manager* manager_unref(Manager *m) {
assert(m);
hashmap_free(m->image_cache);
sd_event_source_unref(m->image_cache_defer_event);
bus_verify_polkit_async_registry_free(m->polkit_registry);
sd_bus_flush_close_unref(m->bus);
sd_event_unref(m->event);
return mfree(m);
}
static int manager_connect_bus(Manager *m) {
int r;
assert(m);
assert(!m->bus);
r = sd_bus_default_system(&m->bus);
if (r < 0)
return log_error_errno(r, "Failed to connect to system bus: %m");
r = bus_add_implementation(m->bus, &manager_object, m);
if (r < 0)
return r;
r = bus_log_control_api_register(m->bus);
if (r < 0)
return r;
r = sd_bus_request_name_async(m->bus, NULL, "org.freedesktop.portable1", 0, NULL, NULL);
if (r < 0)
return log_error_errno(r, "Failed to request name: %m");
r = sd_bus_attach_event(m->bus, m->event, 0);
if (r < 0)
return log_error_errno(r, "Failed to attach bus to event loop: %m");
(void) sd_bus_set_exit_on_disconnect(m->bus, true);
return 0;
}
static int manager_startup(Manager *m) {
int r;
assert(m);
r = manager_connect_bus(m);
if (r < 0)
return r;
return 0;
}
static bool check_idle(void *userdata) {
Manager *m = userdata;
return !m->operations;
}
static int manager_run(Manager *m) {
assert(m);
return bus_event_loop_with_idle(
m->event,
m->bus,
"org.freedesktop.portable1",
DEFAULT_EXIT_USEC,
check_idle, m);
}
static int run(int argc, char *argv[]) {
_cleanup_(manager_unrefp) Manager *m = NULL;
int r;
log_setup();
r = service_parse_argv("systemd-portabled.service",
"Manage registrations of portable images.",
BUS_IMPLEMENTATIONS(&manager_object,
&log_control_object),
argc, argv);
if (r <= 0)
return r;
umask(0022);
if (argc != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes no arguments.");
assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, SIGTERM, SIGINT, SIGRTMIN+18, -1) >= 0);
r = manager_new(&m);
if (r < 0)
return log_error_errno(r, "Failed to allocate manager object: %m");
r = manager_startup(m);
if (r < 0)
return log_error_errno(r, "Failed to fully start up daemon: %m");
log_debug("systemd-portabled running as pid " PID_FMT, getpid_cached());
r = sd_notify(false, NOTIFY_READY);
if (r < 0)
log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
r = manager_run(m);
(void) sd_notify(false, NOTIFY_STOPPING);
log_debug("systemd-portabled stopped as pid " PID_FMT, getpid_cached());
return r;
}
DEFINE_MAIN_FUNCTION(run);
| 4,786 | 25.893258 | 101 |
c
|
null |
systemd-main/src/rc-local-generator/rc-local-generator.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include "generator.h"
#include "initrd-util.h"
#include "log.h"
#include "mkdir-label.h"
#include "string-util.h"
static const char *arg_dest = NULL;
/* So you are reading this, and might wonder: why is this implemented as a generator rather than as a plain, statically
* enabled service that carries appropriate ConditionFileIsExecutable= lines? The answer is this: conditions bypass
* execution of a service's binary, but they have no influence on unit dependencies. Thus, a service that is
* conditioned out will still act as synchronization point in the dependency tree, and we'd rather not have that for
* these two legacy scripts. */
static int add_symlink(const char *service, const char *where) {
const char *from, *to;
assert(service);
assert(where);
from = strjoina(SYSTEM_DATA_UNIT_DIR "/", service);
to = strjoina(arg_dest, "/", where, ".wants/", service);
(void) mkdir_parents_label(to, 0755);
if (symlink(from, to) < 0) {
if (errno == EEXIST)
return 0;
return log_error_errno(errno, "Failed to create symlink %s: %m", to);
}
return 1;
}
static int check_executable(const char *path) {
assert(path);
if (access(path, X_OK) < 0) {
if (errno == ENOENT)
return log_debug_errno(errno, "%s does not exist, skipping.", path);
if (errno == EACCES)
return log_info_errno(errno, "%s is not marked executable, skipping.", path);
return log_warning_errno(errno, "Couldn't determine if %s exists and is executable, skipping: %m", path);
}
return 0;
}
static int run(const char *dest, const char *dest_early, const char *dest_late) {
int r = 0, k = 0;
assert_se(arg_dest = dest);
if (in_initrd()) {
log_debug("Skipping generator, running in the initrd.");
return EXIT_SUCCESS;
}
if (check_executable(RC_LOCAL_PATH) >= 0) {
log_debug("Automatically adding rc-local.service.");
r = add_symlink("rc-local.service", "multi-user.target");
}
return r < 0 ? r : k;
}
DEFINE_MAIN_GENERATOR_FUNCTION(run);
| 2,407 | 30.272727 | 121 |
c
|
null |
systemd-main/src/remount-fs/remount-fs.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <mntent.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "env-util.h"
#include "exit-status.h"
#include "fstab-util.h"
#include "log.h"
#include "main-func.h"
#include "mount-setup.h"
#include "mount-util.h"
#include "path-util.h"
#include "process-util.h"
#include "signal-util.h"
#include "strv.h"
/* Goes through /etc/fstab and remounts all API file systems, applying options that are in /etc/fstab that systemd
* might not have respected */
static int track_pid(Hashmap **h, const char *path, pid_t pid) {
_cleanup_free_ char *c = NULL;
int r;
assert(h);
assert(path);
assert(pid_is_valid(pid));
c = strdup(path);
if (!c)
return log_oom();
r = hashmap_ensure_put(h, NULL, PID_TO_PTR(pid), c);
if (r == -ENOMEM)
return log_oom();
if (r < 0)
return log_error_errno(r, "Failed to store pid " PID_FMT, pid);
TAKE_PTR(c);
return 0;
}
static int do_remount(const char *path, bool force_rw, Hashmap **pids) {
pid_t pid;
int r;
log_debug("Remounting %s...", path);
r = safe_fork(force_rw ? "(remount-rw)" : "(remount)",
FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
if (r < 0)
return r;
if (r == 0) {
/* Child */
execv(MOUNT_PATH,
STRV_MAKE(MOUNT_PATH,
path,
"-o",
force_rw ? "remount,rw" : "remount"));
log_error_errno(errno, "Failed to execute " MOUNT_PATH ": %m");
_exit(EXIT_FAILURE);
}
/* Parent */
return track_pid(pids, path, pid);
}
static int run(int argc, char *argv[]) {
_cleanup_hashmap_free_free_ Hashmap *pids = NULL;
_cleanup_endmntent_ FILE *f = NULL;
bool has_root = false;
struct mntent* me;
int r;
log_setup();
if (argc > 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"This program takes no arguments.");
umask(0022);
f = setmntent(fstab_path(), "re");
if (!f) {
if (errno != ENOENT)
return log_error_errno(errno, "Failed to open %s: %m", fstab_path());
} else
while ((me = getmntent(f))) {
/* Remount the root fs, /usr, and all API VFSs */
if (!mount_point_is_api(me->mnt_dir) &&
!PATH_IN_SET(me->mnt_dir, "/", "/usr"))
continue;
if (path_equal(me->mnt_dir, "/"))
has_root = true;
r = do_remount(me->mnt_dir, false, &pids);
if (r < 0)
return r;
}
if (!has_root) {
/* The $SYSTEMD_REMOUNT_ROOT_RW environment variable is set by systemd-gpt-auto-generator to tell us
* whether to remount things. We honour it only if there's no explicit line in /etc/fstab configured
* which takes precedence. */
r = getenv_bool("SYSTEMD_REMOUNT_ROOT_RW");
if (r < 0 && r != -ENXIO)
log_warning_errno(r, "Failed to parse $SYSTEMD_REMOUNT_ROOT_RW, ignoring: %m");
if (r > 0) {
r = do_remount("/", true, &pids);
if (r < 0)
return r;
}
}
r = 0;
while (!hashmap_isempty(pids)) {
_cleanup_free_ char *s = NULL;
siginfo_t si = {};
if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
if (errno == EINTR)
continue;
return log_error_errno(errno, "waitid() failed: %m");
}
s = hashmap_remove(pids, PID_TO_PTR(si.si_pid));
if (s &&
!is_clean_exit(si.si_code, si.si_status, EXIT_CLEAN_COMMAND, NULL)) {
if (si.si_code == CLD_EXITED)
log_error(MOUNT_PATH " for %s exited with exit status %i.", s, si.si_status);
else
log_error(MOUNT_PATH " for %s terminated by signal %s.", s, signal_to_string(si.si_status));
r = -ENOEXEC;
}
}
return r;
}
DEFINE_MAIN_FUNCTION(run);
| 4,840 | 31.273333 | 124 |
c
|
null |
systemd-main/src/reply-password/reply-password.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stddef.h>
#include <sys/un.h>
#include "alloc-util.h"
#include "main-func.h"
#include "fd-util.h"
#include "fileio.h"
#include "log.h"
#include "macro.h"
#include "memory-util.h"
#include "socket-util.h"
#include "string-util.h"
static int send_on_socket(int fd, const char *socket_name, const void *packet, size_t size) {
union sockaddr_union sa = {};
int salen;
assert(fd >= 0);
assert(socket_name);
assert(packet);
salen = sockaddr_un_set_path(&sa.un, socket_name);
if (salen < 0)
return log_error_errno(salen, "Specified socket path for AF_UNIX socket invalid, refusing: %s", socket_name);
if (sendto(fd, packet, size, MSG_NOSIGNAL, &sa.sa, salen) < 0)
return log_error_errno(errno, "Failed to send: %m");
return 0;
}
static int run(int argc, char *argv[]) {
_cleanup_(erase_and_freep) char *packet = NULL;
_cleanup_close_ int fd = -EBADF;
size_t length = 0;
int r;
log_setup();
if (argc != 3)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Wrong number of arguments.");
if (streq(argv[1], "1")) {
_cleanup_(erase_and_freep) char *line = NULL;
r = read_line(stdin, LONG_LINE_MAX, &line);
if (r < 0)
return log_error_errno(r, "Failed to read password: %m");
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EIO),
"Got EOF while reading password.");
packet = strjoin("+", line);
if (!packet)
return log_oom();
length = 1 + strlen(line) + 1;
} else if (streq(argv[1], "0")) {
packet = strdup("-");
if (!packet)
return log_oom();
length = 1;
} else
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Invalid first argument %s", argv[1]);
fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
if (fd < 0)
return log_error_errno(errno, "socket() failed: %m");
return send_on_socket(fd, argv[2], packet, length);
}
DEFINE_MAIN_FUNCTION(run);
| 2,439 | 29.123457 | 125 |
c
|
null |
systemd-main/src/resolve/dns-type.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/socket.h>
#include <errno.h>
#include "dns-type.h"
#include "parse-util.h"
#include "string-util.h"
typedef const struct {
uint16_t type;
const char *name;
} dns_type;
static const struct dns_type_name *
lookup_dns_type (register const char *str, register GPERF_LEN_TYPE len);
#include "dns_type-from-name.h"
#include "dns_type-to-name.h"
int dns_type_from_string(const char *s) {
const struct dns_type_name *sc;
assert(s);
sc = lookup_dns_type(s, strlen(s));
if (sc)
return sc->id;
s = startswith_no_case(s, "TYPE");
if (s) {
unsigned x;
if (safe_atou(s, &x) >= 0 &&
x <= UINT16_MAX)
return (int) x;
}
return _DNS_TYPE_INVALID;
}
bool dns_type_is_pseudo(uint16_t type) {
/* Checks whether the specified type is a "pseudo-type". What
* a "pseudo-type" precisely is, is defined only very weakly,
* but apparently entails all RR types that are not actually
* stored as RRs on the server and should hence also not be
* cached. We use this list primarily to validate NSEC type
* bitfields, and to verify what to cache. */
return IN_SET(type,
0, /* A Pseudo RR type, according to RFC 2931 */
DNS_TYPE_ANY,
DNS_TYPE_AXFR,
DNS_TYPE_IXFR,
DNS_TYPE_OPT,
DNS_TYPE_TSIG,
DNS_TYPE_TKEY
);
}
bool dns_class_is_pseudo(uint16_t class) {
return class == DNS_CLASS_ANY;
}
bool dns_type_is_valid_query(uint16_t type) {
/* The types valid as questions in packets */
return !IN_SET(type,
0,
DNS_TYPE_OPT,
DNS_TYPE_TSIG,
DNS_TYPE_TKEY,
/* RRSIG are technically valid as questions, but we refuse doing explicit queries for them, as
* they aren't really payload, but signatures for payload, and cannot be validated on their
* own. After all they are the signatures, and have no signatures of their own validating
* them. */
DNS_TYPE_RRSIG);
}
bool dns_type_is_zone_transer(uint16_t type) {
/* Zone transfers, either normal or incremental */
return IN_SET(type,
DNS_TYPE_AXFR,
DNS_TYPE_IXFR);
}
bool dns_type_is_valid_rr(uint16_t type) {
/* The types valid as RR in packets (but not necessarily
* stored on servers). */
return !IN_SET(type,
DNS_TYPE_ANY,
DNS_TYPE_AXFR,
DNS_TYPE_IXFR);
}
bool dns_class_is_valid_rr(uint16_t class) {
return class != DNS_CLASS_ANY;
}
bool dns_type_may_redirect(uint16_t type) {
/* The following record types should never be redirected using
* CNAME/DNAME RRs. See
* <https://tools.ietf.org/html/rfc4035#section-2.5>. */
if (dns_type_is_pseudo(type))
return false;
return !IN_SET(type,
DNS_TYPE_CNAME,
DNS_TYPE_DNAME,
DNS_TYPE_NSEC3,
DNS_TYPE_NSEC,
DNS_TYPE_RRSIG,
DNS_TYPE_NXT,
DNS_TYPE_SIG,
DNS_TYPE_KEY);
}
bool dns_type_may_wildcard(uint16_t type) {
/* The following records may not be expanded from wildcard RRsets */
if (dns_type_is_pseudo(type))
return false;
return !IN_SET(type,
DNS_TYPE_NSEC3,
DNS_TYPE_SOA,
/* Prohibited by https://tools.ietf.org/html/rfc4592#section-4.4 */
DNS_TYPE_DNAME);
}
bool dns_type_apex_only(uint16_t type) {
/* Returns true for all RR types that may only appear signed in a zone apex */
return IN_SET(type,
DNS_TYPE_SOA,
DNS_TYPE_NS, /* this one can appear elsewhere, too, but not signed */
DNS_TYPE_DNSKEY,
DNS_TYPE_NSEC3PARAM);
}
bool dns_type_is_dnssec(uint16_t type) {
return IN_SET(type,
DNS_TYPE_DS,
DNS_TYPE_DNSKEY,
DNS_TYPE_RRSIG,
DNS_TYPE_NSEC,
DNS_TYPE_NSEC3,
DNS_TYPE_NSEC3PARAM);
}
bool dns_type_is_obsolete(uint16_t type) {
return IN_SET(type,
/* Obsoleted by RFC 973 */
DNS_TYPE_MD,
DNS_TYPE_MF,
DNS_TYPE_MAILA,
/* Kinda obsoleted by RFC 2505 */
DNS_TYPE_MB,
DNS_TYPE_MG,
DNS_TYPE_MR,
DNS_TYPE_MINFO,
DNS_TYPE_MAILB,
/* RFC1127 kinda obsoleted this by recommending against its use */
DNS_TYPE_WKS,
/* Declared historical by RFC 6563 */
DNS_TYPE_A6,
/* Obsoleted by DNSSEC-bis */
DNS_TYPE_NXT,
/* RFC 1035 removed support for concepts that needed this from RFC 883 */
DNS_TYPE_NULL);
}
bool dns_type_needs_authentication(uint16_t type) {
/* Returns true for all (non-obsolete) RR types where records are not useful if they aren't
* authenticated. I.e. everything that contains crypto keys. */
return IN_SET(type,
DNS_TYPE_CERT,
DNS_TYPE_SSHFP,
DNS_TYPE_IPSECKEY,
DNS_TYPE_DS,
DNS_TYPE_DNSKEY,
DNS_TYPE_TLSA,
DNS_TYPE_CDNSKEY,
DNS_TYPE_OPENPGPKEY,
DNS_TYPE_CAA);
}
int dns_type_to_af(uint16_t t) {
switch (t) {
case DNS_TYPE_A:
return AF_INET;
case DNS_TYPE_AAAA:
return AF_INET6;
case DNS_TYPE_ANY:
return AF_UNSPEC;
default:
return -EINVAL;
}
}
const char *dns_class_to_string(uint16_t class) {
switch (class) {
case DNS_CLASS_IN:
return "IN";
case DNS_CLASS_ANY:
return "ANY";
}
return NULL;
}
int dns_class_from_string(const char *s) {
if (!s)
return _DNS_CLASS_INVALID;
if (strcaseeq(s, "IN"))
return DNS_CLASS_IN;
else if (strcaseeq(s, "ANY"))
return DNS_CLASS_ANY;
return _DNS_CLASS_INVALID;
}
const char* tlsa_cert_usage_to_string(uint8_t cert_usage) {
switch (cert_usage) {
case 0:
return "CA constraint";
case 1:
return "Service certificate constraint";
case 2:
return "Trust anchor assertion";
case 3:
return "Domain-issued certificate";
case 4 ... 254:
return "Unassigned";
case 255:
return "Private use";
}
return NULL; /* clang cannot count that we covered everything */
}
const char* tlsa_selector_to_string(uint8_t selector) {
switch (selector) {
case 0:
return "Full Certificate";
case 1:
return "SubjectPublicKeyInfo";
case 2 ... 254:
return "Unassigned";
case 255:
return "Private use";
}
return NULL;
}
const char* tlsa_matching_type_to_string(uint8_t selector) {
switch (selector) {
case 0:
return "No hash used";
case 1:
return "SHA-256";
case 2:
return "SHA-512";
case 3 ... 254:
return "Unassigned";
case 255:
return "Private use";
}
return NULL;
}
| 8,421 | 25.567823 | 117 |
c
|
null |
systemd-main/src/resolve/dns-type.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "macro.h"
/* DNS record types, taken from
* http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml.
*/
enum {
/* Normal records */
DNS_TYPE_A = 0x01,
DNS_TYPE_NS,
DNS_TYPE_MD,
DNS_TYPE_MF,
DNS_TYPE_CNAME,
DNS_TYPE_SOA,
DNS_TYPE_MB,
DNS_TYPE_MG,
DNS_TYPE_MR,
DNS_TYPE_NULL,
DNS_TYPE_WKS,
DNS_TYPE_PTR,
DNS_TYPE_HINFO,
DNS_TYPE_MINFO,
DNS_TYPE_MX,
DNS_TYPE_TXT,
DNS_TYPE_RP,
DNS_TYPE_AFSDB,
DNS_TYPE_X25,
DNS_TYPE_ISDN,
DNS_TYPE_RT,
DNS_TYPE_NSAP,
DNS_TYPE_NSAP_PTR,
DNS_TYPE_SIG,
DNS_TYPE_KEY,
DNS_TYPE_PX,
DNS_TYPE_GPOS,
DNS_TYPE_AAAA,
DNS_TYPE_LOC,
DNS_TYPE_NXT,
DNS_TYPE_EID,
DNS_TYPE_NIMLOC,
DNS_TYPE_SRV,
DNS_TYPE_ATMA,
DNS_TYPE_NAPTR,
DNS_TYPE_KX,
DNS_TYPE_CERT,
DNS_TYPE_A6,
DNS_TYPE_DNAME,
DNS_TYPE_SINK,
DNS_TYPE_OPT, /* EDNS0 option */
DNS_TYPE_APL,
DNS_TYPE_DS,
DNS_TYPE_SSHFP,
DNS_TYPE_IPSECKEY,
DNS_TYPE_RRSIG,
DNS_TYPE_NSEC,
DNS_TYPE_DNSKEY,
DNS_TYPE_DHCID,
DNS_TYPE_NSEC3,
DNS_TYPE_NSEC3PARAM,
DNS_TYPE_TLSA,
DNS_TYPE_HIP = 0x37,
DNS_TYPE_NINFO,
DNS_TYPE_RKEY,
DNS_TYPE_TALINK,
DNS_TYPE_CDS,
DNS_TYPE_CDNSKEY,
DNS_TYPE_OPENPGPKEY,
DNS_TYPE_SPF = 0x63,
DNS_TYPE_NID,
DNS_TYPE_L32,
DNS_TYPE_L64,
DNS_TYPE_LP,
DNS_TYPE_EUI48,
DNS_TYPE_EUI64,
DNS_TYPE_TKEY = 0xF9,
DNS_TYPE_TSIG,
DNS_TYPE_IXFR,
DNS_TYPE_AXFR,
DNS_TYPE_MAILB,
DNS_TYPE_MAILA,
DNS_TYPE_ANY,
DNS_TYPE_URI,
DNS_TYPE_CAA,
DNS_TYPE_TA = 0x8000,
DNS_TYPE_DLV,
_DNS_TYPE_MAX,
_DNS_TYPE_INVALID = -EINVAL,
};
assert_cc(DNS_TYPE_SSHFP == 44);
assert_cc(DNS_TYPE_TLSA == 52);
assert_cc(DNS_TYPE_ANY == 255);
/* DNS record classes, see RFC 1035 */
enum {
DNS_CLASS_IN = 0x01,
DNS_CLASS_ANY = 0xFF,
_DNS_CLASS_MAX,
_DNS_CLASS_INVALID = -EINVAL,
};
#define _DNS_CLASS_STRING_MAX (sizeof "CLASS" + DECIMAL_STR_MAX(uint16_t))
#define _DNS_TYPE_STRING_MAX (sizeof "CLASS" + DECIMAL_STR_MAX(uint16_t))
bool dns_type_is_pseudo(uint16_t type);
bool dns_type_is_valid_query(uint16_t type);
bool dns_type_is_valid_rr(uint16_t type);
bool dns_type_may_redirect(uint16_t type);
bool dns_type_is_dnssec(uint16_t type);
bool dns_type_is_obsolete(uint16_t type);
bool dns_type_may_wildcard(uint16_t type);
bool dns_type_apex_only(uint16_t type);
bool dns_type_needs_authentication(uint16_t type);
bool dns_type_is_zone_transer(uint16_t type);
int dns_type_to_af(uint16_t type);
bool dns_class_is_pseudo(uint16_t class);
bool dns_class_is_valid_rr(uint16_t class);
/* TYPE?? follows http://tools.ietf.org/html/rfc3597#section-5 */
const char *dns_type_to_string(int type);
int dns_type_from_string(const char *s);
const char *dns_class_to_string(uint16_t class);
int dns_class_from_string(const char *name);
/* https://tools.ietf.org/html/draft-ietf-dane-protocol-23#section-7.2 */
const char *tlsa_cert_usage_to_string(uint8_t cert_usage);
/* https://tools.ietf.org/html/draft-ietf-dane-protocol-23#section-7.3 */
const char *tlsa_selector_to_string(uint8_t selector);
/* https://tools.ietf.org/html/draft-ietf-dane-protocol-23#section-7.4 */
const char *tlsa_matching_type_to_string(uint8_t selector);
/* https://tools.ietf.org/html/rfc6844#section-5.1 */
#define CAA_FLAG_CRITICAL (1u << 7)
| 3,868 | 25.682759 | 74 |
h
|
null |
systemd-main/src/resolve/fuzz-dns-packet.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "fuzz.h"
#include "memory-util.h"
#include "resolved-dns-packet.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
_cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
if (outside_size_range(size, 0, DNS_PACKET_SIZE_MAX))
return 0;
assert_se(dns_packet_new(&p, DNS_PROTOCOL_DNS, 0, DNS_PACKET_SIZE_MAX) >= 0);
p->size = 0; /* by default append starts after the header, undo that */
assert_se(dns_packet_append_blob(p, data, size, NULL) >= 0);
if (size < DNS_PACKET_HEADER_SIZE) {
/* make sure we pad the packet back up to the minimum header size */
assert_se(p->allocated >= DNS_PACKET_HEADER_SIZE);
memzero(DNS_PACKET_DATA(p) + size, DNS_PACKET_HEADER_SIZE - size);
p->size = DNS_PACKET_HEADER_SIZE;
}
(void) dns_packet_extract(p);
return 0;
}
| 972 | 36.423077 | 85 |
c
|
null |
systemd-main/src/resolve/fuzz-resource-record.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "fd-util.h"
#include "fuzz.h"
#include "memory-util.h"
#include "memstream-util.h"
#include "resolved-dns-packet.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
_cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL, *copy = NULL;
_cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
_cleanup_(memstream_done) MemStream m = {};
FILE *f;
if (outside_size_range(size, 0, DNS_PACKET_SIZE_MAX))
return 0;
if (dns_resource_record_new_from_raw(&rr, data, size) < 0)
return 0;
assert_se(copy = dns_resource_record_copy(rr));
assert_se(dns_resource_record_equal(copy, rr) > 0);
assert_se(f = memstream_init(&m));
(void) fprintf(f, "%s", strna(dns_resource_record_to_string(rr)));
if (dns_resource_record_to_json(rr, &v) < 0)
return 0;
(void) json_variant_dump(v, JSON_FORMAT_PRETTY|JSON_FORMAT_COLOR|JSON_FORMAT_SOURCE, f, NULL);
(void) dns_resource_record_to_wire_format(rr, false);
(void) dns_resource_record_to_wire_format(rr, true);
return 0;
}
| 1,207 | 32.555556 | 102 |
c
|
null |
systemd-main/src/resolve/resolvconf-compat.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <getopt.h>
#include <net/if.h>
#include "alloc-util.h"
#include "build.h"
#include "constants.h"
#include "dns-domain.h"
#include "extract-word.h"
#include "fileio.h"
#include "parse-util.h"
#include "pretty-print.h"
#include "resolvconf-compat.h"
#include "resolvectl.h"
#include "resolved-def.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
static int resolvconf_help(void) {
_cleanup_free_ char *link = NULL;
int r;
r = terminal_urlify_man("resolvectl", "1", &link);
if (r < 0)
return log_oom();
printf("%1$s -a INTERFACE < FILE\n"
"%1$s -d INTERFACE\n"
"\n"
"Register DNS server and domain configuration with systemd-resolved.\n\n"
" -h --help Show this help\n"
" --version Show package version\n"
" -a Register per-interface DNS server and domain data\n"
" -d Unregister per-interface DNS server and domain data\n"
" -f Ignore if specified interface does not exist\n"
" -x Send DNS traffic preferably over this interface\n"
"\n"
"This is a compatibility alias for the resolvectl(1) tool, providing native\n"
"command line compatibility with the resolvconf(8) tool of various Linux\n"
"distributions and BSD systems. Some options supported by other implementations\n"
"are not supported and are ignored: -m, -p, -u. Various options supported by other\n"
"implementations are not supported and will cause the invocation to fail:\n"
"-I, -i, -l, -R, -r, -v, -V, --enable-updates, --disable-updates,\n"
"--updates-are-enabled.\n"
"\nSee the %2$s for details.\n",
program_invocation_short_name,
link);
return 0;
}
static int parse_nameserver(const char *string) {
int r;
assert(string);
for (;;) {
_cleanup_free_ char *word = NULL;
r = extract_first_word(&string, &word, NULL, 0);
if (r < 0)
return r;
if (r == 0)
break;
if (strv_push(&arg_set_dns, word) < 0)
return log_oom();
word = NULL;
}
return 0;
}
static int parse_search_domain(const char *string) {
int r;
assert(string);
for (;;) {
_cleanup_free_ char *word = NULL;
r = extract_first_word(&string, &word, NULL, EXTRACT_UNQUOTE);
if (r < 0)
return r;
if (r == 0)
break;
if (strv_push(&arg_set_domain, word) < 0)
return log_oom();
word = NULL;
}
return 0;
}
int resolvconf_parse_argv(int argc, char *argv[]) {
enum {
ARG_VERSION = 0x100,
ARG_ENABLE_UPDATES,
ARG_DISABLE_UPDATES,
ARG_UPDATES_ARE_ENABLED,
};
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, ARG_VERSION },
/* The following are specific to Debian's original resolvconf */
{ "enable-updates", no_argument, NULL, ARG_ENABLE_UPDATES },
{ "disable-updates", no_argument, NULL, ARG_DISABLE_UPDATES },
{ "updates-are-enabled", no_argument, NULL, ARG_UPDATES_ARE_ENABLED },
{}
};
enum {
TYPE_REGULAR,
TYPE_PRIVATE, /* -p: Not supported, treated identically to TYPE_REGULAR */
TYPE_EXCLUSIVE, /* -x */
} type = TYPE_REGULAR;
int c, r;
assert(argc >= 0);
assert(argv);
/* openresolv checks these environment variables */
if (getenv("IF_EXCLUSIVE"))
type = TYPE_EXCLUSIVE;
if (getenv("IF_PRIVATE"))
type = TYPE_PRIVATE; /* not actually supported */
arg_mode = _MODE_INVALID;
while ((c = getopt_long(argc, argv, "hadxpfm:uIi:l:Rr:vV", options, NULL)) >= 0)
switch (c) {
case 'h':
return resolvconf_help();
case ARG_VERSION:
return version();
/* -a and -d is what everybody can agree on */
case 'a':
arg_mode = MODE_SET_LINK;
break;
case 'd':
arg_mode = MODE_REVERT_LINK;
break;
/* The exclusive/private/force stuff is an openresolv invention, we support in some skewed way */
case 'x':
type = TYPE_EXCLUSIVE;
break;
case 'p':
type = TYPE_PRIVATE; /* not actually supported */
break;
case 'f':
arg_ifindex_permissive = true;
break;
/* The metrics stuff is an openresolv invention we ignore (and don't really need) */
case 'm':
log_debug("Switch -%c ignored.", c);
break;
/* -u supposedly should "update all subscribers". We have no subscribers, hence let's make
this a NOP, and exit immediately, cleanly. */
case 'u':
log_info("Switch -%c ignored.", c);
return 0;
/* The following options are openresolv inventions we don't support. */
case 'I':
case 'i':
case 'l':
case 'R':
case 'r':
case 'v':
case 'V':
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Switch -%c not supported.", c);
/* The Debian resolvconf commands we don't support. */
case ARG_ENABLE_UPDATES:
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Switch --enable-updates not supported.");
case ARG_DISABLE_UPDATES:
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Switch --disable-updates not supported.");
case ARG_UPDATES_ARE_ENABLED:
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Switch --updates-are-enabled not supported.");
case '?':
return -EINVAL;
default:
assert_not_reached();
}
if (arg_mode == _MODE_INVALID)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Expected either -a or -d on the command line.");
if (optind+1 != argc)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Expected interface name as argument.");
r = ifname_resolvconf_mangle(argv[optind]);
if (r <= 0)
return r;
optind++;
if (arg_mode == MODE_SET_LINK) {
unsigned n = 0;
for (;;) {
_cleanup_free_ char *line = NULL;
const char *a, *l;
r = read_line(stdin, LONG_LINE_MAX, &line);
if (r < 0)
return log_error_errno(r, "Failed to read from stdin: %m");
if (r == 0)
break;
n++;
l = strstrip(line);
if (IN_SET(*l, '#', ';', 0))
continue;
a = first_word(l, "nameserver");
if (a) {
(void) parse_nameserver(a);
continue;
}
a = first_word(l, "domain");
if (!a)
a = first_word(l, "search");
if (a) {
(void) parse_search_domain(a);
continue;
}
log_syntax(NULL, LOG_DEBUG, "stdin", n, 0, "Ignoring resolv.conf line: %s", l);
}
if (type == TYPE_EXCLUSIVE) {
/* If -x mode is selected, let's preferably route non-suffixed lookups to this interface. This
* somewhat matches the original -x behaviour */
r = strv_extend(&arg_set_domain, "~.");
if (r < 0)
return log_oom();
} else if (type == TYPE_PRIVATE)
log_debug("Private DNS server data not supported, ignoring.");
if (!arg_set_dns)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"No DNS servers specified, refusing operation.");
}
return 1; /* work to do */
}
| 9,804 | 34.143369 | 118 |
c
|
null |
systemd-main/src/resolve/resolvectl.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <in-addr-util.h>
#include <stdbool.h>
#include <sys/types.h>
typedef enum ExecutionMode {
MODE_RESOLVE_HOST,
MODE_RESOLVE_RECORD,
MODE_RESOLVE_SERVICE,
MODE_RESOLVE_OPENPGP,
MODE_RESOLVE_TLSA,
MODE_STATISTICS,
MODE_RESET_STATISTICS,
MODE_FLUSH_CACHES,
MODE_RESET_SERVER_FEATURES,
MODE_STATUS,
MODE_SET_LINK,
MODE_REVERT_LINK,
_MODE_INVALID = -EINVAL,
} ExecutionMode;
extern ExecutionMode arg_mode;
extern char **arg_set_dns;
extern char **arg_set_domain;
extern bool arg_ifindex_permissive;
int ifname_mangle_full(const char *s, bool drop_protocol_specifier);
static inline int ifname_mangle(const char *s) {
return ifname_mangle_full(s, false);
}
static inline int ifname_resolvconf_mangle(const char *s) {
return ifname_mangle_full(s, true);
}
| 942 | 25.194444 | 68 |
h
|
null |
systemd-main/src/resolve/resolved-bus.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "bus-object.h"
#include "resolved-manager.h"
extern const BusObjectImplementation manager_object;
int manager_connect_bus(Manager *m);
int _manager_send_changed(Manager *manager, const char *property, ...) _sentinel_;
#define manager_send_changed(manager, ...) _manager_send_changed(manager, __VA_ARGS__, NULL)
int bus_dns_server_append(sd_bus_message *reply, DnsServer *s, bool with_ifindex, bool extended);
int bus_property_get_resolve_support(sd_bus *bus, const char *path, const char *interface,
const char *property, sd_bus_message *reply,
void *userdata, sd_bus_error *error);
void bus_client_log(sd_bus_message *m, const char *what);
| 790 | 42.944444 | 97 |
h
|
null |
systemd-main/src/resolve/resolved-conf.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "conf-parser.h"
#include "resolved-dns-server.h"
int manager_parse_config_file(Manager *m);
int manager_parse_search_domains_and_warn(Manager *m, const char *string);
int manager_parse_dns_server_string_and_warn(Manager *m, DnsServerType type, const char *string);
const struct ConfigPerfItem* resolved_gperf_lookup(const char *key, GPERF_LEN_TYPE length);
const struct ConfigPerfItem* resolved_dnssd_gperf_lookup(const char *key, GPERF_LEN_TYPE length);
CONFIG_PARSER_PROTOTYPE(config_parse_dns_servers);
CONFIG_PARSER_PROTOTYPE(config_parse_search_domains);
CONFIG_PARSER_PROTOTYPE(config_parse_dns_stub_listener_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_dnssd_service_name);
CONFIG_PARSER_PROTOTYPE(config_parse_dnssd_service_type);
CONFIG_PARSER_PROTOTYPE(config_parse_dnssd_txt);
CONFIG_PARSER_PROTOTYPE(config_parse_dns_stub_listener_extra);
| 927 | 39.347826 | 97 |
h
|
null |
systemd-main/src/resolve/resolved-dns-answer.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdio.h>
#include "alloc-util.h"
#include "dns-domain.h"
#include "random-util.h"
#include "resolved-dns-answer.h"
#include "resolved-dns-dnssec.h"
#include "string-util.h"
static DnsAnswerItem *dns_answer_item_free(DnsAnswerItem *item) {
if (!item)
return NULL;
dns_resource_record_unref(item->rr);
dns_resource_record_unref(item->rrsig);
return mfree(item);
}
DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(DnsAnswerItem, dns_answer_item, dns_answer_item_free);
DEFINE_TRIVIAL_CLEANUP_FUNC(DnsAnswerItem*, dns_answer_item_unref);
static void dns_answer_item_hash_func(const DnsAnswerItem *a, struct siphash *state) {
assert(a);
assert(state);
siphash24_compress(&a->ifindex, sizeof(a->ifindex), state);
dns_resource_record_hash_func(a->rr, state);
}
static int dns_answer_item_compare_func(const DnsAnswerItem *a, const DnsAnswerItem *b) {
int r;
assert(a);
assert(b);
r = CMP(a->ifindex, b->ifindex);
if (r != 0)
return r;
return dns_resource_record_compare_func(a->rr, b->rr);
}
DEFINE_PRIVATE_HASH_OPS_WITH_KEY_DESTRUCTOR(
dns_answer_item_hash_ops,
DnsAnswerItem,
dns_answer_item_hash_func,
dns_answer_item_compare_func,
dns_answer_item_unref);
static int dns_answer_reserve_internal(DnsAnswer *a, size_t n) {
size_t m;
assert(a);
assert(a->items);
m = ordered_set_size(a->items);
assert(m <= UINT16_MAX); /* We can only place 64K RRs in an answer at max */
n = saturate_add(m, n, UINT16_MAX);
/* Higher multipliers give slightly higher efficiency through hash collisions, but the gains
* quickly drop off after 2. */
return ordered_set_reserve(a->items, n * 2);
}
DnsAnswer *dns_answer_new(size_t n) {
_cleanup_ordered_set_free_ OrderedSet *s = NULL;
_cleanup_(dns_answer_unrefp) DnsAnswer *a = NULL;
if (n > UINT16_MAX)
n = UINT16_MAX;
s = ordered_set_new(&dns_answer_item_hash_ops);
if (!s)
return NULL;
a = new(DnsAnswer, 1);
if (!a)
return NULL;
*a = (DnsAnswer) {
.n_ref = 1,
.items = TAKE_PTR(s),
};
if (dns_answer_reserve_internal(a, n) < 0)
return NULL;
return TAKE_PTR(a);
}
static DnsAnswer *dns_answer_free(DnsAnswer *a) {
assert(a);
ordered_set_free(a->items);
return mfree(a);
}
DEFINE_TRIVIAL_REF_UNREF_FUNC(DnsAnswer, dns_answer, dns_answer_free);
static int dns_answer_add_raw(
DnsAnswer *a,
DnsResourceRecord *rr,
int ifindex,
DnsAnswerFlags flags,
DnsResourceRecord *rrsig) {
_cleanup_(dns_answer_item_unrefp) DnsAnswerItem *item = NULL;
int r;
assert(rr);
if (!a)
return -ENOSPC;
if (dns_answer_size(a) >= UINT16_MAX)
return -ENOSPC;
item = new(DnsAnswerItem, 1);
if (!item)
return -ENOMEM;
*item = (DnsAnswerItem) {
.n_ref = 1,
.rr = dns_resource_record_ref(rr),
.ifindex = ifindex,
.flags = flags,
.rrsig = dns_resource_record_ref(rrsig),
};
r = ordered_set_put(a->items, item);
if (r < 0)
return r;
TAKE_PTR(item);
return 1;
}
static int dns_answer_add_raw_all(DnsAnswer *a, DnsAnswer *source) {
DnsAnswerItem *item;
int r;
DNS_ANSWER_FOREACH_ITEM(item, source) {
r = dns_answer_add_raw(
a,
item->rr,
item->ifindex,
item->flags,
item->rrsig);
if (r < 0)
return r;
}
return 0;
}
int dns_answer_add(
DnsAnswer *a,
DnsResourceRecord *rr,
int ifindex,
DnsAnswerFlags flags,
DnsResourceRecord *rrsig) {
DnsAnswerItem tmp, *exist;
assert(rr);
if (!a)
return -ENOSPC;
if (a->n_ref > 1)
return -EBUSY;
tmp = (DnsAnswerItem) {
.rr = rr,
.ifindex = ifindex,
};
exist = ordered_set_get(a->items, &tmp);
if (exist) {
/* There's already an RR of the same RRset in place! Let's see if the TTLs more or less
* match. We don't really care if they match precisely, but we do care whether one is 0 and
* the other is not. See RFC 2181, Section 5.2. */
if ((rr->ttl == 0) != (exist->rr->ttl == 0))
return -EINVAL;
/* Entry already exists, keep the entry with the higher TTL. */
if (rr->ttl > exist->rr->ttl) {
DNS_RR_REPLACE(exist->rr, dns_resource_record_ref(rr));
/* Update RRSIG and RR at the same time */
if (rrsig)
DNS_RR_REPLACE(exist->rrsig, dns_resource_record_ref(rrsig));
}
exist->flags |= flags;
if (rr->key->type == DNS_TYPE_RRSIG) {
/* If the rr is RRSIG, then move the rr to the end. */
assert_se(ordered_set_remove(a->items, exist) == exist);
assert_se(ordered_set_put(a->items, exist) == 1);
}
return 0;
}
return dns_answer_add_raw(a, rr, ifindex, flags, rrsig);
}
static int dns_answer_add_all(DnsAnswer *a, DnsAnswer *b) {
DnsAnswerItem *item;
int r;
DNS_ANSWER_FOREACH_ITEM(item, b) {
r = dns_answer_add(a, item->rr, item->ifindex, item->flags, item->rrsig);
if (r < 0)
return r;
}
return 0;
}
int dns_answer_add_extend(
DnsAnswer **a,
DnsResourceRecord *rr,
int ifindex,
DnsAnswerFlags flags,
DnsResourceRecord *rrsig) {
int r;
assert(a);
assert(rr);
r = dns_answer_reserve_or_clone(a, 1);
if (r < 0)
return r;
return dns_answer_add(*a, rr, ifindex, flags, rrsig);
}
int dns_answer_add_soa(DnsAnswer *a, const char *name, uint32_t ttl, int ifindex) {
_cleanup_(dns_resource_record_unrefp) DnsResourceRecord *soa = NULL;
soa = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_SOA, name);
if (!soa)
return -ENOMEM;
soa->ttl = ttl;
soa->soa.mname = strdup(name);
if (!soa->soa.mname)
return -ENOMEM;
soa->soa.rname = strjoin("root.", name);
if (!soa->soa.rname)
return -ENOMEM;
soa->soa.serial = 1;
soa->soa.refresh = 1;
soa->soa.retry = 1;
soa->soa.expire = 1;
soa->soa.minimum = ttl;
return dns_answer_add(a, soa, ifindex, DNS_ANSWER_AUTHENTICATED, NULL);
}
int dns_answer_match_key(DnsAnswer *a, const DnsResourceKey *key, DnsAnswerFlags *ret_flags) {
DnsAnswerFlags flags = 0, i_flags;
DnsResourceRecord *i;
bool found = false;
int r;
assert(key);
DNS_ANSWER_FOREACH_FLAGS(i, i_flags, a) {
r = dns_resource_key_match_rr(key, i, NULL);
if (r < 0)
return r;
if (r == 0)
continue;
if (!ret_flags)
return 1;
if (found)
flags &= i_flags;
else {
flags = i_flags;
found = true;
}
}
if (ret_flags)
*ret_flags = flags;
return found;
}
bool dns_answer_contains_nsec_or_nsec3(DnsAnswer *a) {
DnsResourceRecord *i;
DNS_ANSWER_FOREACH(i, a)
if (IN_SET(i->key->type, DNS_TYPE_NSEC, DNS_TYPE_NSEC3))
return true;
return false;
}
int dns_answer_contains_zone_nsec3(DnsAnswer *answer, const char *zone) {
DnsResourceRecord *rr;
int r;
/* Checks whether the specified answer contains at least one NSEC3 RR in the specified zone */
DNS_ANSWER_FOREACH(rr, answer) {
const char *p;
if (rr->key->type != DNS_TYPE_NSEC3)
continue;
p = dns_resource_key_name(rr->key);
r = dns_name_parent(&p);
if (r < 0)
return r;
if (r == 0)
continue;
r = dns_name_equal(p, zone);
if (r != 0)
return r;
}
return false;
}
bool dns_answer_contains(DnsAnswer *answer, DnsResourceRecord *rr) {
DnsResourceRecord *i;
DNS_ANSWER_FOREACH(i, answer)
if (dns_resource_record_equal(i, rr))
return true;
return false;
}
int dns_answer_find_soa(
DnsAnswer *a,
const DnsResourceKey *key,
DnsResourceRecord **ret,
DnsAnswerFlags *ret_flags) {
DnsResourceRecord *rr, *soa = NULL;
DnsAnswerFlags rr_flags, soa_flags = 0;
int r;
assert(key);
/* For a SOA record we can never find a matching SOA record */
if (key->type == DNS_TYPE_SOA)
goto not_found;
DNS_ANSWER_FOREACH_FLAGS(rr, rr_flags, a) {
r = dns_resource_key_match_soa(key, rr->key);
if (r < 0)
return r;
if (r > 0) {
if (soa) {
r = dns_name_endswith(dns_resource_key_name(rr->key), dns_resource_key_name(soa->key));
if (r < 0)
return r;
if (r > 0)
continue;
}
soa = rr;
soa_flags = rr_flags;
}
}
if (!soa)
goto not_found;
if (ret)
*ret = soa;
if (ret_flags)
*ret_flags = soa_flags;
return 1;
not_found:
if (ret)
*ret = NULL;
if (ret_flags)
*ret_flags = 0;
return 0;
}
int dns_answer_find_cname_or_dname(
DnsAnswer *a,
const DnsResourceKey *key,
DnsResourceRecord **ret,
DnsAnswerFlags *ret_flags) {
DnsResourceRecord *rr;
DnsAnswerFlags rr_flags;
int r;
assert(key);
/* For a {C,D}NAME record we can never find a matching {C,D}NAME record */
if (!dns_type_may_redirect(key->type))
return 0;
DNS_ANSWER_FOREACH_FLAGS(rr, rr_flags, a) {
r = dns_resource_key_match_cname_or_dname(key, rr->key, NULL);
if (r < 0)
return r;
if (r > 0) {
if (ret)
*ret = rr;
if (ret_flags)
*ret_flags = rr_flags;
return 1;
}
}
if (ret)
*ret = NULL;
if (ret_flags)
*ret_flags = 0;
return 0;
}
int dns_answer_merge(DnsAnswer *a, DnsAnswer *b, DnsAnswer **ret) {
_cleanup_(dns_answer_unrefp) DnsAnswer *k = NULL;
int r;
assert(ret);
if (a == b) {
*ret = dns_answer_ref(a);
return 0;
}
if (dns_answer_size(a) <= 0) {
*ret = dns_answer_ref(b);
return 0;
}
if (dns_answer_size(b) <= 0) {
*ret = dns_answer_ref(a);
return 0;
}
k = dns_answer_new(dns_answer_size(a) + dns_answer_size(b));
if (!k)
return -ENOMEM;
r = dns_answer_add_raw_all(k, a);
if (r < 0)
return r;
r = dns_answer_add_all(k, b);
if (r < 0)
return r;
*ret = TAKE_PTR(k);
return 0;
}
int dns_answer_extend(DnsAnswer **a, DnsAnswer *b) {
DnsAnswer *merged;
int r;
assert(a);
r = dns_answer_merge(*a, b, &merged);
if (r < 0)
return r;
DNS_ANSWER_REPLACE(*a, merged);
return 0;
}
int dns_answer_remove_by_key(DnsAnswer **a, const DnsResourceKey *key) {
DnsAnswerItem *item;
bool found = false;
int r;
assert(a);
assert(key);
/* Remove all entries matching the specified key from *a */
DNS_ANSWER_FOREACH_ITEM(item, *a) {
r = dns_resource_key_equal(item->rr->key, key);
if (r < 0)
return r;
if (r > 0) {
dns_answer_item_unref(ordered_set_remove((*a)->items, item));
found = true;
}
}
if (!found)
return 0;
if (dns_answer_isempty(*a))
*a = dns_answer_unref(*a); /* Return NULL for the empty answer */
return 1;
}
int dns_answer_remove_by_rr(DnsAnswer **a, DnsResourceRecord *rr) {
_unused_ _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr_ref = dns_resource_record_ref(rr);
DnsAnswerItem *item;
bool found = false;
int r;
assert(a);
assert(rr);
/* Remove all entries matching the specified RR from *a */
DNS_ANSWER_FOREACH_ITEM(item, *a) {
r = dns_resource_record_equal(item->rr, rr);
if (r < 0)
return r;
if (r > 0) {
dns_answer_item_unref(ordered_set_remove((*a)->items, item));
found = true;
}
}
if (!found)
return 0;
if (dns_answer_isempty(*a))
*a = dns_answer_unref(*a); /* Return NULL for the empty answer */
return 1;
}
int dns_answer_remove_by_answer_keys(DnsAnswer **a, DnsAnswer *b) {
_cleanup_(dns_resource_key_unrefp) DnsResourceKey *prev = NULL;
DnsAnswerItem *item;
int r;
/* Removes all items from '*a' that have a matching key in 'b' */
DNS_ANSWER_FOREACH_ITEM(item, b) {
if (prev && dns_resource_key_equal(item->rr->key, prev)) /* Skip this one, we already looked at it */
continue;
r = dns_answer_remove_by_key(a, item->rr->key);
if (r < 0)
return r;
if (!*a)
return 0; /* a is already empty. */
/* Let's remember this entry's RR key, to optimize the loop a bit: if we have an RRset with
* more than one item then we don't need to remove the key multiple times */
DNS_RESOURCE_KEY_REPLACE(prev, dns_resource_key_ref(item->rr->key));
}
return 0;
}
int dns_answer_copy_by_key(
DnsAnswer **a,
DnsAnswer *source,
const DnsResourceKey *key,
DnsAnswerFlags or_flags,
DnsResourceRecord *rrsig) {
DnsAnswerItem *item;
int r;
assert(a);
assert(key);
/* Copy all RRs matching the specified key from source into *a */
DNS_ANSWER_FOREACH_ITEM(item, source) {
r = dns_resource_key_equal(item->rr->key, key);
if (r < 0)
return r;
if (r == 0)
continue;
r = dns_answer_add_extend(a, item->rr, item->ifindex, item->flags|or_flags, rrsig ?: item->rrsig);
if (r < 0)
return r;
}
return 0;
}
int dns_answer_move_by_key(
DnsAnswer **to,
DnsAnswer **from,
const DnsResourceKey *key,
DnsAnswerFlags or_flags,
DnsResourceRecord *rrsig) {
int r;
assert(to);
assert(from);
assert(key);
r = dns_answer_copy_by_key(to, *from, key, or_flags, rrsig);
if (r < 0)
return r;
return dns_answer_remove_by_key(from, key);
}
void dns_answer_order_by_scope(DnsAnswer *a, bool prefer_link_local) {
_cleanup_free_ DnsAnswerItem **items = NULL;
DnsAnswerItem **p, *item;
size_t n;
n = dns_answer_size(a);
if (n <= 1)
return;
/* RFC 4795, Section 2.6 suggests we should order entries
* depending on whether the sender is a link-local address. */
p = items = new(DnsAnswerItem*, n);
if (!items)
return (void) log_oom();
/* Order preferred address records and other records to the beginning of the array */
DNS_ANSWER_FOREACH_ITEM(item, a)
if (dns_resource_record_is_link_local_address(item->rr) == prefer_link_local)
*p++ = dns_answer_item_ref(item);
/* Order address records that are not preferred to the end of the array */
DNS_ANSWER_FOREACH_ITEM(item, a)
if (dns_resource_record_is_link_local_address(item->rr) != prefer_link_local)
*p++ = dns_answer_item_ref(item);
assert((size_t) (p - items) == n);
ordered_set_clear(a->items);
for (size_t i = 0; i < n; i++)
assert_se(ordered_set_put(a->items, items[i]) >= 0);
}
int dns_answer_reserve(DnsAnswer **a, size_t n_free) {
assert(a);
if (n_free <= 0)
return 0;
if (!*a) {
DnsAnswer *n;
n = dns_answer_new(n_free);
if (!n)
return -ENOMEM;
*a = n;
return 0;
}
if ((*a)->n_ref > 1)
return -EBUSY;
return dns_answer_reserve_internal(*a, n_free);
}
int dns_answer_reserve_or_clone(DnsAnswer **a, size_t n_free) {
_cleanup_(dns_answer_unrefp) DnsAnswer *n = NULL;
size_t ns;
int r;
assert(a);
r = dns_answer_reserve(a, n_free);
if (r != -EBUSY)
return r;
ns = dns_answer_size(*a);
assert(ns <= UINT16_MAX); /* Maximum number of RRs we can stick into a DNS packet section */
ns = saturate_add(ns, n_free, UINT16_MAX);
n = dns_answer_new(ns);
if (!n)
return -ENOMEM;
r = dns_answer_add_raw_all(n, *a);
if (r < 0)
return r;
DNS_ANSWER_REPLACE(*a, TAKE_PTR(n));
return 0;
}
/*
* This function is not used in the code base, but is useful when debugging. Do not delete.
*/
void dns_answer_dump(DnsAnswer *answer, FILE *f) {
DnsAnswerItem *item;
if (!f)
f = stdout;
DNS_ANSWER_FOREACH_ITEM(item, answer) {
const char *t;
fputc('\t', f);
t = dns_resource_record_to_string(item->rr);
if (!t) {
log_oom();
continue;
}
fputs(t, f);
fputs("\t;", f);
fprintf(f, " ttl=%" PRIu32, item->rr->ttl);
if (item->ifindex != 0)
fprintf(f, " ifindex=%i", item->ifindex);
if (item->rrsig)
fputs(" rrsig", f);
if (item->flags & DNS_ANSWER_AUTHENTICATED)
fputs(" authenticated", f);
if (item->flags & DNS_ANSWER_CACHEABLE)
fputs(" cacheable", f);
if (item->flags & DNS_ANSWER_SHARED_OWNER)
fputs(" shared-owner", f);
if (item->flags & DNS_ANSWER_CACHE_FLUSH)
fputs(" cache-flush", f);
if (item->flags & DNS_ANSWER_GOODBYE)
fputs(" goodbye", f);
if (item->flags & DNS_ANSWER_SECTION_ANSWER)
fputs(" section-answer", f);
if (item->flags & DNS_ANSWER_SECTION_AUTHORITY)
fputs(" section-authority", f);
if (item->flags & DNS_ANSWER_SECTION_ADDITIONAL)
fputs(" section-additional", f);
fputc('\n', f);
}
}
int dns_answer_has_dname_for_cname(DnsAnswer *a, DnsResourceRecord *cname) {
DnsResourceRecord *rr;
int r;
assert(cname);
/* Checks whether the answer contains a DNAME record that indicates that the specified CNAME record is
* synthesized from it */
if (cname->key->type != DNS_TYPE_CNAME)
return 0;
DNS_ANSWER_FOREACH(rr, a) {
_cleanup_free_ char *n = NULL;
if (rr->key->type != DNS_TYPE_DNAME)
continue;
if (rr->key->class != cname->key->class)
continue;
r = dns_name_change_suffix(cname->cname.name, rr->dname.name, dns_resource_key_name(rr->key), &n);
if (r < 0)
return r;
if (r == 0)
continue;
r = dns_name_equal(n, dns_resource_key_name(cname->key));
if (r < 0)
return r;
if (r > 0)
return 1;
}
return 0;
}
void dns_answer_randomize(DnsAnswer *a) {
_cleanup_free_ DnsAnswerItem **items = NULL;
DnsAnswerItem **p, *item;
size_t n;
/* Permutes the answer list randomly (Knuth shuffle) */
n = dns_answer_size(a);
if (n <= 1)
return;
p = items = new(DnsAnswerItem*, n);
if (!items)
return (void) log_oom();
DNS_ANSWER_FOREACH_ITEM(item, a)
*p++ = dns_answer_item_ref(item);
assert((size_t) (p - items) == n);
for (size_t i = 0; i < n; i++) {
size_t k;
k = random_u64_range(n);
if (k == i)
continue;
SWAP_TWO(items[i], items[k]);
}
ordered_set_clear(a->items);
for (size_t i = 0; i < n; i++)
assert_se(ordered_set_put(a->items, items[i]) >= 0);
}
uint32_t dns_answer_min_ttl(DnsAnswer *a) {
uint32_t ttl = UINT32_MAX;
DnsResourceRecord *rr;
/* Return the smallest TTL of all RRs in this answer */
DNS_ANSWER_FOREACH(rr, a) {
/* Don't consider OPT (where the TTL field is used for other purposes than an actual TTL) */
if (dns_type_is_pseudo(rr->key->type) ||
dns_class_is_pseudo(rr->key->class))
continue;
ttl = MIN(ttl, rr->ttl);
}
return ttl;
}
| 23,835 | 27.009401 | 119 |
c
|
null |
systemd-main/src/resolve/resolved-dns-cache.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "hashmap.h"
#include "list.h"
#include "prioq.h"
#include "resolve-util.h"
#include "resolved-dns-dnssec.h"
#include "time-util.h"
typedef struct DnsCache {
Hashmap *by_key;
Prioq *by_expiry;
unsigned n_hit;
unsigned n_miss;
} DnsCache;
#include "resolved-dns-answer.h"
#include "resolved-dns-packet.h"
#include "resolved-dns-question.h"
#include "resolved-dns-rr.h"
void dns_cache_flush(DnsCache *c);
void dns_cache_prune(DnsCache *c);
int dns_cache_put(
DnsCache *c,
DnsCacheMode cache_mode,
DnsProtocol protocol,
DnsResourceKey *key,
int rcode,
DnsAnswer *answer,
DnsPacket *full_packet,
uint64_t query_flags,
DnssecResult dnssec_result,
uint32_t nsec_ttl,
int owner_family,
const union in_addr_union *owner_address,
usec_t stale_retention_usec);
int dns_cache_lookup(
DnsCache *c,
DnsResourceKey *key,
uint64_t query_flags,
int *ret_rcode,
DnsAnswer **ret_answer,
DnsPacket **ret_full_packet,
uint64_t *ret_query_flags,
DnssecResult *ret_dnssec_result);
int dns_cache_check_conflicts(DnsCache *cache, DnsResourceRecord *rr, int owner_family, const union in_addr_union *owner_address);
void dns_cache_dump(DnsCache *cache, FILE *f);
int dns_cache_dump_to_json(DnsCache *cache, JsonVariant **ret);
bool dns_cache_is_empty(DnsCache *cache);
unsigned dns_cache_size(DnsCache *cache);
int dns_cache_export_shared_to_packet(DnsCache *cache, DnsPacket *p, usec_t ts, unsigned max_rr);
| 1,832 | 29.04918 | 130 |
h
|
null |
systemd-main/src/resolve/resolved-dns-search-domain.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "dns-domain.h"
#include "resolved-dns-search-domain.h"
#include "resolved-link.h"
#include "resolved-manager.h"
int dns_search_domain_new(
Manager *m,
DnsSearchDomain **ret,
DnsSearchDomainType type,
Link *l,
const char *name) {
_cleanup_free_ char *normalized = NULL;
DnsSearchDomain *d;
int r;
assert(m);
assert((type == DNS_SEARCH_DOMAIN_LINK) == !!l);
assert(name);
r = dns_name_normalize(name, 0, &normalized);
if (r < 0)
return r;
if (l) {
if (l->n_search_domains >= LINK_SEARCH_DOMAINS_MAX)
return -E2BIG;
} else {
if (m->n_search_domains >= MANAGER_SEARCH_DOMAINS_MAX)
return -E2BIG;
}
d = new(DnsSearchDomain, 1);
if (!d)
return -ENOMEM;
*d = (DnsSearchDomain) {
.n_ref = 1,
.manager = m,
.type = type,
.name = TAKE_PTR(normalized),
};
switch (type) {
case DNS_SEARCH_DOMAIN_LINK:
d->link = l;
LIST_APPEND(domains, l->search_domains, d);
l->n_search_domains++;
break;
case DNS_SEARCH_DOMAIN_SYSTEM:
LIST_APPEND(domains, m->search_domains, d);
m->n_search_domains++;
break;
default:
assert_not_reached();
}
d->linked = true;
if (ret)
*ret = d;
return 0;
}
static DnsSearchDomain* dns_search_domain_free(DnsSearchDomain *d) {
assert(d);
free(d->name);
return mfree(d);
}
DEFINE_TRIVIAL_REF_UNREF_FUNC(DnsSearchDomain, dns_search_domain, dns_search_domain_free);
void dns_search_domain_unlink(DnsSearchDomain *d) {
assert(d);
assert(d->manager);
if (!d->linked)
return;
switch (d->type) {
case DNS_SEARCH_DOMAIN_LINK:
assert(d->link);
assert(d->link->n_search_domains > 0);
LIST_REMOVE(domains, d->link->search_domains, d);
d->link->n_search_domains--;
break;
case DNS_SEARCH_DOMAIN_SYSTEM:
assert(d->manager->n_search_domains > 0);
LIST_REMOVE(domains, d->manager->search_domains, d);
d->manager->n_search_domains--;
break;
}
d->linked = false;
dns_search_domain_unref(d);
}
void dns_search_domain_move_back_and_unmark(DnsSearchDomain *d) {
DnsSearchDomain *tail;
assert(d);
if (!d->marked)
return;
d->marked = false;
if (!d->linked || !d->domains_next)
return;
switch (d->type) {
case DNS_SEARCH_DOMAIN_LINK:
assert(d->link);
tail = LIST_FIND_TAIL(domains, d);
LIST_REMOVE(domains, d->link->search_domains, d);
LIST_INSERT_AFTER(domains, d->link->search_domains, tail, d);
break;
case DNS_SEARCH_DOMAIN_SYSTEM:
tail = LIST_FIND_TAIL(domains, d);
LIST_REMOVE(domains, d->manager->search_domains, d);
LIST_INSERT_AFTER(domains, d->manager->search_domains, tail, d);
break;
default:
assert_not_reached();
}
}
void dns_search_domain_unlink_all(DnsSearchDomain *first) {
DnsSearchDomain *next;
if (!first)
return;
next = first->domains_next;
dns_search_domain_unlink(first);
dns_search_domain_unlink_all(next);
}
bool dns_search_domain_unlink_marked(DnsSearchDomain *first) {
DnsSearchDomain *next;
bool changed;
if (!first)
return false;
next = first->domains_next;
if (first->marked) {
dns_search_domain_unlink(first);
changed = true;
} else
changed = false;
return dns_search_domain_unlink_marked(next) || changed;
}
void dns_search_domain_mark_all(DnsSearchDomain *first) {
if (!first)
return;
first->marked = true;
dns_search_domain_mark_all(first->domains_next);
}
int dns_search_domain_find(DnsSearchDomain *first, const char *name, DnsSearchDomain **ret) {
int r;
assert(name);
assert(ret);
LIST_FOREACH(domains, d, first) {
r = dns_name_equal(name, d->name);
if (r < 0)
return r;
if (r > 0) {
*ret = d;
return 1;
}
}
*ret = NULL;
return 0;
}
| 5,006 | 24.035 | 93 |
c
|
null |
systemd-main/src/resolve/resolved-dns-search-domain.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "list.h"
#include "macro.h"
typedef struct DnsSearchDomain DnsSearchDomain;
typedef struct Link Link;
typedef struct Manager Manager;
typedef enum DnsSearchDomainType {
DNS_SEARCH_DOMAIN_SYSTEM,
DNS_SEARCH_DOMAIN_LINK,
} DnsSearchDomainType;
struct DnsSearchDomain {
Manager *manager;
unsigned n_ref;
DnsSearchDomainType type;
Link *link;
char *name;
bool marked:1;
bool route_only:1;
bool linked:1;
LIST_FIELDS(DnsSearchDomain, domains);
};
int dns_search_domain_new(
Manager *m,
DnsSearchDomain **ret,
DnsSearchDomainType type,
Link *link,
const char *name);
DnsSearchDomain* dns_search_domain_ref(DnsSearchDomain *d);
DnsSearchDomain* dns_search_domain_unref(DnsSearchDomain *d);
void dns_search_domain_unlink(DnsSearchDomain *d);
void dns_search_domain_move_back_and_unmark(DnsSearchDomain *d);
void dns_search_domain_unlink_all(DnsSearchDomain *first);
bool dns_search_domain_unlink_marked(DnsSearchDomain *first);
void dns_search_domain_mark_all(DnsSearchDomain *first);
int dns_search_domain_find(DnsSearchDomain *first, const char *name, DnsSearchDomain **ret);
static inline const char* DNS_SEARCH_DOMAIN_NAME(DnsSearchDomain *d) {
return d ? d->name : NULL;
}
DEFINE_TRIVIAL_CLEANUP_FUNC(DnsSearchDomain*, dns_search_domain_unref);
| 1,505 | 25.421053 | 92 |
h
|
null |
systemd-main/src/resolve/resolved-dns-stream.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <netinet/tcp.h>
#include <unistd.h>
#include "alloc-util.h"
#include "fd-util.h"
#include "io-util.h"
#include "macro.h"
#include "missing_network.h"
#include "resolved-dns-stream.h"
#include "resolved-manager.h"
#define DNS_STREAMS_MAX 128
#define DNS_QUERIES_PER_STREAM 32
static void dns_stream_stop(DnsStream *s) {
assert(s);
s->io_event_source = sd_event_source_disable_unref(s->io_event_source);
s->timeout_event_source = sd_event_source_disable_unref(s->timeout_event_source);
s->fd = safe_close(s->fd);
/* Disconnect us from the server object if we are now not usable anymore */
dns_stream_detach(s);
}
static int dns_stream_update_io(DnsStream *s) {
uint32_t f = 0;
assert(s);
if (s->write_packet && s->n_written < sizeof(s->write_size) + s->write_packet->size)
f |= EPOLLOUT;
else if (!ordered_set_isempty(s->write_queue)) {
dns_packet_unref(s->write_packet);
s->write_packet = ordered_set_steal_first(s->write_queue);
s->write_size = htobe16(s->write_packet->size);
s->n_written = 0;
f |= EPOLLOUT;
}
/* Let's read a packet if we haven't queued any yet. Except if we already hit a limit of parallel
* queries for this connection. */
if ((!s->read_packet || s->n_read < sizeof(s->read_size) + s->read_packet->size) &&
set_size(s->queries) < DNS_QUERIES_PER_STREAM)
f |= EPOLLIN;
s->requested_events = f;
#if ENABLE_DNS_OVER_TLS
/* For handshake and clean closing purposes, TLS can override requested events */
if (s->dnstls_events != 0)
f = s->dnstls_events;
#endif
return sd_event_source_set_io_events(s->io_event_source, f);
}
static int dns_stream_complete(DnsStream *s, int error) {
_cleanup_(dns_stream_unrefp) _unused_ DnsStream *ref = dns_stream_ref(s); /* Protect stream while we process it */
assert(s);
assert(error >= 0);
/* Error is > 0 when the connection failed for some reason in the network stack. It's == 0 if we sent
* and received exactly one packet each (in the LLMNR client case). */
#if ENABLE_DNS_OVER_TLS
if (s->encrypted) {
int r;
r = dnstls_stream_shutdown(s, error);
if (r != -EAGAIN)
dns_stream_stop(s);
} else
#endif
dns_stream_stop(s);
dns_stream_detach(s);
if (s->complete)
s->complete(s, error);
else /* the default action if no completion function is set is to close the stream */
dns_stream_unref(s);
return 0;
}
static int dns_stream_identify(DnsStream *s) {
CMSG_BUFFER_TYPE(CMSG_SPACE(MAXSIZE(struct in_pktinfo, struct in6_pktinfo))
+ CMSG_SPACE(int) + /* for the TTL */
+ EXTRA_CMSG_SPACE /* kernel appears to require extra space */) control;
struct msghdr mh = {};
struct cmsghdr *cmsg;
socklen_t sl;
int r;
assert(s);
if (s->identified)
return 0;
/* Query the local side */
s->local_salen = sizeof(s->local);
r = getsockname(s->fd, &s->local.sa, &s->local_salen);
if (r < 0)
return -errno;
if (s->local.sa.sa_family == AF_INET6 && s->ifindex <= 0)
s->ifindex = s->local.in6.sin6_scope_id;
/* Query the remote side */
s->peer_salen = sizeof(s->peer);
r = getpeername(s->fd, &s->peer.sa, &s->peer_salen);
if (r < 0)
return -errno;
if (s->peer.sa.sa_family == AF_INET6 && s->ifindex <= 0)
s->ifindex = s->peer.in6.sin6_scope_id;
/* Check consistency */
assert(s->peer.sa.sa_family == s->local.sa.sa_family);
assert(IN_SET(s->peer.sa.sa_family, AF_INET, AF_INET6));
/* Query connection meta information */
sl = sizeof(control);
if (s->peer.sa.sa_family == AF_INET) {
r = getsockopt(s->fd, IPPROTO_IP, IP_PKTOPTIONS, &control, &sl);
if (r < 0)
return -errno;
} else if (s->peer.sa.sa_family == AF_INET6) {
r = getsockopt(s->fd, IPPROTO_IPV6, IPV6_2292PKTOPTIONS, &control, &sl);
if (r < 0)
return -errno;
} else
return -EAFNOSUPPORT;
mh.msg_control = &control;
mh.msg_controllen = sl;
CMSG_FOREACH(cmsg, &mh) {
if (cmsg->cmsg_level == IPPROTO_IPV6) {
assert(s->peer.sa.sa_family == AF_INET6);
switch (cmsg->cmsg_type) {
case IPV6_PKTINFO: {
struct in6_pktinfo *i = CMSG_TYPED_DATA(cmsg, struct in6_pktinfo);
if (s->ifindex <= 0)
s->ifindex = i->ipi6_ifindex;
break;
}
case IPV6_HOPLIMIT:
s->ttl = *CMSG_TYPED_DATA(cmsg, int);
break;
}
} else if (cmsg->cmsg_level == IPPROTO_IP) {
assert(s->peer.sa.sa_family == AF_INET);
switch (cmsg->cmsg_type) {
case IP_PKTINFO: {
struct in_pktinfo *i = CMSG_TYPED_DATA(cmsg, struct in_pktinfo);
if (s->ifindex <= 0)
s->ifindex = i->ipi_ifindex;
break;
}
case IP_TTL:
s->ttl = *CMSG_TYPED_DATA(cmsg, int);
break;
}
}
}
/* The Linux kernel sets the interface index to the loopback
* device if the connection came from the local host since it
* avoids the routing table in such a case. Let's unset the
* interface index in such a case. */
if (s->ifindex == LOOPBACK_IFINDEX)
s->ifindex = 0;
/* If we don't know the interface index still, we look for the
* first local interface with a matching address. Yuck! */
if (s->ifindex <= 0)
s->ifindex = manager_find_ifindex(s->manager, s->local.sa.sa_family, sockaddr_in_addr(&s->local.sa));
if (s->protocol == DNS_PROTOCOL_LLMNR && s->ifindex > 0) {
/* Make sure all packets for this connection are sent on the same interface */
r = socket_set_unicast_if(s->fd, s->local.sa.sa_family, s->ifindex);
if (r < 0)
log_debug_errno(errno, "Failed to invoke IP_UNICAST_IF/IPV6_UNICAST_IF: %m");
}
s->identified = true;
return 0;
}
ssize_t dns_stream_writev(DnsStream *s, const struct iovec *iov, size_t iovcnt, int flags) {
ssize_t m;
assert(s);
assert(iov);
#if ENABLE_DNS_OVER_TLS
if (s->encrypted && !(flags & DNS_STREAM_WRITE_TLS_DATA))
return dnstls_stream_writev(s, iov, iovcnt);
#endif
if (s->tfo_salen > 0) {
struct msghdr hdr = {
.msg_iov = (struct iovec*) iov,
.msg_iovlen = iovcnt,
.msg_name = &s->tfo_address.sa,
.msg_namelen = s->tfo_salen
};
m = sendmsg(s->fd, &hdr, MSG_FASTOPEN);
if (m < 0) {
if (errno == EOPNOTSUPP) {
s->tfo_salen = 0;
if (connect(s->fd, &s->tfo_address.sa, s->tfo_salen) < 0)
return -errno;
return -EAGAIN;
}
if (errno == EINPROGRESS)
return -EAGAIN;
return -errno;
} else
s->tfo_salen = 0; /* connection is made */
} else {
m = writev(s->fd, iov, iovcnt);
if (m < 0)
return -errno;
}
return m;
}
static ssize_t dns_stream_read(DnsStream *s, void *buf, size_t count) {
ssize_t ss;
#if ENABLE_DNS_OVER_TLS
if (s->encrypted)
ss = dnstls_stream_read(s, buf, count);
else
#endif
{
ss = read(s->fd, buf, count);
if (ss < 0)
return -errno;
}
return ss;
}
static int on_stream_timeout(sd_event_source *es, usec_t usec, void *userdata) {
DnsStream *s = ASSERT_PTR(userdata);
return dns_stream_complete(s, ETIMEDOUT);
}
static DnsPacket *dns_stream_take_read_packet(DnsStream *s) {
assert(s);
/* Note, dns_stream_update() should be called after this is called. When this is called, the
* stream may be already full and the EPOLLIN flag is dropped from the stream IO event source.
* Even this makes a room to read in the stream, this does not call dns_stream_update(), hence
* EPOLLIN flag is not set automatically. So, to read further packets from the stream,
* dns_stream_update() must be called explicitly. Currently, this is only called from
* on_stream_io(), and there dns_stream_update() is called. */
if (!s->read_packet)
return NULL;
if (s->n_read < sizeof(s->read_size))
return NULL;
if (s->n_read < sizeof(s->read_size) + be16toh(s->read_size))
return NULL;
s->n_read = 0;
return TAKE_PTR(s->read_packet);
}
static int on_stream_io(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
_cleanup_(dns_stream_unrefp) DnsStream *s = dns_stream_ref(userdata); /* Protect stream while we process it */
bool progressed = false;
int r;
assert(s);
#if ENABLE_DNS_OVER_TLS
if (s->encrypted) {
r = dnstls_stream_on_io(s, revents);
if (r == DNSTLS_STREAM_CLOSED)
return 0;
if (r == -EAGAIN)
return dns_stream_update_io(s);
if (r < 0)
return dns_stream_complete(s, -r);
r = dns_stream_update_io(s);
if (r < 0)
return r;
}
#endif
/* only identify after connecting */
if (s->tfo_salen == 0) {
r = dns_stream_identify(s);
if (r < 0)
return dns_stream_complete(s, -r);
}
if ((revents & EPOLLOUT) &&
s->write_packet &&
s->n_written < sizeof(s->write_size) + s->write_packet->size) {
struct iovec iov[] = {
IOVEC_MAKE(&s->write_size, sizeof(s->write_size)),
IOVEC_MAKE(DNS_PACKET_DATA(s->write_packet), s->write_packet->size),
};
IOVEC_INCREMENT(iov, ELEMENTSOF(iov), s->n_written);
ssize_t ss = dns_stream_writev(s, iov, ELEMENTSOF(iov), 0);
if (ss < 0) {
if (!ERRNO_IS_TRANSIENT(ss))
return dns_stream_complete(s, -ss);
} else {
progressed = true;
s->n_written += ss;
}
/* Are we done? If so, disable the event source for EPOLLOUT */
if (s->n_written >= sizeof(s->write_size) + s->write_packet->size) {
r = dns_stream_update_io(s);
if (r < 0)
return dns_stream_complete(s, -r);
}
}
while ((revents & (EPOLLIN|EPOLLHUP|EPOLLRDHUP)) &&
(!s->read_packet ||
s->n_read < sizeof(s->read_size) + s->read_packet->size)) {
if (s->n_read < sizeof(s->read_size)) {
ssize_t ss;
ss = dns_stream_read(s, (uint8_t*) &s->read_size + s->n_read, sizeof(s->read_size) - s->n_read);
if (ss < 0) {
if (!ERRNO_IS_TRANSIENT(ss))
return dns_stream_complete(s, -ss);
break;
} else if (ss == 0)
return dns_stream_complete(s, ECONNRESET);
else {
progressed = true;
s->n_read += ss;
}
}
if (s->n_read >= sizeof(s->read_size)) {
if (be16toh(s->read_size) < DNS_PACKET_HEADER_SIZE)
return dns_stream_complete(s, EBADMSG);
if (s->n_read < sizeof(s->read_size) + be16toh(s->read_size)) {
ssize_t ss;
if (!s->read_packet) {
r = dns_packet_new(&s->read_packet, s->protocol, be16toh(s->read_size), DNS_PACKET_SIZE_MAX);
if (r < 0)
return dns_stream_complete(s, -r);
s->read_packet->size = be16toh(s->read_size);
s->read_packet->ipproto = IPPROTO_TCP;
s->read_packet->family = s->peer.sa.sa_family;
s->read_packet->ttl = s->ttl;
s->read_packet->ifindex = s->ifindex;
s->read_packet->timestamp = now(CLOCK_BOOTTIME);
if (s->read_packet->family == AF_INET) {
s->read_packet->sender.in = s->peer.in.sin_addr;
s->read_packet->sender_port = be16toh(s->peer.in.sin_port);
s->read_packet->destination.in = s->local.in.sin_addr;
s->read_packet->destination_port = be16toh(s->local.in.sin_port);
} else {
assert(s->read_packet->family == AF_INET6);
s->read_packet->sender.in6 = s->peer.in6.sin6_addr;
s->read_packet->sender_port = be16toh(s->peer.in6.sin6_port);
s->read_packet->destination.in6 = s->local.in6.sin6_addr;
s->read_packet->destination_port = be16toh(s->local.in6.sin6_port);
if (s->read_packet->ifindex == 0)
s->read_packet->ifindex = s->peer.in6.sin6_scope_id;
if (s->read_packet->ifindex == 0)
s->read_packet->ifindex = s->local.in6.sin6_scope_id;
}
}
ss = dns_stream_read(s,
(uint8_t*) DNS_PACKET_DATA(s->read_packet) + s->n_read - sizeof(s->read_size),
sizeof(s->read_size) + be16toh(s->read_size) - s->n_read);
if (ss < 0) {
if (!ERRNO_IS_TRANSIENT(ss))
return dns_stream_complete(s, -ss);
break;
} else if (ss == 0)
return dns_stream_complete(s, ECONNRESET);
else
s->n_read += ss;
}
/* Are we done? If so, call the packet handler and re-enable EPOLLIN for the
* event source if necessary. */
_cleanup_(dns_packet_unrefp) DnsPacket *p = dns_stream_take_read_packet(s);
if (p) {
assert(s->on_packet);
r = s->on_packet(s, p);
if (r < 0)
return r;
r = dns_stream_update_io(s);
if (r < 0)
return dns_stream_complete(s, -r);
s->packet_received = true;
/* If we just disabled the read event, stop reading */
if (!FLAGS_SET(s->requested_events, EPOLLIN))
break;
}
}
}
/* Complete the stream if finished reading and writing one packet, and there's nothing
* else left to write. */
if (s->type == DNS_STREAM_LLMNR_SEND && s->packet_received &&
!FLAGS_SET(s->requested_events, EPOLLOUT))
return dns_stream_complete(s, 0);
/* If we did something, let's restart the timeout event source */
if (progressed && s->timeout_event_source) {
r = sd_event_source_set_time_relative(s->timeout_event_source, DNS_STREAM_ESTABLISHED_TIMEOUT_USEC);
if (r < 0)
log_warning_errno(errno, "Couldn't restart TCP connection timeout, ignoring: %m");
}
return 0;
}
static DnsStream *dns_stream_free(DnsStream *s) {
DnsPacket *p;
assert(s);
dns_stream_stop(s);
if (s->manager) {
LIST_REMOVE(streams, s->manager->dns_streams, s);
s->manager->n_dns_streams[s->type]--;
}
#if ENABLE_DNS_OVER_TLS
if (s->encrypted)
dnstls_stream_free(s);
#endif
ORDERED_SET_FOREACH(p, s->write_queue)
dns_packet_unref(ordered_set_remove(s->write_queue, p));
dns_packet_unref(s->write_packet);
dns_packet_unref(s->read_packet);
dns_server_unref(s->server);
ordered_set_free(s->write_queue);
return mfree(s);
}
DEFINE_TRIVIAL_REF_UNREF_FUNC(DnsStream, dns_stream, dns_stream_free);
int dns_stream_new(
Manager *m,
DnsStream **ret,
DnsStreamType type,
DnsProtocol protocol,
int fd,
const union sockaddr_union *tfo_address,
int (on_packet)(DnsStream*, DnsPacket*),
int (complete)(DnsStream*, int), /* optional */
usec_t connect_timeout_usec) {
_cleanup_(dns_stream_unrefp) DnsStream *s = NULL;
int r;
assert(m);
assert(ret);
assert(type >= 0);
assert(type < _DNS_STREAM_TYPE_MAX);
assert(protocol >= 0);
assert(protocol < _DNS_PROTOCOL_MAX);
assert(fd >= 0);
assert(on_packet);
if (m->n_dns_streams[type] > DNS_STREAMS_MAX)
return -EBUSY;
s = new(DnsStream, 1);
if (!s)
return -ENOMEM;
*s = (DnsStream) {
.n_ref = 1,
.fd = -EBADF,
.protocol = protocol,
.type = type,
};
r = ordered_set_ensure_allocated(&s->write_queue, &dns_packet_hash_ops);
if (r < 0)
return r;
r = sd_event_add_io(m->event, &s->io_event_source, fd, EPOLLIN, on_stream_io, s);
if (r < 0)
return r;
(void) sd_event_source_set_description(s->io_event_source, "dns-stream-io");
r = sd_event_add_time_relative(
m->event,
&s->timeout_event_source,
CLOCK_BOOTTIME,
connect_timeout_usec, 0,
on_stream_timeout, s);
if (r < 0)
return r;
(void) sd_event_source_set_description(s->timeout_event_source, "dns-stream-timeout");
LIST_PREPEND(streams, m->dns_streams, s);
m->n_dns_streams[type]++;
s->manager = m;
s->fd = fd;
s->on_packet = on_packet;
s->complete = complete;
if (tfo_address) {
s->tfo_address = *tfo_address;
s->tfo_salen = tfo_address->sa.sa_family == AF_INET6 ? sizeof(tfo_address->in6) : sizeof(tfo_address->in);
}
*ret = TAKE_PTR(s);
return 0;
}
int dns_stream_write_packet(DnsStream *s, DnsPacket *p) {
int r;
assert(s);
assert(p);
r = ordered_set_put(s->write_queue, p);
if (r < 0)
return r;
dns_packet_ref(p);
return dns_stream_update_io(s);
}
void dns_stream_detach(DnsStream *s) {
assert(s);
if (!s->server)
return;
if (s->server->stream != s)
return;
dns_server_unref_stream(s->server);
}
| 21,824 | 35.619128 | 133 |
c
|
null |
systemd-main/src/resolve/resolved-dns-stream.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-event.h"
#include "ordered-set.h"
#include "socket-util.h"
typedef struct DnsServer DnsServer;
typedef struct DnsStream DnsStream;
typedef struct DnsTransaction DnsTransaction;
typedef struct Manager Manager;
typedef struct DnsStubListenerExtra DnsStubListenerExtra;
#include "resolved-dns-packet.h"
#include "resolved-dnstls.h"
/* Various timeouts for establishing TCP connections. First the default time-out for that. */
#define DNS_STREAM_DEFAULT_TIMEOUT_USEC (10 * USEC_PER_SEC)
/* In the DNS stub, be more friendly for incoming connections, than we are to ourselves for outgoing ones */
#define DNS_STREAM_STUB_TIMEOUT_USEC (30 * USEC_PER_SEC)
/* In opportunistic TLS mode, lower timeouts */
#define DNS_STREAM_OPPORTUNISTIC_TLS_TIMEOUT_USEC (3 * USEC_PER_SEC)
/* Once connections are established apply this timeout once nothing happens anymore */
#define DNS_STREAM_ESTABLISHED_TIMEOUT_USEC (10 * USEC_PER_SEC)
typedef enum DnsStreamType {
DNS_STREAM_LOOKUP, /* Outgoing connection to a classic DNS server */
DNS_STREAM_LLMNR_SEND, /* Outgoing LLMNR TCP lookup */
DNS_STREAM_LLMNR_RECV, /* Incoming LLMNR TCP lookup */
DNS_STREAM_STUB, /* Incoming DNS stub connection */
_DNS_STREAM_TYPE_MAX,
_DNS_STREAM_TYPE_INVALID = -EINVAL,
} DnsStreamType;
#define DNS_STREAM_WRITE_TLS_DATA 1
/* Streams are used by three subsystems:
*
* 1. The normal transaction logic when doing a DNS or LLMNR lookup via TCP
* 2. The LLMNR logic when accepting a TCP-based lookup
* 3. The DNS stub logic when accepting a TCP-based lookup
*/
struct DnsStream {
Manager *manager;
unsigned n_ref;
DnsStreamType type;
DnsProtocol protocol;
int fd;
union sockaddr_union peer;
socklen_t peer_salen;
union sockaddr_union local;
socklen_t local_salen;
int ifindex;
uint32_t ttl;
bool identified;
bool packet_received; /* At least one packet is received. Used by LLMNR. */
uint32_t requested_events;
/* only when using TCP fast open */
union sockaddr_union tfo_address;
socklen_t tfo_salen;
#if ENABLE_DNS_OVER_TLS
DnsTlsStreamData dnstls_data;
uint32_t dnstls_events;
#endif
sd_event_source *io_event_source;
sd_event_source *timeout_event_source;
be16_t write_size, read_size;
DnsPacket *write_packet, *read_packet;
size_t n_written, n_read;
OrderedSet *write_queue;
int (*on_packet)(DnsStream *s, DnsPacket *p);
int (*complete)(DnsStream *s, int error);
LIST_HEAD(DnsTransaction, transactions); /* when used by the transaction logic */
DnsServer *server; /* when used by the transaction logic */
Set *queries; /* when used by the DNS stub logic */
/* used when DNS-over-TLS is enabled */
bool encrypted:1;
DnsStubListenerExtra *stub_listener_extra;
LIST_FIELDS(DnsStream, streams);
};
int dns_stream_new(
Manager *m,
DnsStream **ret,
DnsStreamType type,
DnsProtocol protocol,
int fd,
const union sockaddr_union *tfo_address,
int (on_packet)(DnsStream*, DnsPacket*),
int (complete)(DnsStream*, int), /* optional */
usec_t connect_timeout_usec);
#if ENABLE_DNS_OVER_TLS
int dns_stream_connect_tls(DnsStream *s, void *tls_session);
#endif
DnsStream *dns_stream_unref(DnsStream *s);
DnsStream *dns_stream_ref(DnsStream *s);
DEFINE_TRIVIAL_CLEANUP_FUNC(DnsStream*, dns_stream_unref);
int dns_stream_write_packet(DnsStream *s, DnsPacket *p);
ssize_t dns_stream_writev(DnsStream *s, const struct iovec *iov, size_t iovcnt, int flags);
static inline bool DNS_STREAM_QUEUED(DnsStream *s) {
assert(s);
if (s->fd < 0) /* already stopped? */
return false;
return !!s->write_packet;
}
void dns_stream_detach(DnsStream *s);
| 4,176 | 31.379845 | 108 |
h
|
null |
systemd-main/src/resolve/resolved-dns-stub.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "hash-funcs.h"
typedef struct DnsStubListenerExtra DnsStubListenerExtra;
typedef enum DnsStubListenerMode {
DNS_STUB_LISTENER_NO,
DNS_STUB_LISTENER_UDP = 1 << 0,
DNS_STUB_LISTENER_TCP = 1 << 1,
DNS_STUB_LISTENER_YES = DNS_STUB_LISTENER_UDP | DNS_STUB_LISTENER_TCP,
_DNS_STUB_LISTENER_MODE_MAX,
_DNS_STUB_LISTENER_MODE_INVALID = -EINVAL,
} DnsStubListenerMode;
#include "resolved-manager.h"
struct DnsStubListenerExtra {
Manager *manager;
DnsStubListenerMode mode;
int family;
union in_addr_union address;
uint16_t port;
sd_event_source *udp_event_source;
sd_event_source *tcp_event_source;
Hashmap *queries_by_packet;
};
extern const struct hash_ops dns_stub_listener_extra_hash_ops;
int dns_stub_listener_extra_new(Manager *m, DnsStubListenerExtra **ret);
DnsStubListenerExtra *dns_stub_listener_extra_free(DnsStubListenerExtra *p);
static inline uint16_t dns_stub_listener_extra_port(DnsStubListenerExtra *p) {
assert(p);
return p->port > 0 ? p->port : 53;
}
void manager_dns_stub_stop(Manager *m);
int manager_dns_stub_start(Manager *m);
const char* dns_stub_listener_mode_to_string(DnsStubListenerMode p) _const_;
DnsStubListenerMode dns_stub_listener_mode_from_string(const char *s) _pure_;
| 1,409 | 27.77551 | 78 |
h
|
null |
systemd-main/src/resolve/resolved-dns-transaction.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-event.h"
#include "in-addr-util.h"
typedef struct DnsTransaction DnsTransaction;
typedef struct DnsTransactionFinder DnsTransactionFinder;
typedef enum DnsTransactionState DnsTransactionState;
typedef enum DnsTransactionSource DnsTransactionSource;
#include "resolved-dns-answer.h"
#include "resolved-dns-dnssec.h"
#include "resolved-dns-packet.h"
#include "resolved-dns-question.h"
#include "resolved-dns-server.h"
enum DnsTransactionState {
DNS_TRANSACTION_NULL,
DNS_TRANSACTION_PENDING,
DNS_TRANSACTION_VALIDATING,
DNS_TRANSACTION_RCODE_FAILURE,
DNS_TRANSACTION_SUCCESS,
DNS_TRANSACTION_NO_SERVERS,
DNS_TRANSACTION_TIMEOUT,
DNS_TRANSACTION_ATTEMPTS_MAX_REACHED,
DNS_TRANSACTION_INVALID_REPLY,
DNS_TRANSACTION_ERRNO,
DNS_TRANSACTION_ABORTED,
DNS_TRANSACTION_DNSSEC_FAILED,
DNS_TRANSACTION_NO_TRUST_ANCHOR,
DNS_TRANSACTION_RR_TYPE_UNSUPPORTED,
DNS_TRANSACTION_NETWORK_DOWN,
DNS_TRANSACTION_NOT_FOUND, /* like NXDOMAIN, but when LLMNR/TCP connections fail */
DNS_TRANSACTION_NO_SOURCE, /* All suitable DnsTransactionSource turned off */
DNS_TRANSACTION_STUB_LOOP,
_DNS_TRANSACTION_STATE_MAX,
_DNS_TRANSACTION_STATE_INVALID = -EINVAL,
};
#define DNS_TRANSACTION_IS_LIVE(state) IN_SET((state), DNS_TRANSACTION_NULL, DNS_TRANSACTION_PENDING, DNS_TRANSACTION_VALIDATING)
enum DnsTransactionSource {
DNS_TRANSACTION_NETWORK,
DNS_TRANSACTION_CACHE,
DNS_TRANSACTION_ZONE,
DNS_TRANSACTION_TRUST_ANCHOR,
_DNS_TRANSACTION_SOURCE_MAX,
_DNS_TRANSACTION_SOURCE_INVALID = -EINVAL,
};
struct DnsTransaction {
DnsScope *scope;
DnsResourceKey *key; /* For regular lookups the RR key to look for */
DnsPacket *bypass; /* For bypass lookups the full original request packet */
uint64_t query_flags;
DnsPacket *sent, *received;
DnsAnswer *answer;
int answer_rcode;
DnssecResult answer_dnssec_result;
DnsTransactionSource answer_source;
uint32_t answer_nsec_ttl;
int answer_errno; /* if state is DNS_TRANSACTION_ERRNO */
DnsTransactionState state;
/* SD_RESOLVED_AUTHENTICATED here indicates whether the primary answer is authenticated, i.e. whether
* the RRs from answer which directly match the question are authenticated, or, if there are none,
* whether the NODATA or NXDOMAIN case is. It says nothing about additional RRs listed in the answer,
* however they have their own DNS_ANSWER_AUTHORIZED FLAGS. Note that this bit is defined different
* than the AD bit in DNS packets, as that covers more than just the actual primary answer. */
uint64_t answer_query_flags;
/* Contains DNSKEY, DS, SOA RRs we already verified and need
* to authenticate this reply */
DnsAnswer *validated_keys;
usec_t start_usec;
usec_t next_attempt_after;
sd_event_source *timeout_event_source;
unsigned n_attempts;
/* UDP connection logic, if we need it */
int dns_udp_fd;
sd_event_source *dns_udp_event_source;
/* TCP connection logic, if we need it */
DnsStream *stream;
/* The active server */
DnsServer *server;
/* The features of the DNS server at time of transaction start */
DnsServerFeatureLevel current_feature_level;
/* If we got SERVFAIL back, we retry the lookup, using a lower feature level than we used before. */
DnsServerFeatureLevel clamp_feature_level_servfail;
uint16_t id;
bool tried_stream:1;
bool initial_jitter_scheduled:1;
bool initial_jitter_elapsed:1;
bool probing:1;
/* Query candidates this transaction is referenced by and that
* shall be notified about this specific transaction
* completing. */
Set *notify_query_candidates, *notify_query_candidates_done;
/* Zone items this transaction is referenced by and that shall
* be notified about completion. */
Set *notify_zone_items, *notify_zone_items_done;
/* Other transactions that this transactions is referenced by
* and that shall be notified about completion. This is used
* when transactions want to validate their RRsets, but need
* another DNSKEY or DS RR to do so. */
Set *notify_transactions, *notify_transactions_done;
/* The opposite direction: the transactions this transaction
* created in order to request DNSKEY or DS RRs. */
Set *dnssec_transactions;
unsigned n_picked_servers;
unsigned block_gc;
LIST_FIELDS(DnsTransaction, transactions_by_scope);
LIST_FIELDS(DnsTransaction, transactions_by_stream);
LIST_FIELDS(DnsTransaction, transactions_by_key);
/* Note: fields should be ordered to minimize alignment gaps. Use pahole! */
};
int dns_transaction_new(DnsTransaction **ret, DnsScope *s, DnsResourceKey *key, DnsPacket *bypass, uint64_t flags);
DnsTransaction* dns_transaction_free(DnsTransaction *t);
DnsTransaction* dns_transaction_gc(DnsTransaction *t);
DEFINE_TRIVIAL_CLEANUP_FUNC(DnsTransaction*, dns_transaction_gc);
int dns_transaction_go(DnsTransaction *t);
void dns_transaction_process_reply(DnsTransaction *t, DnsPacket *p, bool encrypted);
void dns_transaction_complete(DnsTransaction *t, DnsTransactionState state);
void dns_transaction_notify(DnsTransaction *t, DnsTransaction *source);
int dns_transaction_validate_dnssec(DnsTransaction *t);
int dns_transaction_request_dnssec_keys(DnsTransaction *t);
static inline DnsResourceKey *dns_transaction_key(DnsTransaction *t) {
assert(t);
/* Return the lookup key of this transaction. Either takes the lookup key from the bypass packet if
* we are a bypass transaction. Or take the configured key for regular transactions. */
if (t->key)
return t->key;
assert(t->bypass);
return dns_question_first_key(t->bypass->question);
}
static inline uint64_t dns_transaction_source_to_query_flags(DnsTransactionSource s) {
switch (s) {
case DNS_TRANSACTION_NETWORK:
return SD_RESOLVED_FROM_NETWORK;
case DNS_TRANSACTION_CACHE:
return SD_RESOLVED_FROM_CACHE;
case DNS_TRANSACTION_ZONE:
return SD_RESOLVED_FROM_ZONE;
case DNS_TRANSACTION_TRUST_ANCHOR:
return SD_RESOLVED_FROM_TRUST_ANCHOR;
default:
return 0;
}
}
const char* dns_transaction_state_to_string(DnsTransactionState p) _const_;
DnsTransactionState dns_transaction_state_from_string(const char *s) _pure_;
const char* dns_transaction_source_to_string(DnsTransactionSource p) _const_;
DnsTransactionSource dns_transaction_source_from_string(const char *s) _pure_;
/* LLMNR Jitter interval, see RFC 4795 Section 7 */
#define LLMNR_JITTER_INTERVAL_USEC (100 * USEC_PER_MSEC)
/* mDNS probing interval, see RFC 6762 Section 8.1 */
#define MDNS_PROBING_INTERVAL_USEC (250 * USEC_PER_MSEC)
/* Maximum attempts to send DNS requests, across all DNS servers */
#define DNS_TRANSACTION_ATTEMPTS_MAX 24
/* Maximum attempts to send LLMNR requests, see RFC 4795 Section 2.7 */
#define LLMNR_TRANSACTION_ATTEMPTS_MAX 3
/* Maximum attempts to send MDNS requests, see RFC 6762 Section 8.1 */
#define MDNS_TRANSACTION_ATTEMPTS_MAX 3
#define TRANSACTION_ATTEMPTS_MAX(p) ((p) == DNS_PROTOCOL_LLMNR ? \
LLMNR_TRANSACTION_ATTEMPTS_MAX : \
(p) == DNS_PROTOCOL_MDNS ? \
MDNS_TRANSACTION_ATTEMPTS_MAX : \
DNS_TRANSACTION_ATTEMPTS_MAX)
| 8,011 | 35.752294 | 129 |
h
|
null |
systemd-main/src/resolve/resolved-dns-trust-anchor.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
typedef struct DnsTrustAnchor DnsTrustAnchor;
#include "hashmap.h"
#include "resolved-dns-answer.h"
#include "resolved-dns-rr.h"
/* This contains a fixed database mapping domain names to DS or DNSKEY records. */
struct DnsTrustAnchor {
Hashmap *positive_by_key;
Set *negative_by_name;
Set *revoked_by_rr;
};
int dns_trust_anchor_load(DnsTrustAnchor *d);
void dns_trust_anchor_flush(DnsTrustAnchor *d);
int dns_trust_anchor_lookup_positive(DnsTrustAnchor *d, const DnsResourceKey* key, DnsAnswer **answer);
int dns_trust_anchor_lookup_negative(DnsTrustAnchor *d, const char *name);
int dns_trust_anchor_check_revoked(DnsTrustAnchor *d, DnsResourceRecord *dnskey, DnsAnswer *rrs);
int dns_trust_anchor_is_revoked(DnsTrustAnchor *d, DnsResourceRecord *rr);
| 847 | 31.615385 | 103 |
h
|
null |
systemd-main/src/resolve/resolved-dns-zone.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "hashmap.h"
typedef struct DnsZone {
Hashmap *by_key;
Hashmap *by_name;
} DnsZone;
typedef struct DnsZoneItem DnsZoneItem;
typedef enum DnsZoneItemState DnsZoneItemState;
#include "resolved-dns-answer.h"
#include "resolved-dns-question.h"
#include "resolved-dns-rr.h"
#include "resolved-dns-transaction.h"
/* RFC 4795 Section 2.8. suggests a TTL of 30s by default */
#define LLMNR_DEFAULT_TTL (30)
/* RFC 6762 Section 10. suggests a TTL of 120s by default */
#define MDNS_DEFAULT_TTL (120)
enum DnsZoneItemState {
DNS_ZONE_ITEM_PROBING,
DNS_ZONE_ITEM_ESTABLISHED,
DNS_ZONE_ITEM_VERIFYING,
DNS_ZONE_ITEM_WITHDRAWN,
};
struct DnsZoneItem {
DnsScope *scope;
DnsResourceRecord *rr;
DnsZoneItemState state;
unsigned block_ready;
bool probing_enabled;
LIST_FIELDS(DnsZoneItem, by_key);
LIST_FIELDS(DnsZoneItem, by_name);
DnsTransaction *probe_transaction;
};
void dns_zone_flush(DnsZone *z);
int dns_zone_put(DnsZone *z, DnsScope *s, DnsResourceRecord *rr, bool probe);
DnsZoneItem* dns_zone_get(DnsZone *z, DnsResourceRecord *rr);
void dns_zone_remove_rr(DnsZone *z, DnsResourceRecord *rr);
int dns_zone_remove_rrs_by_key(DnsZone *z, DnsResourceKey *key);
int dns_zone_lookup(DnsZone *z, DnsResourceKey *key, int ifindex, DnsAnswer **answer, DnsAnswer **soa, bool *tentative);
void dns_zone_item_conflict(DnsZoneItem *i);
void dns_zone_item_notify(DnsZoneItem *i);
int dns_zone_check_conflicts(DnsZone *zone, DnsResourceRecord *rr);
int dns_zone_verify_conflicts(DnsZone *zone, DnsResourceKey *key);
void dns_zone_verify_all(DnsZone *zone);
void dns_zone_item_probe_stop(DnsZoneItem *i);
void dns_zone_dump(DnsZone *zone, FILE *f);
bool dns_zone_is_empty(DnsZone *zone);
bool dns_zone_contains_name(DnsZone *z, const char *name);
| 1,929 | 26.571429 | 120 |
h
|
null |
systemd-main/src/resolve/resolved-dnssd.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "conf-files.h"
#include "conf-parser.h"
#include "constants.h"
#include "resolved-dnssd.h"
#include "resolved-dns-rr.h"
#include "resolved-manager.h"
#include "resolved-conf.h"
#include "specifier.h"
#include "strv.h"
#define DNSSD_SERVICE_DIRS ((const char* const*) CONF_PATHS_STRV("systemd/dnssd"))
DnssdTxtData *dnssd_txtdata_free(DnssdTxtData *txt_data) {
if (!txt_data)
return NULL;
dns_resource_record_unref(txt_data->rr);
dns_txt_item_free_all(txt_data->txts);
return mfree(txt_data);
}
DnssdTxtData *dnssd_txtdata_free_all(DnssdTxtData *txt_data) {
DnssdTxtData *next;
if (!txt_data)
return NULL;
next = txt_data->items_next;
dnssd_txtdata_free(txt_data);
return dnssd_txtdata_free_all(next);
}
DnssdService *dnssd_service_free(DnssdService *service) {
if (!service)
return NULL;
if (service->manager)
hashmap_remove(service->manager->dnssd_services, service->name);
dns_resource_record_unref(service->ptr_rr);
dns_resource_record_unref(service->srv_rr);
dnssd_txtdata_free_all(service->txt_data_items);
free(service->filename);
free(service->name);
free(service->type);
free(service->name_template);
return mfree(service);
}
static int dnssd_service_load(Manager *manager, const char *filename) {
_cleanup_(dnssd_service_freep) DnssdService *service = NULL;
_cleanup_(dnssd_txtdata_freep) DnssdTxtData *txt_data = NULL;
char *d;
const char *dropin_dirname;
int r;
assert(manager);
assert(filename);
service = new0(DnssdService, 1);
if (!service)
return log_oom();
service->filename = strdup(filename);
if (!service->filename)
return log_oom();
service->name = strdup(basename(filename));
if (!service->name)
return log_oom();
d = endswith(service->name, ".dnssd");
if (!d)
return -EINVAL;
assert(streq(d, ".dnssd"));
*d = '\0';
dropin_dirname = strjoina(service->name, ".dnssd.d");
r = config_parse_many(
STRV_MAKE_CONST(filename), DNSSD_SERVICE_DIRS, dropin_dirname, /* root = */ NULL,
"Service\0",
config_item_perf_lookup, resolved_dnssd_gperf_lookup,
CONFIG_PARSE_WARN,
service,
NULL,
NULL);
if (r < 0)
return r;
if (!service->name_template)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"%s doesn't define service instance name",
service->name);
if (!service->type)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"%s doesn't define service type",
service->name);
if (!service->txt_data_items) {
txt_data = new0(DnssdTxtData, 1);
if (!txt_data)
return log_oom();
r = dns_txt_item_new_empty(&txt_data->txts);
if (r < 0)
return r;
LIST_PREPEND(items, service->txt_data_items, txt_data);
TAKE_PTR(txt_data);
}
r = hashmap_ensure_put(&manager->dnssd_services, &string_hash_ops, service->name, service);
if (r < 0)
return r;
service->manager = manager;
r = dnssd_update_rrs(service);
if (r < 0)
return r;
TAKE_PTR(service);
return 0;
}
static int specifier_dnssd_hostname(char specifier, const void *data, const char *root, const void *userdata, char **ret) {
const Manager *m = ASSERT_PTR(userdata);
char *n;
assert(m->llmnr_hostname);
n = strdup(m->llmnr_hostname);
if (!n)
return -ENOMEM;
*ret = n;
return 0;
}
int dnssd_render_instance_name(Manager *m, DnssdService *s, char **ret) {
static const Specifier specifier_table[] = {
{ 'a', specifier_architecture, NULL },
{ 'b', specifier_boot_id, NULL },
{ 'B', specifier_os_build_id, NULL },
{ 'H', specifier_dnssd_hostname, NULL },
{ 'm', specifier_machine_id, NULL },
{ 'o', specifier_os_id, NULL },
{ 'v', specifier_kernel_release, NULL },
{ 'w', specifier_os_version_id, NULL },
{ 'W', specifier_os_variant_id, NULL },
{}
};
_cleanup_free_ char *name = NULL;
int r;
assert(m);
assert(s);
assert(s->name_template);
r = specifier_printf(s->name_template, DNS_LABEL_MAX, specifier_table, NULL, m, &name);
if (r < 0)
return log_debug_errno(r, "Failed to replace specifiers: %m");
if (!dns_service_name_is_valid(name))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"Service instance name '%s' is invalid.",
name);
if (ret)
*ret = TAKE_PTR(name);
return 0;
}
int dnssd_load(Manager *manager) {
_cleanup_strv_free_ char **files = NULL;
int r;
assert(manager);
if (manager->mdns_support != RESOLVE_SUPPORT_YES)
return 0;
r = conf_files_list_strv(&files, ".dnssd", NULL, 0, DNSSD_SERVICE_DIRS);
if (r < 0)
return log_error_errno(r, "Failed to enumerate .dnssd files: %m");
STRV_FOREACH_BACKWARDS(f, files) {
r = dnssd_service_load(manager, *f);
if (r < 0)
log_warning_errno(r, "Failed to load '%s': %m", *f);
}
return 0;
}
int dnssd_update_rrs(DnssdService *s) {
_cleanup_free_ char *n = NULL, *service_name = NULL, *full_name = NULL;
int r;
assert(s);
assert(s->txt_data_items);
assert(s->manager);
s->ptr_rr = dns_resource_record_unref(s->ptr_rr);
s->srv_rr = dns_resource_record_unref(s->srv_rr);
LIST_FOREACH(items, txt_data, s->txt_data_items)
txt_data->rr = dns_resource_record_unref(txt_data->rr);
r = dnssd_render_instance_name(s->manager, s, &n);
if (r < 0)
return r;
r = dns_name_concat(s->type, "local", 0, &service_name);
if (r < 0)
return r;
r = dns_name_concat(n, service_name, 0, &full_name);
if (r < 0)
return r;
LIST_FOREACH(items, txt_data, s->txt_data_items) {
txt_data->rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_TXT,
full_name);
if (!txt_data->rr)
goto oom;
txt_data->rr->ttl = MDNS_DEFAULT_TTL;
txt_data->rr->txt.items = dns_txt_item_copy(txt_data->txts);
if (!txt_data->rr->txt.items)
goto oom;
}
s->ptr_rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_PTR,
service_name);
if (!s->ptr_rr)
goto oom;
s->ptr_rr->ttl = MDNS_DEFAULT_TTL;
s->ptr_rr->ptr.name = strdup(full_name);
if (!s->ptr_rr->ptr.name)
goto oom;
s->srv_rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_SRV,
full_name);
if (!s->srv_rr)
goto oom;
s->srv_rr->ttl = MDNS_DEFAULT_TTL;
s->srv_rr->srv.priority = s->priority;
s->srv_rr->srv.weight = s->weight;
s->srv_rr->srv.port = s->port;
s->srv_rr->srv.name = strdup(s->manager->mdns_hostname);
if (!s->srv_rr->srv.name)
goto oom;
return 0;
oom:
LIST_FOREACH(items, txt_data, s->txt_data_items)
txt_data->rr = dns_resource_record_unref(txt_data->rr);
s->ptr_rr = dns_resource_record_unref(s->ptr_rr);
s->srv_rr = dns_resource_record_unref(s->srv_rr);
return -ENOMEM;
}
int dnssd_txt_item_new_from_string(const char *key, const char *value, DnsTxtItem **ret_item) {
size_t length;
DnsTxtItem *i;
length = strlen(key);
if (!isempty(value))
length += strlen(value) + 1; /* length of value plus '=' */
i = malloc0(offsetof(DnsTxtItem, data) + length + 1); /* for safety reasons we add an extra NUL byte */
if (!i)
return -ENOMEM;
memcpy(i->data, key, strlen(key));
if (!isempty(value)) {
memcpy(i->data + strlen(key), "=", 1);
memcpy(i->data + strlen(key) + 1, value, strlen(value));
}
i->length = length;
*ret_item = TAKE_PTR(i);
return 0;
}
int dnssd_txt_item_new_from_data(const char *key, const void *data, const size_t size, DnsTxtItem **ret_item) {
size_t length;
DnsTxtItem *i;
length = strlen(key);
if (size > 0)
length += size + 1; /* size of date plus '=' */
i = malloc0(offsetof(DnsTxtItem, data) + length + 1); /* for safety reasons we add an extra NUL byte */
if (!i)
return -ENOMEM;
memcpy(i->data, key, strlen(key));
if (size > 0) {
memcpy(i->data + strlen(key), "=", 1);
memcpy(i->data + strlen(key) + 1, data, size);
}
i->length = length;
*ret_item = TAKE_PTR(i);
return 0;
}
int dnssd_signal_conflict(Manager *manager, const char *name) {
DnssdService *s;
int r;
if (sd_bus_is_ready(manager->bus) <= 0)
return 0;
HASHMAP_FOREACH(s, manager->dnssd_services) {
if (s->withdrawn)
continue;
if (dns_name_equal(dns_resource_key_name(s->srv_rr->key), name)) {
_cleanup_free_ char *path = NULL;
s->withdrawn = true;
r = sd_bus_path_encode("/org/freedesktop/resolve1/dnssd", s->name, &path);
if (r < 0)
return log_error_errno(r, "Can't get D-BUS object path: %m");
r = sd_bus_emit_signal(manager->bus,
path,
"org.freedesktop.resolve1.DnssdService",
"Conflicted",
NULL);
if (r < 0)
return log_error_errno(r, "Cannot emit signal: %m");
break;
}
}
return 0;
}
| 11,328 | 30.209366 | 123 |
c
|
null |
systemd-main/src/resolve/resolved-dnssd.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "list.h"
typedef struct DnssdService DnssdService;
typedef struct DnssdTxtData DnssdTxtData;
typedef struct Manager Manager;
typedef struct DnsResourceRecord DnsResourceRecord;
typedef struct DnsTxtItem DnsTxtItem;
enum {
DNS_TXT_ITEM_TEXT,
DNS_TXT_ITEM_DATA,
};
struct DnssdTxtData {
DnsResourceRecord *rr;
LIST_HEAD(DnsTxtItem, txts);
LIST_FIELDS(DnssdTxtData, items);
};
struct DnssdService {
char *filename;
char *name;
char *name_template;
char *type;
uint16_t port;
uint16_t priority;
uint16_t weight;
DnsResourceRecord *ptr_rr;
DnsResourceRecord *srv_rr;
/* Section 6.8 of RFC 6763 allows having service
* instances with multiple TXT resource records. */
LIST_HEAD(DnssdTxtData, txt_data_items);
Manager *manager;
bool withdrawn:1;
uid_t originator;
};
DnssdService *dnssd_service_free(DnssdService *service);
DnssdTxtData *dnssd_txtdata_free(DnssdTxtData *txt_data);
DnssdTxtData *dnssd_txtdata_free_all(DnssdTxtData *txt_data);
DEFINE_TRIVIAL_CLEANUP_FUNC(DnssdService*, dnssd_service_free);
DEFINE_TRIVIAL_CLEANUP_FUNC(DnssdTxtData*, dnssd_txtdata_free);
int dnssd_render_instance_name(Manager *m, DnssdService *s, char **ret);
int dnssd_load(Manager *manager);
int dnssd_txt_item_new_from_string(const char *key, const char *value, DnsTxtItem **ret_item);
int dnssd_txt_item_new_from_data(const char *key, const void *value, const size_t size, DnsTxtItem **ret_item);
int dnssd_update_rrs(DnssdService *s);
int dnssd_signal_conflict(Manager *manager, const char *name);
| 1,729 | 26.903226 | 111 |
h
|
null |
systemd-main/src/resolve/resolved-dnstls-gnutls.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#if !ENABLE_DNS_OVER_TLS || !DNS_OVER_TLS_USE_GNUTLS
#error This source file requires DNS-over-TLS to be enabled and GnuTLS to be available.
#endif
#include <gnutls/socket.h>
#include "io-util.h"
#include "resolved-dns-stream.h"
#include "resolved-dnstls.h"
#include "resolved-manager.h"
#define TLS_PROTOCOL_PRIORITY "NORMAL:-VERS-ALL:+VERS-TLS1.3:+VERS-TLS1.2"
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(gnutls_session_t, gnutls_deinit, NULL);
static ssize_t dnstls_stream_vec_push(gnutls_transport_ptr_t p, const giovec_t *iov, int iovcnt) {
int r;
assert(p);
r = dns_stream_writev((DnsStream*) p, (const struct iovec*) iov, iovcnt, DNS_STREAM_WRITE_TLS_DATA);
if (r < 0) {
errno = -r;
return -1;
}
return r;
}
int dnstls_stream_connect_tls(DnsStream *stream, DnsServer *server) {
_cleanup_(gnutls_deinitp) gnutls_session_t gs = NULL;
int r;
assert(stream);
assert(server);
r = gnutls_init(&gs, GNUTLS_CLIENT | GNUTLS_ENABLE_FALSE_START | GNUTLS_NONBLOCK);
if (r < 0)
return r;
/* As DNS-over-TLS is a recent protocol, older TLS versions can be disabled */
r = gnutls_priority_set_direct(gs, TLS_PROTOCOL_PRIORITY, NULL);
if (r < 0)
return r;
r = gnutls_credentials_set(gs, GNUTLS_CRD_CERTIFICATE, stream->manager->dnstls_data.cert_cred);
if (r < 0)
return r;
if (server->dnstls_data.session_data.size > 0) {
gnutls_session_set_data(gs, server->dnstls_data.session_data.data, server->dnstls_data.session_data.size);
// Clear old session ticket
gnutls_free(server->dnstls_data.session_data.data);
server->dnstls_data.session_data.data = NULL;
server->dnstls_data.session_data.size = 0;
}
if (server->manager->dns_over_tls_mode == DNS_OVER_TLS_YES) {
if (server->server_name)
gnutls_session_set_verify_cert(gs, server->server_name, 0);
else {
stream->dnstls_data.validation.type = GNUTLS_DT_IP_ADDRESS;
if (server->family == AF_INET) {
stream->dnstls_data.validation.data = (unsigned char*) &server->address.in.s_addr;
stream->dnstls_data.validation.size = 4;
} else {
stream->dnstls_data.validation.data = server->address.in6.s6_addr;
stream->dnstls_data.validation.size = 16;
}
gnutls_session_set_verify_cert2(gs, &stream->dnstls_data.validation, 1, 0);
}
}
if (server->server_name) {
r = gnutls_server_name_set(gs, GNUTLS_NAME_DNS, server->server_name, strlen(server->server_name));
if (r < 0)
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set server name: %s", gnutls_strerror(r));
}
gnutls_handshake_set_timeout(gs, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
gnutls_transport_set_ptr2(gs, (gnutls_transport_ptr_t) (long) stream->fd, stream);
gnutls_transport_set_vec_push_function(gs, &dnstls_stream_vec_push);
stream->encrypted = true;
stream->dnstls_data.handshake = gnutls_handshake(gs);
if (stream->dnstls_data.handshake < 0 && gnutls_error_is_fatal(stream->dnstls_data.handshake))
return -ECONNREFUSED;
stream->dnstls_data.session = TAKE_PTR(gs);
return 0;
}
void dnstls_stream_free(DnsStream *stream) {
assert(stream);
assert(stream->encrypted);
if (stream->dnstls_data.session)
gnutls_deinit(stream->dnstls_data.session);
}
int dnstls_stream_on_io(DnsStream *stream, uint32_t revents) {
int r;
assert(stream);
assert(stream->encrypted);
assert(stream->dnstls_data.session);
if (stream->dnstls_data.shutdown) {
r = gnutls_bye(stream->dnstls_data.session, GNUTLS_SHUT_RDWR);
if (r == GNUTLS_E_AGAIN) {
stream->dnstls_events = gnutls_record_get_direction(stream->dnstls_data.session) == 1 ? EPOLLOUT : EPOLLIN;
return -EAGAIN;
} else if (r < 0)
log_debug("Failed to invoke gnutls_bye: %s", gnutls_strerror(r));
stream->dnstls_events = 0;
stream->dnstls_data.shutdown = false;
dns_stream_unref(stream);
return DNSTLS_STREAM_CLOSED;
} else if (stream->dnstls_data.handshake < 0) {
stream->dnstls_data.handshake = gnutls_handshake(stream->dnstls_data.session);
if (stream->dnstls_data.handshake == GNUTLS_E_AGAIN) {
stream->dnstls_events = gnutls_record_get_direction(stream->dnstls_data.session) == 1 ? EPOLLOUT : EPOLLIN;
return -EAGAIN;
} else if (stream->dnstls_data.handshake < 0) {
log_debug("Failed to invoke gnutls_handshake: %s", gnutls_strerror(stream->dnstls_data.handshake));
if (gnutls_error_is_fatal(stream->dnstls_data.handshake))
return -ECONNREFUSED;
}
stream->dnstls_events = 0;
}
return 0;
}
int dnstls_stream_shutdown(DnsStream *stream, int error) {
int r;
assert(stream);
assert(stream->encrypted);
assert(stream->dnstls_data.session);
/* Store TLS Ticket for faster successive TLS handshakes */
if (stream->server && stream->server->dnstls_data.session_data.size == 0 && stream->dnstls_data.handshake == GNUTLS_E_SUCCESS)
gnutls_session_get_data2(stream->dnstls_data.session, &stream->server->dnstls_data.session_data);
if (IN_SET(error, ETIMEDOUT, 0)) {
r = gnutls_bye(stream->dnstls_data.session, GNUTLS_SHUT_RDWR);
if (r == GNUTLS_E_AGAIN) {
if (!stream->dnstls_data.shutdown) {
stream->dnstls_data.shutdown = true;
dns_stream_ref(stream);
return -EAGAIN;
}
} else if (r < 0)
log_debug("Failed to invoke gnutls_bye: %s", gnutls_strerror(r));
}
return 0;
}
ssize_t dnstls_stream_writev(DnsStream *stream, const struct iovec *iov, size_t iovcnt) {
ssize_t ss;
assert(stream);
assert(stream->encrypted);
assert(stream->dnstls_data.session);
assert(iov);
assert(IOVEC_TOTAL_SIZE(iov, iovcnt) > 0);
gnutls_record_cork(stream->dnstls_data.session);
for (size_t i = 0; i < iovcnt; i++) {
ss = gnutls_record_send(
stream->dnstls_data.session,
iov[i].iov_base, iov[i].iov_len);
if (ss < 0)
break;
}
ss = gnutls_record_uncork(stream->dnstls_data.session, 0);
if (ss < 0)
switch (ss) {
case GNUTLS_E_INTERRUPTED:
return -EINTR;
case GNUTLS_E_AGAIN:
return -EAGAIN;
default:
return log_debug_errno(SYNTHETIC_ERRNO(EPIPE),
"Failed to invoke gnutls_record_send: %s",
gnutls_strerror(ss));
}
return ss;
}
ssize_t dnstls_stream_read(DnsStream *stream, void *buf, size_t count) {
ssize_t ss;
assert(stream);
assert(stream->encrypted);
assert(stream->dnstls_data.session);
assert(buf);
ss = gnutls_record_recv(stream->dnstls_data.session, buf, count);
if (ss < 0)
switch (ss) {
case GNUTLS_E_INTERRUPTED:
return -EINTR;
case GNUTLS_E_AGAIN:
return -EAGAIN;
default:
return log_debug_errno(SYNTHETIC_ERRNO(EPIPE),
"Failed to invoke gnutls_record_recv: %s",
gnutls_strerror(ss));
}
return ss;
}
void dnstls_server_free(DnsServer *server) {
assert(server);
if (server->dnstls_data.session_data.data)
gnutls_free(server->dnstls_data.session_data.data);
}
int dnstls_manager_init(Manager *manager) {
int r;
assert(manager);
r = gnutls_certificate_allocate_credentials(&manager->dnstls_data.cert_cred);
if (r < 0)
return -ENOMEM;
r = gnutls_certificate_set_x509_system_trust(manager->dnstls_data.cert_cred);
if (r < 0)
log_warning("Failed to load system trust store: %s", gnutls_strerror(r));
return 0;
}
void dnstls_manager_free(Manager *manager) {
assert(manager);
if (manager->dnstls_data.cert_cred)
gnutls_certificate_free_credentials(manager->dnstls_data.cert_cred);
}
| 9,487 | 36.354331 | 134 |
c
|
null |
systemd-main/src/resolve/resolved-dnstls-gnutls.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if !ENABLE_DNS_OVER_TLS || !DNS_OVER_TLS_USE_GNUTLS
#error This source file requires DNS-over-TLS to be enabled and GnuTLS to be available.
#endif
#include <gnutls/gnutls.h>
#include <stdbool.h>
struct DnsTlsManagerData {
gnutls_certificate_credentials_t cert_cred;
};
struct DnsTlsServerData {
gnutls_datum_t session_data;
};
struct DnsTlsStreamData {
gnutls_session_t session;
gnutls_typed_vdata_st validation;
int handshake;
bool shutdown;
};
| 562 | 21.52 | 87 |
h
|
null |
systemd-main/src/resolve/resolved-dnstls.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if ENABLE_DNS_OVER_TLS
#include <stdint.h>
#include <sys/uio.h>
typedef struct DnsServer DnsServer;
typedef struct DnsStream DnsStream;
typedef struct DnsTlsManagerData DnsTlsManagerData;
typedef struct DnsTlsServerData DnsTlsServerData;
typedef struct DnsTlsStreamData DnsTlsStreamData;
typedef struct Manager Manager;
#if DNS_OVER_TLS_USE_GNUTLS
#include "resolved-dnstls-gnutls.h"
#elif DNS_OVER_TLS_USE_OPENSSL
#include "resolved-dnstls-openssl.h"
#else
#error Unknown dependency for supporting DNS-over-TLS
#endif
#define DNSTLS_STREAM_CLOSED 1
int dnstls_stream_connect_tls(DnsStream *stream, DnsServer *server);
void dnstls_stream_free(DnsStream *stream);
int dnstls_stream_on_io(DnsStream *stream, uint32_t revents);
int dnstls_stream_shutdown(DnsStream *stream, int error);
ssize_t dnstls_stream_writev(DnsStream *stream, const struct iovec *iov, size_t iovcnt);
ssize_t dnstls_stream_read(DnsStream *stream, void *buf, size_t count);
void dnstls_server_free(DnsServer *server);
int dnstls_manager_init(Manager *manager);
void dnstls_manager_free(Manager *manager);
#endif /* ENABLE_DNS_OVER_TLS */
| 1,180 | 29.282051 | 88 |
h
|
null |
systemd-main/src/resolve/resolved-etc-hosts.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "resolved-manager.h"
#include "resolved-dns-question.h"
#include "resolved-dns-answer.h"
typedef struct EtcHostsItemByAddress {
struct in_addr_data address;
Set *names;
const char *canonical_name;
} EtcHostsItemByAddress;
typedef struct EtcHostsItemByName {
char *name;
Set *addresses;
} EtcHostsItemByName;
int etc_hosts_parse(EtcHosts *hosts, FILE *f);
void etc_hosts_clear(EtcHosts *hosts);
void manager_etc_hosts_flush(Manager *m);
int manager_etc_hosts_lookup(Manager *m, DnsQuestion* q, DnsAnswer **answer);
| 630 | 25.291667 | 77 |
h
|
null |
systemd-main/src/resolve/resolved-link-bus.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "bus-util.h"
#include "resolved-link.h"
extern const BusObjectImplementation link_object;
char *link_bus_path(const Link *link);
int bus_link_method_set_dns_servers(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_set_dns_servers_ex(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_set_domains(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_set_default_route(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_set_llmnr(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_set_mdns(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_set_dns_over_tls(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_set_dnssec(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_set_dnssec_negative_trust_anchors(sd_bus_message *message, void *userdata, sd_bus_error *error);
int bus_link_method_revert(sd_bus_message *message, void *userdata, sd_bus_error *error);
| 1,208 | 51.565217 | 116 |
h
|
null |
systemd-main/src/resolve/resolved-link.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/stat.h>
#include "sd-netlink.h"
#include "in-addr-util.h"
#include "network-util.h"
#include "ratelimit.h"
#include "resolve-util.h"
typedef struct Link Link;
typedef struct LinkAddress LinkAddress;
#include "resolved-dns-rr.h"
#include "resolved-dns-scope.h"
#include "resolved-dns-search-domain.h"
#include "resolved-dns-server.h"
#define LINK_SEARCH_DOMAINS_MAX 256
#define LINK_DNS_SERVERS_MAX 256
struct LinkAddress {
Link *link;
int family;
union in_addr_union in_addr;
union in_addr_union in_addr_broadcast;
unsigned char prefixlen;
unsigned char flags, scope;
DnsResourceRecord *llmnr_address_rr;
DnsResourceRecord *llmnr_ptr_rr;
DnsResourceRecord *mdns_address_rr;
DnsResourceRecord *mdns_ptr_rr;
LIST_FIELDS(LinkAddress, addresses);
};
struct Link {
Manager *manager;
int ifindex;
unsigned flags;
LIST_HEAD(LinkAddress, addresses);
unsigned n_addresses;
LIST_HEAD(DnsServer, dns_servers);
DnsServer *current_dns_server;
unsigned n_dns_servers;
LIST_HEAD(DnsSearchDomain, search_domains);
unsigned n_search_domains;
int default_route;
ResolveSupport llmnr_support;
ResolveSupport mdns_support;
DnsOverTlsMode dns_over_tls_mode;
DnssecMode dnssec_mode;
Set *dnssec_negative_trust_anchors;
DnsScope *unicast_scope;
DnsScope *llmnr_ipv4_scope;
DnsScope *llmnr_ipv6_scope;
DnsScope *mdns_ipv4_scope;
DnsScope *mdns_ipv6_scope;
struct stat networkd_state_file_stat;
LinkOperationalState networkd_operstate;
bool is_managed;
char *ifname;
uint32_t mtu;
uint8_t operstate;
bool loaded;
char *state_file;
bool unicast_relevant;
};
int link_new(Manager *m, Link **ret, int ifindex);
Link *link_free(Link *l);
int link_process_rtnl(Link *l, sd_netlink_message *m);
int link_update(Link *l);
bool link_relevant(Link *l, int family, bool local_multicast);
LinkAddress* link_find_address(Link *l, int family, const union in_addr_union *in_addr);
void link_add_rrs(Link *l, bool force_remove);
void link_flush_settings(Link *l);
void link_set_dnssec_mode(Link *l, DnssecMode mode);
void link_set_dns_over_tls_mode(Link *l, DnsOverTlsMode mode);
void link_allocate_scopes(Link *l);
DnsServer* link_set_dns_server(Link *l, DnsServer *s);
DnsServer* link_get_dns_server(Link *l);
void link_next_dns_server(Link *l, DnsServer *if_current);
DnssecMode link_get_dnssec_mode(Link *l);
bool link_dnssec_supported(Link *l);
DnsOverTlsMode link_get_dns_over_tls_mode(Link *l);
ResolveSupport link_get_llmnr_support(Link *link);
ResolveSupport link_get_mdns_support(Link *link);
int link_save_user(Link *l);
int link_load_user(Link *l);
void link_remove_user(Link *l);
int link_address_new(Link *l,
LinkAddress **ret,
int family,
const union in_addr_union *in_addr,
const union in_addr_union *in_addr_broadcast);
LinkAddress *link_address_free(LinkAddress *a);
int link_address_update_rtnl(LinkAddress *a, sd_netlink_message *m);
bool link_address_relevant(LinkAddress *l, bool local_multicast);
void link_address_add_rrs(LinkAddress *a, bool force_remove);
bool link_negative_trust_anchor_lookup(Link *l, const char *name);
DEFINE_TRIVIAL_CLEANUP_FUNC(Link*, link_free);
| 3,557 | 26.796875 | 88 |
h
|
null |
systemd-main/src/resolve/resolved-resolv-conf.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "resolved-manager.h"
int manager_check_resolv_conf(const Manager *m);
int manager_read_resolv_conf(Manager *m);
int manager_write_resolv_conf(Manager *m);
typedef enum ResolvConfMode {
RESOLV_CONF_UPLINK,
RESOLV_CONF_STUB,
RESOLV_CONF_STATIC,
RESOLV_CONF_FOREIGN,
RESOLV_CONF_MISSING,
_RESOLV_CONF_MODE_MAX,
_RESOLV_CONF_MODE_INVALID = -EINVAL,
} ResolvConfMode;
int resolv_conf_mode(void);
const char* resolv_conf_mode_to_string(ResolvConfMode m) _const_;
ResolvConfMode resolv_conf_mode_from_string(const char *s) _pure_;
| 656 | 26.375 | 66 |
h
|
null |
systemd-main/src/resolve/resolved-socket-graveyard.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "resolved-socket-graveyard.h"
#define SOCKET_GRAVEYARD_USEC (5 * USEC_PER_SEC)
#define SOCKET_GRAVEYARD_MAX 100
/* This implements a socket "graveyard" for UDP sockets. If a socket fd is added to the graveyard it is kept
* open for a couple of more seconds, expecting one reply. Once the reply is received the fd is closed
* immediately, or if none is received it is closed after the timeout. Why all this? So that if we contact a
* DNS server, and it doesn't reply instantly, and we lose interest in the response and thus close the fd, we
* don't end up sending back an ICMP error once the server responds but we aren't listening anymore. (See
* https://github.com/systemd/systemd/issues/17421 for further information.)
*
* Note that we don't allocate any timer event source to clear up the graveyard once the socket's timeout is
* reached. Instead we operate lazily: we close old entries when adding a new fd to the graveyard, or
* whenever any code runs manager_socket_graveyard_process() — which the DNS transaction code does right
* before allocating a new UDP socket. */
static SocketGraveyard* socket_graveyard_free(SocketGraveyard *g) {
if (!g)
return NULL;
if (g->manager) {
assert(g->manager->n_socket_graveyard > 0);
g->manager->n_socket_graveyard--;
if (g->manager->socket_graveyard_oldest == g)
g->manager->socket_graveyard_oldest = g->graveyard_prev;
LIST_REMOVE(graveyard, g->manager->socket_graveyard, g);
assert((g->manager->n_socket_graveyard > 0) == !!g->manager->socket_graveyard);
assert((g->manager->n_socket_graveyard > 0) == !!g->manager->socket_graveyard_oldest);
}
if (g->io_event_source) {
log_debug("Closing graveyard socket fd %i", sd_event_source_get_io_fd(g->io_event_source));
sd_event_source_disable_unref(g->io_event_source);
}
return mfree(g);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(SocketGraveyard*, socket_graveyard_free);
void manager_socket_graveyard_process(Manager *m) {
usec_t n = USEC_INFINITY;
assert(m);
while (m->socket_graveyard_oldest) {
SocketGraveyard *g = m->socket_graveyard_oldest;
if (n == USEC_INFINITY)
assert_se(sd_event_now(m->event, CLOCK_BOOTTIME, &n) >= 0);
if (g->deadline > n)
break;
socket_graveyard_free(g);
}
}
void manager_socket_graveyard_clear(Manager *m) {
assert(m);
while (m->socket_graveyard)
socket_graveyard_free(m->socket_graveyard);
}
static int on_io_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
SocketGraveyard *g = ASSERT_PTR(userdata);
/* An IO event happened on the graveyard fd. We don't actually care which event that is, and we don't
* read any incoming packet off the socket. We just close the fd, that's enough to not trigger the
* ICMP unreachable port event */
socket_graveyard_free(g);
return 0;
}
static void manager_socket_graveyard_make_room(Manager *m) {
assert(m);
while (m->n_socket_graveyard >= SOCKET_GRAVEYARD_MAX)
socket_graveyard_free(m->socket_graveyard_oldest);
}
int manager_add_socket_to_graveyard(Manager *m, int fd) {
_cleanup_(socket_graveyard_freep) SocketGraveyard *g = NULL;
int r;
assert(m);
assert(fd >= 0);
manager_socket_graveyard_process(m);
manager_socket_graveyard_make_room(m);
g = new(SocketGraveyard, 1);
if (!g)
return log_oom();
*g = (SocketGraveyard) {
.manager = m,
};
LIST_PREPEND(graveyard, m->socket_graveyard, g);
if (!m->socket_graveyard_oldest)
m->socket_graveyard_oldest = g;
m->n_socket_graveyard++;
assert_se(sd_event_now(m->event, CLOCK_BOOTTIME, &g->deadline) >= 0);
g->deadline += SOCKET_GRAVEYARD_USEC;
r = sd_event_add_io(m->event, &g->io_event_source, fd, EPOLLIN, on_io_event, g);
if (r < 0)
return log_error_errno(r, "Failed to create graveyard IO source: %m");
r = sd_event_source_set_io_fd_own(g->io_event_source, true);
if (r < 0)
return log_error_errno(r, "Failed to enable graveyard IO source fd ownership: %m");
(void) sd_event_source_set_description(g->io_event_source, "graveyard");
log_debug("Added socket %i to graveyard", fd);
TAKE_PTR(g);
return 0;
}
| 4,764 | 35.098485 | 109 |
c
|
null |
systemd-main/src/resolve/resolved-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "dns-def.h"
#include "dns-domain.h"
#include "hostname-util.h"
#include "idn-util.h"
#include "resolved-util.h"
#include "utf8.h"
int resolve_system_hostname(char **full_hostname, char **first_label) {
_cleanup_free_ char *h = NULL, *n = NULL;
#if HAVE_LIBIDN2
_cleanup_free_ char *utf8 = NULL;
#elif HAVE_LIBIDN
int k;
#endif
char label[DNS_LABEL_MAX];
const char *p, *decoded;
int r;
/* Return the full hostname in *full_hostname, if nonnull.
*
* Extract and normalize the first label of the locally configured hostname, check it's not
* "localhost", and return it in *first_label, if nonnull. */
r = gethostname_strict(&h);
if (r < 0)
return log_debug_errno(r, "Can't determine system hostname: %m");
p = h;
r = dns_label_unescape(&p, label, sizeof label, 0);
if (r < 0)
return log_debug_errno(r, "Failed to unescape hostname: %m");
if (r == 0)
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"Couldn't find a single label in hostname.");
#if HAVE_LIBIDN || HAVE_LIBIDN2
r = dlopen_idn();
if (r < 0) {
log_debug_errno(r, "Failed to initialize IDN support, ignoring: %m");
decoded = label; /* no decoding */
} else
#endif
{
#if HAVE_LIBIDN2
r = sym_idn2_to_unicode_8z8z(label, &utf8, 0);
if (r != IDN2_OK)
return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
"Failed to undo IDNA: %s", sym_idn2_strerror(r));
assert(utf8_is_valid(utf8));
r = strlen(utf8);
decoded = utf8;
#elif HAVE_LIBIDN
k = dns_label_undo_idna(label, r, label, sizeof label);
if (k < 0)
return log_debug_errno(k, "Failed to undo IDNA: %m");
if (k > 0)
r = k;
if (!utf8_is_valid(label))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"System hostname is not UTF-8 clean.");
decoded = label;
#else
decoded = label; /* no decoding */
#endif
}
r = dns_label_escape_new(decoded, r, &n);
if (r < 0)
return log_debug_errno(r, "Failed to escape hostname: %m");
if (is_localhost(n))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"System hostname is 'localhost', ignoring.");
if (full_hostname)
*full_hostname = TAKE_PTR(h);
if (first_label)
*first_label = TAKE_PTR(n);
return 0;
}
| 2,919 | 33.352941 | 99 |
c
|
null |
systemd-main/src/resolve/resolved.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "sd-daemon.h"
#include "sd-event.h"
#include "bus-log-control-api.h"
#include "capability-util.h"
#include "daemon-util.h"
#include "main-func.h"
#include "mkdir-label.h"
#include "resolved-bus.h"
#include "resolved-conf.h"
#include "resolved-manager.h"
#include "resolved-resolv-conf.h"
#include "selinux-util.h"
#include "service-util.h"
#include "signal-util.h"
#include "user-util.h"
static int run(int argc, char *argv[]) {
_cleanup_(manager_freep) Manager *m = NULL;
_unused_ _cleanup_(notify_on_cleanup) const char *notify_stop = NULL;
int r;
log_setup();
r = service_parse_argv("systemd-resolved.service",
"Provide name resolution with caching using DNS, mDNS, LLMNR.",
BUS_IMPLEMENTATIONS(&manager_object,
&log_control_object),
argc, argv);
if (r <= 0)
return r;
umask(0022);
r = mac_init();
if (r < 0)
return r;
/* Drop privileges, but only if we have been started as root. If we are not running as root we assume most
* privileges are already dropped and we can't create our directory. */
if (getuid() == 0) {
const char *user = "systemd-resolve";
uid_t uid;
gid_t gid;
r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
if (r < 0)
return log_error_errno(r, "Cannot resolve user name %s: %m", user);
/* As we're root, we can create the directory where resolv.conf will live */
r = mkdir_safe_label("/run/systemd/resolve", 0755, uid, gid, MKDIR_WARN_MODE);
if (r < 0)
return log_error_errno(r, "Could not create runtime directory: %m");
/* Drop privileges, but keep three caps. Note that we drop two of those too, later on (see below) */
r = drop_privileges(uid, gid,
(UINT64_C(1) << CAP_NET_RAW)| /* needed for SO_BINDTODEVICE */
(UINT64_C(1) << CAP_NET_BIND_SERVICE)| /* needed to bind on port 53 */
(UINT64_C(1) << CAP_SETPCAP) /* needed in order to drop the caps later */);
if (r < 0)
return log_error_errno(r, "Failed to drop privileges: %m");
}
assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, SIGUSR1, SIGUSR2, SIGRTMIN+1, SIGRTMIN+18, -1) >= 0);
r = manager_new(&m);
if (r < 0)
return log_error_errno(r, "Could not create manager: %m");
r = manager_start(m);
if (r < 0)
return log_error_errno(r, "Failed to start manager: %m");
/* Write finish default resolv.conf to avoid a dangling symlink */
(void) manager_write_resolv_conf(m);
(void) manager_check_resolv_conf(m);
/* Let's drop the remaining caps now */
r = capability_bounding_set_drop((UINT64_C(1) << CAP_NET_RAW), true);
if (r < 0)
return log_error_errno(r, "Failed to drop remaining caps: %m");
notify_stop = notify_start(NOTIFY_READY, NOTIFY_STOPPING);
r = sd_event_loop(m->event);
if (r < 0)
return log_error_errno(r, "Event loop failed: %m");
return 0;
}
DEFINE_MAIN_FUNCTION(run);
| 3,662 | 35.63 | 122 |
c
|
null |
systemd-main/src/resolve/test-dnssec-complex.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <netinet/ip.h>
#include "sd-bus.h"
#include "af-list.h"
#include "alloc-util.h"
#include "bus-common-errors.h"
#include "bus-locator.h"
#include "dns-type.h"
#include "random-util.h"
#include "resolved-def.h"
#include "string-util.h"
#include "time-util.h"
static void prefix_random(const char *name, char **ret) {
uint64_t i, u;
char *m = NULL;
u = 1 + (random_u64() & 3);
for (i = 0; i < u; i++) {
_cleanup_free_ char *b = NULL;
char *x;
assert_se(asprintf(&b, "x%" PRIu64 "x", random_u64()));
x = strjoin(b, ".", name);
assert_se(x);
free(m);
m = x;
}
*ret = m;
}
static void test_rr_lookup(sd_bus *bus, const char *name, uint16_t type, const char *result) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *req = NULL, *reply = NULL;
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_free_ char *m = NULL;
int r;
/* If the name starts with a dot, we prefix one to three random labels */
if (startswith(name, ".")) {
prefix_random(name + 1, &m);
name = m;
}
assert_se(bus_message_new_method_call(bus, &req, bus_resolve_mgr, "ResolveRecord") >= 0);
assert_se(sd_bus_message_append(req, "isqqt", 0, name, DNS_CLASS_IN, type, UINT64_C(0)) >= 0);
r = sd_bus_call(bus, req, SD_RESOLVED_QUERY_TIMEOUT_USEC, &error, &reply);
if (r < 0) {
assert_se(result);
assert_se(sd_bus_error_has_name(&error, result));
log_info("[OK] %s/%s resulted in <%s>.", name, dns_type_to_string(type), error.name);
} else {
assert_se(!result);
log_info("[OK] %s/%s succeeded.", name, dns_type_to_string(type));
}
}
static void test_hostname_lookup(sd_bus *bus, const char *name, int family, const char *result) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *req = NULL, *reply = NULL;
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_free_ char *m = NULL;
const char *af;
int r;
af = family == AF_UNSPEC ? "AF_UNSPEC" : af_to_name(family);
/* If the name starts with a dot, we prefix one to three random labels */
if (startswith(name, ".")) {
prefix_random(name + 1, &m);
name = m;
}
assert_se(bus_message_new_method_call(bus, &req, bus_resolve_mgr, "ResolveHostname") >= 0);
assert_se(sd_bus_message_append(req, "isit", 0, name, family, UINT64_C(0)) >= 0);
r = sd_bus_call(bus, req, SD_RESOLVED_QUERY_TIMEOUT_USEC, &error, &reply);
if (r < 0) {
assert_se(result);
assert_se(sd_bus_error_has_name(&error, result));
log_info("[OK] %s/%s resulted in <%s>.", name, af, error.name);
} else {
assert_se(!result);
log_info("[OK] %s/%s succeeded.", name, af);
}
}
int main(int argc, char* argv[]) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
/* Note that this is a manual test as it requires:
*
* Full network access
* A DNSSEC capable DNS server
* That zones contacted are still set up as they were when I wrote this.
*/
assert_se(sd_bus_open_system(&bus) >= 0);
/* Normally signed */
test_rr_lookup(bus, "www.eurid.eu", DNS_TYPE_A, NULL);
test_hostname_lookup(bus, "www.eurid.eu", AF_UNSPEC, NULL);
test_rr_lookup(bus, "sigok.verteiltesysteme.net", DNS_TYPE_A, NULL);
test_hostname_lookup(bus, "sigok.verteiltesysteme.net", AF_UNSPEC, NULL);
/* Normally signed, NODATA */
test_rr_lookup(bus, "www.eurid.eu", DNS_TYPE_RP, BUS_ERROR_NO_SUCH_RR);
test_rr_lookup(bus, "sigok.verteiltesysteme.net", DNS_TYPE_RP, BUS_ERROR_NO_SUCH_RR);
/* Invalid signature */
test_rr_lookup(bus, "sigfail.verteiltesysteme.net", DNS_TYPE_A, BUS_ERROR_DNSSEC_FAILED);
test_hostname_lookup(bus, "sigfail.verteiltesysteme.net", AF_INET, BUS_ERROR_DNSSEC_FAILED);
/* Invalid signature, RSA, wildcard */
test_rr_lookup(bus, ".wilda.rhybar.0skar.cz", DNS_TYPE_A, BUS_ERROR_DNSSEC_FAILED);
test_hostname_lookup(bus, ".wilda.rhybar.0skar.cz", AF_INET, BUS_ERROR_DNSSEC_FAILED);
/* Invalid signature, ECDSA, wildcard */
test_rr_lookup(bus, ".wilda.rhybar.ecdsa.0skar.cz", DNS_TYPE_A, BUS_ERROR_DNSSEC_FAILED);
test_hostname_lookup(bus, ".wilda.rhybar.ecdsa.0skar.cz", AF_INET, BUS_ERROR_DNSSEC_FAILED);
/* Missing DS for DNSKEY */
test_rr_lookup(bus, "www.dnssec-bogus.sg", DNS_TYPE_A, BUS_ERROR_DNSSEC_FAILED);
test_hostname_lookup(bus, "www.dnssec-bogus.sg", AF_INET, BUS_ERROR_DNSSEC_FAILED);
/* NXDOMAIN in NSEC domain */
test_rr_lookup(bus, "hhh.nasa.gov", DNS_TYPE_A, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, "hhh.nasa.gov", AF_UNSPEC, BUS_ERROR_DNS_NXDOMAIN);
test_rr_lookup(bus, "_pgpkey-https._tcp.hkps.pool.sks-keyservers.net", DNS_TYPE_SRV, BUS_ERROR_DNS_NXDOMAIN);
/* wildcard, NSEC zone */
test_rr_lookup(bus, ".wilda.nsec.0skar.cz", DNS_TYPE_A, NULL);
test_hostname_lookup(bus, ".wilda.nsec.0skar.cz", AF_INET, NULL);
/* wildcard, NSEC zone, NODATA */
test_rr_lookup(bus, ".wilda.nsec.0skar.cz", DNS_TYPE_RP, BUS_ERROR_NO_SUCH_RR);
/* wildcard, NSEC3 zone */
test_rr_lookup(bus, ".wilda.0skar.cz", DNS_TYPE_A, NULL);
test_hostname_lookup(bus, ".wilda.0skar.cz", AF_INET, NULL);
/* wildcard, NSEC3 zone, NODATA */
test_rr_lookup(bus, ".wilda.0skar.cz", DNS_TYPE_RP, BUS_ERROR_NO_SUCH_RR);
/* wildcard, NSEC zone, CNAME */
test_rr_lookup(bus, ".wild.nsec.0skar.cz", DNS_TYPE_A, NULL);
test_hostname_lookup(bus, ".wild.nsec.0skar.cz", AF_UNSPEC, NULL);
test_hostname_lookup(bus, ".wild.nsec.0skar.cz", AF_INET, NULL);
/* wildcard, NSEC zone, NODATA, CNAME */
test_rr_lookup(bus, ".wild.nsec.0skar.cz", DNS_TYPE_RP, BUS_ERROR_NO_SUCH_RR);
/* wildcard, NSEC3 zone, CNAME */
test_rr_lookup(bus, ".wild.0skar.cz", DNS_TYPE_A, NULL);
test_hostname_lookup(bus, ".wild.0skar.cz", AF_UNSPEC, NULL);
test_hostname_lookup(bus, ".wild.0skar.cz", AF_INET, NULL);
/* wildcard, NSEC3 zone, NODATA, CNAME */
test_rr_lookup(bus, ".wild.0skar.cz", DNS_TYPE_RP, BUS_ERROR_NO_SUCH_RR);
/* NODATA due to empty non-terminal in NSEC domain */
test_rr_lookup(bus, "herndon.nasa.gov", DNS_TYPE_A, BUS_ERROR_NO_SUCH_RR);
test_hostname_lookup(bus, "herndon.nasa.gov", AF_UNSPEC, BUS_ERROR_NO_SUCH_RR);
test_hostname_lookup(bus, "herndon.nasa.gov", AF_INET, BUS_ERROR_NO_SUCH_RR);
test_hostname_lookup(bus, "herndon.nasa.gov", AF_INET6, BUS_ERROR_NO_SUCH_RR);
/* NXDOMAIN in NSEC root zone: */
test_rr_lookup(bus, "jasdhjas.kjkfgjhfjg", DNS_TYPE_A, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, "jasdhjas.kjkfgjhfjg", AF_UNSPEC, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, "jasdhjas.kjkfgjhfjg", AF_INET, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, "jasdhjas.kjkfgjhfjg", AF_INET6, BUS_ERROR_DNS_NXDOMAIN);
/* NXDOMAIN in NSEC3 .com zone: */
test_rr_lookup(bus, "kjkfgjhfjgsdfdsfd.com", DNS_TYPE_A, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, "kjkfgjhfjgsdfdsfd.com", AF_INET, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, "kjkfgjhfjgsdfdsfd.com", AF_INET6, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, "kjkfgjhfjgsdfdsfd.com", AF_UNSPEC, BUS_ERROR_DNS_NXDOMAIN);
/* Unsigned A */
test_rr_lookup(bus, "poettering.de", DNS_TYPE_A, NULL);
test_rr_lookup(bus, "poettering.de", DNS_TYPE_AAAA, NULL);
test_hostname_lookup(bus, "poettering.de", AF_UNSPEC, NULL);
test_hostname_lookup(bus, "poettering.de", AF_INET, NULL);
test_hostname_lookup(bus, "poettering.de", AF_INET6, NULL);
#if HAVE_LIBIDN2 || HAVE_LIBIDN
/* Unsigned A with IDNA conversion necessary */
test_hostname_lookup(bus, "pöttering.de", AF_UNSPEC, NULL);
test_hostname_lookup(bus, "pöttering.de", AF_INET, NULL);
test_hostname_lookup(bus, "pöttering.de", AF_INET6, NULL);
#endif
/* DNAME, pointing to NXDOMAIN */
test_rr_lookup(bus, ".ireallyhpoethisdoesnexist.xn--kprw13d.", DNS_TYPE_A, BUS_ERROR_DNS_NXDOMAIN);
test_rr_lookup(bus, ".ireallyhpoethisdoesnexist.xn--kprw13d.", DNS_TYPE_RP, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, ".ireallyhpoethisdoesntexist.xn--kprw13d.", AF_UNSPEC, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, ".ireallyhpoethisdoesntexist.xn--kprw13d.", AF_INET, BUS_ERROR_DNS_NXDOMAIN);
test_hostname_lookup(bus, ".ireallyhpoethisdoesntexist.xn--kprw13d.", AF_INET6, BUS_ERROR_DNS_NXDOMAIN);
return 0;
}
| 9,263 | 42.492958 | 117 |
c
|
null |
systemd-main/src/resolve/test-resolve-tables.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "dns-type.h"
#include "resolved-dns-dnssec.h"
#include "resolved-dns-packet.h"
#include "test-tables.h"
int main(int argc, char **argv) {
uint16_t i;
test_table(dns_protocol, DNS_PROTOCOL);
test_table(dnssec_result, DNSSEC_RESULT);
test_table(dnssec_verdict, DNSSEC_VERDICT);
test_table_sparse(dns_rcode, DNS_RCODE);
test_table_sparse(dns_type, DNS_TYPE);
log_info("/* DNS_TYPE */");
for (i = 0; i < _DNS_TYPE_MAX; i++) {
const char *s;
s = dns_type_to_string(i);
assert_se(s == NULL || strlen(s) < _DNS_TYPE_STRING_MAX);
if (s)
log_info("%-*s %s%s%s%s%s%s%s%s%s",
(int) _DNS_TYPE_STRING_MAX - 1, s,
dns_type_is_pseudo(i) ? "pseudo " : "",
dns_type_is_valid_query(i) ? "valid_query " : "",
dns_type_is_valid_rr(i) ? "is_valid_rr " : "",
dns_type_may_redirect(i) ? "may_redirect " : "",
dns_type_is_dnssec(i) ? "dnssec " : "",
dns_type_is_obsolete(i) ? "obsolete " : "",
dns_type_may_wildcard(i) ? "wildcard " : "",
dns_type_apex_only(i) ? "apex_only " : "",
dns_type_needs_authentication(i) ? "needs_authentication" : "");
}
log_info("/* DNS_CLASS */");
for (i = 0; i < _DNS_CLASS_MAX; i++) {
const char *s;
s = dns_class_to_string(i);
assert_se(s == NULL || strlen(s) < _DNS_CLASS_STRING_MAX);
if (s)
log_info("%-*s %s%s",
(int) _DNS_CLASS_STRING_MAX - 1, s,
dns_class_is_pseudo(i) ? "is_pseudo " : "",
dns_class_is_valid_rr(i) ? "is_valid_rr " : "");
}
return EXIT_SUCCESS;
}
| 2,156 | 38.218182 | 97 |
c
|
null |
systemd-main/src/resolve/test-resolved-etc-hosts.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <arpa/inet.h>
#include <malloc.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "log.h"
#include "resolved-etc-hosts.h"
#include "strv.h"
#include "tests.h"
#include "tmpfile-util.h"
TEST(parse_etc_hosts_system) {
_cleanup_fclose_ FILE *f = NULL;
f = fopen("/etc/hosts", "re");
if (!f) {
assert_se(errno == ENOENT);
return;
}
_cleanup_(etc_hosts_clear) EtcHosts hosts = {};
assert_se(etc_hosts_parse(&hosts, f) == 0);
}
#define in_addr_4(_address_str) \
(&(struct in_addr_data) { .family = AF_INET, .address.in = { .s_addr = inet_addr(_address_str) } })
#define in_addr_6(...) \
(&(struct in_addr_data) { .family = AF_INET6, .address.in6 = { .s6_addr = __VA_ARGS__ } })
#define has_4(_set, _address_str) \
set_contains(_set, in_addr_4(_address_str))
#define has_6(_set, ...) \
set_contains(_set, in_addr_6(__VA_ARGS__))
TEST(parse_etc_hosts) {
_cleanup_(unlink_tempfilep) char
t[] = "/tmp/test-resolved-etc-hosts.XXXXXX";
int fd;
_cleanup_fclose_ FILE *f = NULL;
fd = mkostemp_safe(t);
assert_se(fd >= 0);
f = fdopen(fd, "r+");
assert_se(f);
fputs("1.2.3.4 some.where\n"
"1.2.3.5 some.where\n"
"1.2.3.6 dash dash-dash.where-dash\n"
"1.2.3.7 bad-dash- -bad-dash -bad-dash.bad-\n"
"1.2.3.8\n"
"1.2.3.9 before.comment # within.comment\n"
"1.2.3.10 before.comment#within.comment2\n"
"1.2.3.11 before.comment# within.comment3\n"
"1.2.3.12 before.comment#\n"
"1.2.3 short.address\n"
"1.2.3.4.5 long.address\n"
"1::2::3 multi.colon\n"
"::0 some.where some.other\n"
"0.0.0.0 deny.listed\n"
"::5\t\t\t \tsome.where\tsome.other foobar.foo.foo\t\t\t\n"
" \n", f);
assert_se(fflush_and_check(f) >= 0);
rewind(f);
_cleanup_(etc_hosts_clear) EtcHosts hosts = {};
assert_se(etc_hosts_parse(&hosts, f) == 0);
EtcHostsItemByName *bn;
assert_se(bn = hashmap_get(hosts.by_name, "some.where"));
assert_se(set_size(bn->addresses) == 3);
assert_se(has_4(bn->addresses, "1.2.3.4"));
assert_se(has_4(bn->addresses, "1.2.3.5"));
assert_se(has_6(bn->addresses, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5}));
assert_se(bn = hashmap_get(hosts.by_name, "dash"));
assert_se(set_size(bn->addresses) == 1);
assert_se(has_4(bn->addresses, "1.2.3.6"));
assert_se(bn = hashmap_get(hosts.by_name, "dash-dash.where-dash"));
assert_se(set_size(bn->addresses) == 1);
assert_se(has_4(bn->addresses, "1.2.3.6"));
/* See https://tools.ietf.org/html/rfc1035#section-2.3.1 */
FOREACH_STRING(s, "bad-dash-", "-bad-dash", "-bad-dash.bad-")
assert_se(!hashmap_get(hosts.by_name, s));
assert_se(bn = hashmap_get(hosts.by_name, "before.comment"));
assert_se(set_size(bn->addresses) == 4);
assert_se(has_4(bn->addresses, "1.2.3.9"));
assert_se(has_4(bn->addresses, "1.2.3.10"));
assert_se(has_4(bn->addresses, "1.2.3.11"));
assert_se(has_4(bn->addresses, "1.2.3.12"));
assert_se(!hashmap_get(hosts.by_name, "within.comment"));
assert_se(!hashmap_get(hosts.by_name, "within.comment2"));
assert_se(!hashmap_get(hosts.by_name, "within.comment3"));
assert_se(!hashmap_get(hosts.by_name, "#"));
assert_se(!hashmap_get(hosts.by_name, "short.address"));
assert_se(!hashmap_get(hosts.by_name, "long.address"));
assert_se(!hashmap_get(hosts.by_name, "multi.colon"));
assert_se(!set_contains(hosts.no_address, "short.address"));
assert_se(!set_contains(hosts.no_address, "long.address"));
assert_se(!set_contains(hosts.no_address, "multi.colon"));
assert_se(bn = hashmap_get(hosts.by_name, "some.other"));
assert_se(set_size(bn->addresses) == 1);
assert_se(has_6(bn->addresses, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5}));
EtcHostsItemByAddress *ba;
assert_se(ba = hashmap_get(hosts.by_address, in_addr_4("1.2.3.6")));
assert_se(set_size(ba->names) == 2);
assert_se(set_contains(ba->names, "dash"));
assert_se(set_contains(ba->names, "dash-dash.where-dash"));
assert_se(streq(ba->canonical_name, "dash"));
assert_se(ba = hashmap_get(hosts.by_address, in_addr_6({0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5})));
assert_se(set_size(ba->names) == 3);
assert_se(set_contains(ba->names, "some.where"));
assert_se(set_contains(ba->names, "some.other"));
assert_se(set_contains(ba->names, "foobar.foo.foo"));
assert_se(streq(ba->canonical_name, "some.where"));
assert_se( set_contains(hosts.no_address, "some.where"));
assert_se( set_contains(hosts.no_address, "some.other"));
assert_se( set_contains(hosts.no_address, "deny.listed"));
assert_se(!set_contains(hosts.no_address, "foobar.foo.foo"));
}
static void test_parse_file_one(const char *fname) {
_cleanup_(etc_hosts_clear) EtcHosts hosts = {};
_cleanup_fclose_ FILE *f = NULL;
log_info("/* %s(\"%s\") */", __func__, fname);
assert_se(f = fopen(fname, "re"));
assert_se(etc_hosts_parse(&hosts, f) == 0);
}
TEST(parse_file) {
for (int i = 1; i < saved_argc; i++)
test_parse_file_one(saved_argv[i]);
}
DEFINE_TEST_MAIN(LOG_DEBUG);
| 5,968 | 37.509677 | 115 |
c
|
null |
systemd-main/src/resolve/test-resolved-packet.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "log.h"
#include "resolved-dns-packet.h"
#include "tests.h"
TEST(dns_packet_new) {
size_t i;
_cleanup_(dns_packet_unrefp) DnsPacket *p2 = NULL;
for (i = 0; i <= DNS_PACKET_SIZE_MAX; i++) {
_cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
assert_se(dns_packet_new(&p, DNS_PROTOCOL_DNS, i, DNS_PACKET_SIZE_MAX) == 0);
log_debug("dns_packet_new: %zu → %zu", i, p->allocated);
assert_se(p->allocated >= MIN(DNS_PACKET_SIZE_MAX, i));
if (i > DNS_PACKET_SIZE_START + 10 && i < DNS_PACKET_SIZE_MAX - 10)
i = MIN(i * 2, DNS_PACKET_SIZE_MAX - 10);
}
assert_se(dns_packet_new(&p2, DNS_PROTOCOL_DNS, DNS_PACKET_SIZE_MAX + 1, DNS_PACKET_SIZE_MAX) == -EFBIG);
}
DEFINE_TEST_MAIN(LOG_DEBUG);
| 890 | 32 | 113 |
c
|
null |
systemd-main/src/run-generator/run-generator.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "alloc-util.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio.h"
#include "generator.h"
#include "glyph-util.h"
#include "mkdir.h"
#include "proc-cmdline.h"
#include "special.h"
#include "specifier.h"
#include "strv.h"
static const char *arg_dest = NULL;
static char **arg_commands = NULL;
static char *arg_success_action = NULL;
static char *arg_failure_action = NULL;
STATIC_DESTRUCTOR_REGISTER(arg_commands, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_success_action, freep);
STATIC_DESTRUCTOR_REGISTER(arg_failure_action, freep);
static int parse(const char *key, const char *value, void *data) {
int r;
if (proc_cmdline_key_streq(key, "systemd.run")) {
if (proc_cmdline_value_missing(key, value))
return 0;
r = strv_extend(&arg_commands, value);
if (r < 0)
return log_oom();
} else if (proc_cmdline_key_streq(key, "systemd.run_success_action")) {
if (proc_cmdline_value_missing(key, value))
return 0;
return free_and_strdup_warn(&arg_success_action, value);
} else if (proc_cmdline_key_streq(key, "systemd.run_failure_action")) {
if (proc_cmdline_value_missing(key, value))
return 0;
return free_and_strdup_warn(&arg_failure_action, value);
}
return 0;
}
static int generate(void) {
_cleanup_fclose_ FILE *f = NULL;
const char *p;
int r;
if (strv_isempty(arg_commands) && !arg_success_action)
return 0;
p = strjoina(arg_dest, "/kernel-command-line.service");
f = fopen(p, "wxe");
if (!f)
return log_error_errno(errno, "Failed to create unit file %s: %m", p);
fputs("# Automatically generated by systemd-run-generator\n\n"
"[Unit]\n"
"Description=Command from Kernel Command Line\n"
"Documentation=man:systemd-run-generator(8)\n"
"SourcePath=/proc/cmdline\n", f);
if (!streq_ptr(arg_success_action, "none"))
fprintf(f, "SuccessAction=%s\n",
arg_success_action ?: "exit");
if (!streq_ptr(arg_failure_action, "none"))
fprintf(f, "FailureAction=%s\n",
arg_failure_action ?: "exit");
fputs("\n"
"[Service]\n"
"Type=oneshot\n"
"StandardOutput=journal+console\n", f);
STRV_FOREACH(c, arg_commands) {
_cleanup_free_ char *a = NULL;
a = specifier_escape(*c);
if (!a)
return log_oom();
fprintf(f, "ExecStart=%s\n", a);
}
r = fflush_and_check(f);
if (r < 0)
return log_error_errno(r, "Failed to write unit file %s: %m", p);
/* Let's create a target we can link "default.target" to */
p = strjoina(arg_dest, "/kernel-command-line.target");
r = write_string_file(
p,
"# Automatically generated by systemd-run-generator\n\n"
"[Unit]\n"
"Description=Command from Kernel Command Line\n"
"Documentation=man:systemd-run-generator(8)\n"
"SourcePath=/proc/cmdline\n"
"Requires=kernel-command-line.service\n"
"After=kernel-command-line.service\n",
WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_NOFOLLOW);
if (r < 0)
return log_error_errno(r, "Failed to create unit file %s: %m", p);
/* And now redirect default.target to our new target */
p = strjoina(arg_dest, "/" SPECIAL_DEFAULT_TARGET);
if (symlink("kernel-command-line.target", p) < 0)
return log_error_errno(errno, "Failed to link unit file kernel-command-line.target %s %s: %m",
special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), p);
return 0;
}
static int run(const char *dest, const char *dest_early, const char *dest_late) {
int r;
assert_se(arg_dest = dest);
r = proc_cmdline_parse(parse, 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");
return generate();
}
DEFINE_MAIN_GENERATOR_FUNCTION(run);
| 4,646 | 32.431655 | 110 |
c
|
null |
systemd-main/src/shared/acl-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "acl-util.h"
#include "alloc-util.h"
#include "errno-util.h"
#include "string-util.h"
#include "strv.h"
#include "user-util.h"
#if HAVE_ACL
int acl_find_uid(acl_t acl, uid_t uid, acl_entry_t *ret_entry) {
acl_entry_t i;
int r;
assert(acl);
assert(uid_is_valid(uid));
assert(ret_entry);
for (r = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
r > 0;
r = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
acl_tag_t tag;
uid_t *u;
bool b;
if (acl_get_tag_type(i, &tag) < 0)
return -errno;
if (tag != ACL_USER)
continue;
u = acl_get_qualifier(i);
if (!u)
return -errno;
b = *u == uid;
acl_free(u);
if (b) {
*ret_entry = i;
return 1;
}
}
if (r < 0)
return -errno;
*ret_entry = NULL;
return 0;
}
int calc_acl_mask_if_needed(acl_t *acl_p) {
acl_entry_t i;
int r;
bool need = false;
assert(acl_p);
for (r = acl_get_entry(*acl_p, ACL_FIRST_ENTRY, &i);
r > 0;
r = acl_get_entry(*acl_p, ACL_NEXT_ENTRY, &i)) {
acl_tag_t tag;
if (acl_get_tag_type(i, &tag) < 0)
return -errno;
if (tag == ACL_MASK)
return 0;
if (IN_SET(tag, ACL_USER, ACL_GROUP))
need = true;
}
if (r < 0)
return -errno;
if (need && acl_calc_mask(acl_p) < 0)
return -errno;
return need;
}
int add_base_acls_if_needed(acl_t *acl_p, const char *path) {
acl_entry_t i;
int r;
bool have_user_obj = false, have_group_obj = false, have_other = false;
struct stat st;
_cleanup_(acl_freep) acl_t basic = NULL;
assert(acl_p);
assert(path);
for (r = acl_get_entry(*acl_p, ACL_FIRST_ENTRY, &i);
r > 0;
r = acl_get_entry(*acl_p, ACL_NEXT_ENTRY, &i)) {
acl_tag_t tag;
if (acl_get_tag_type(i, &tag) < 0)
return -errno;
if (tag == ACL_USER_OBJ)
have_user_obj = true;
else if (tag == ACL_GROUP_OBJ)
have_group_obj = true;
else if (tag == ACL_OTHER)
have_other = true;
if (have_user_obj && have_group_obj && have_other)
return 0;
}
if (r < 0)
return -errno;
r = stat(path, &st);
if (r < 0)
return -errno;
basic = acl_from_mode(st.st_mode);
if (!basic)
return -errno;
for (r = acl_get_entry(basic, ACL_FIRST_ENTRY, &i);
r > 0;
r = acl_get_entry(basic, ACL_NEXT_ENTRY, &i)) {
acl_tag_t tag;
acl_entry_t dst;
if (acl_get_tag_type(i, &tag) < 0)
return -errno;
if ((tag == ACL_USER_OBJ && have_user_obj) ||
(tag == ACL_GROUP_OBJ && have_group_obj) ||
(tag == ACL_OTHER && have_other))
continue;
r = acl_create_entry(acl_p, &dst);
if (r < 0)
return -errno;
r = acl_copy_entry(dst, i);
if (r < 0)
return -errno;
}
if (r < 0)
return -errno;
return 0;
}
int acl_search_groups(const char *path, char ***ret_groups) {
_cleanup_strv_free_ char **g = NULL;
_cleanup_(acl_freep) acl_t acl = NULL;
bool ret = false;
acl_entry_t entry;
int r;
assert(path);
acl = acl_get_file(path, ACL_TYPE_DEFAULT);
if (!acl)
return -errno;
r = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry);
for (;;) {
_cleanup_(acl_free_gid_tpp) gid_t *gid = NULL;
acl_tag_t tag;
if (r < 0)
return -errno;
if (r == 0)
break;
if (acl_get_tag_type(entry, &tag) < 0)
return -errno;
if (tag != ACL_GROUP)
goto next;
gid = acl_get_qualifier(entry);
if (!gid)
return -errno;
if (in_gid(*gid) > 0) {
if (!ret_groups)
return true;
ret = true;
}
if (ret_groups) {
char *name;
name = gid_to_name(*gid);
if (!name)
return -ENOMEM;
r = strv_consume(&g, name);
if (r < 0)
return r;
}
next:
r = acl_get_entry(acl, ACL_NEXT_ENTRY, &entry);
}
if (ret_groups)
*ret_groups = TAKE_PTR(g);
return ret;
}
int parse_acl(
const char *text,
acl_t *ret_acl_access,
acl_t *ret_acl_access_exec, /* extra rules to apply to inodes subject to uppercase X handling */
acl_t *ret_acl_default,
bool want_mask) {
_cleanup_strv_free_ char **a = NULL, **e = NULL, **d = NULL, **split = NULL;
_cleanup_(acl_freep) acl_t a_acl = NULL, e_acl = NULL, d_acl = NULL;
int r;
assert(text);
assert(ret_acl_access);
assert(ret_acl_access_exec);
assert(ret_acl_default);
split = strv_split(text, ",");
if (!split)
return -ENOMEM;
STRV_FOREACH(entry, split) {
_cleanup_strv_free_ char **entry_split = NULL;
_cleanup_free_ char *entry_join = NULL;
int n;
n = strv_split_full(&entry_split, *entry, ":", EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_RETAIN_ESCAPE);
if (n < 0)
return n;
if (n < 3 || n > 4)
return -EINVAL;
string_replace_char(entry_split[n-1], 'X', 'x');
if (n == 4) {
if (!STR_IN_SET(entry_split[0], "default", "d"))
return -EINVAL;
entry_join = strv_join(entry_split + 1, ":");
if (!entry_join)
return -ENOMEM;
r = strv_consume(&d, TAKE_PTR(entry_join));
} else { /* n == 3 */
entry_join = strv_join(entry_split, ":");
if (!entry_join)
return -ENOMEM;
if (!streq(*entry, entry_join))
r = strv_consume(&e, TAKE_PTR(entry_join));
else
r = strv_consume(&a, TAKE_PTR(entry_join));
}
if (r < 0)
return r;
}
if (!strv_isempty(a)) {
_cleanup_free_ char *join = NULL;
join = strv_join(a, ",");
if (!join)
return -ENOMEM;
a_acl = acl_from_text(join);
if (!a_acl)
return -errno;
if (want_mask) {
r = calc_acl_mask_if_needed(&a_acl);
if (r < 0)
return r;
}
}
if (!strv_isempty(e)) {
_cleanup_free_ char *join = NULL;
join = strv_join(e, ",");
if (!join)
return -ENOMEM;
e_acl = acl_from_text(join);
if (!e_acl)
return -errno;
/* The mask must be calculated after deciding whether the execute bit should be set. */
}
if (!strv_isempty(d)) {
_cleanup_free_ char *join = NULL;
join = strv_join(d, ",");
if (!join)
return -ENOMEM;
d_acl = acl_from_text(join);
if (!d_acl)
return -errno;
if (want_mask) {
r = calc_acl_mask_if_needed(&d_acl);
if (r < 0)
return r;
}
}
*ret_acl_access = TAKE_PTR(a_acl);
*ret_acl_access_exec = TAKE_PTR(e_acl);
*ret_acl_default = TAKE_PTR(d_acl);
return 0;
}
static int acl_entry_equal(acl_entry_t a, acl_entry_t b) {
acl_tag_t tag_a, tag_b;
if (acl_get_tag_type(a, &tag_a) < 0)
return -errno;
if (acl_get_tag_type(b, &tag_b) < 0)
return -errno;
if (tag_a != tag_b)
return false;
switch (tag_a) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
/* can have only one of those */
return true;
case ACL_USER: {
_cleanup_(acl_free_uid_tpp) uid_t *uid_a = NULL, *uid_b = NULL;
uid_a = acl_get_qualifier(a);
if (!uid_a)
return -errno;
uid_b = acl_get_qualifier(b);
if (!uid_b)
return -errno;
return *uid_a == *uid_b;
}
case ACL_GROUP: {
_cleanup_(acl_free_gid_tpp) gid_t *gid_a = NULL, *gid_b = NULL;
gid_a = acl_get_qualifier(a);
if (!gid_a)
return -errno;
gid_b = acl_get_qualifier(b);
if (!gid_b)
return -errno;
return *gid_a == *gid_b;
}
default:
assert_not_reached();
}
}
static int find_acl_entry(acl_t acl, acl_entry_t entry, acl_entry_t *ret) {
acl_entry_t i;
int r;
for (r = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
r > 0;
r = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
r = acl_entry_equal(i, entry);
if (r < 0)
return r;
if (r > 0) {
if (ret)
*ret = i;
return 0;
}
}
if (r < 0)
return -errno;
return -ENOENT;
}
int acls_for_file(const char *path, acl_type_t type, acl_t acl, acl_t *ret) {
_cleanup_(acl_freep) acl_t applied = NULL;
acl_entry_t i;
int r;
assert(path);
applied = acl_get_file(path, type);
if (!applied)
return -errno;
for (r = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
r > 0;
r = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
acl_entry_t j;
r = find_acl_entry(applied, i, &j);
if (r == -ENOENT) {
if (acl_create_entry(&applied, &j) < 0)
return -errno;
} else if (r < 0)
return r;
if (acl_copy_entry(j, i) < 0)
return -errno;
}
if (r < 0)
return -errno;
if (ret)
*ret = TAKE_PTR(applied);
return 0;
}
/* POSIX says that ACL_{READ,WRITE,EXECUTE} don't have to be bitmasks. But that is a natural thing to do and
* all extant implementations do it. Let's make sure that we fail verbosely in the (imho unlikely) scenario
* that we get a new implementation that does not satisfy this. */
assert_cc(!(ACL_READ & ACL_WRITE));
assert_cc(!(ACL_WRITE & ACL_EXECUTE));
assert_cc(!(ACL_EXECUTE & ACL_READ));
assert_cc((unsigned) ACL_READ == ACL_READ);
assert_cc((unsigned) ACL_WRITE == ACL_WRITE);
assert_cc((unsigned) ACL_EXECUTE == ACL_EXECUTE);
int fd_add_uid_acl_permission(
int fd,
uid_t uid,
unsigned mask) {
_cleanup_(acl_freep) acl_t acl = NULL;
acl_permset_t permset;
acl_entry_t entry;
int r;
/* Adds an ACL entry for the specified file to allow the indicated access to the specified
* user. Operates purely incrementally. */
assert(fd >= 0);
assert(uid_is_valid(uid));
acl = acl_get_fd(fd);
if (!acl)
return -errno;
r = acl_find_uid(acl, uid, &entry);
if (r <= 0) {
if (acl_create_entry(&acl, &entry) < 0 ||
acl_set_tag_type(entry, ACL_USER) < 0 ||
acl_set_qualifier(entry, &uid) < 0)
return -errno;
}
if (acl_get_permset(entry, &permset) < 0)
return -errno;
if ((mask & ACL_READ) && acl_add_perm(permset, ACL_READ) < 0)
return -errno;
if ((mask & ACL_WRITE) && acl_add_perm(permset, ACL_WRITE) < 0)
return -errno;
if ((mask & ACL_EXECUTE) && acl_add_perm(permset, ACL_EXECUTE) < 0)
return -errno;
r = calc_acl_mask_if_needed(&acl);
if (r < 0)
return r;
if (acl_set_fd(fd, acl) < 0)
return -errno;
return 0;
}
int fd_acl_make_read_only(int fd) {
_cleanup_(acl_freep) acl_t acl = NULL;
bool changed = false;
acl_entry_t i;
int r;
assert(fd >= 0);
/* Safely drops all W bits from all relevant ACL entries of the file, without changing entries which
* are masked by the ACL mask */
acl = acl_get_fd(fd);
if (!acl) {
if (!ERRNO_IS_NOT_SUPPORTED(errno))
return -errno;
/* No ACLs? Then just update the regular mode_t */
return fd_acl_make_read_only_fallback(fd);
}
for (r = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
r > 0;
r = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
acl_permset_t permset;
acl_tag_t tag;
int b;
if (acl_get_tag_type(i, &tag) < 0)
return -errno;
/* These three control the x bits overall (as ACL_MASK affects all remaining tags) */
if (!IN_SET(tag, ACL_USER_OBJ, ACL_MASK, ACL_OTHER))
continue;
if (acl_get_permset(i, &permset) < 0)
return -errno;
b = acl_get_perm(permset, ACL_WRITE);
if (b < 0)
return -errno;
if (b) {
if (acl_delete_perm(permset, ACL_WRITE) < 0)
return -errno;
changed = true;
}
}
if (r < 0)
return -errno;
if (!changed)
return 0;
if (acl_set_fd(fd, acl) < 0) {
if (!ERRNO_IS_NOT_SUPPORTED(errno))
return -errno;
return fd_acl_make_read_only_fallback(fd);
}
return 1;
}
int fd_acl_make_writable(int fd) {
_cleanup_(acl_freep) acl_t acl = NULL;
acl_entry_t i;
int r;
/* Safely adds the writable bit to the owner's ACL entry of this inode. (And only the owner's! – This
* not the obvious inverse of fd_acl_make_read_only() hence!) */
acl = acl_get_fd(fd);
if (!acl) {
if (!ERRNO_IS_NOT_SUPPORTED(errno))
return -errno;
/* No ACLs? Then just update the regular mode_t */
return fd_acl_make_writable_fallback(fd);
}
for (r = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
r > 0;
r = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
acl_permset_t permset;
acl_tag_t tag;
int b;
if (acl_get_tag_type(i, &tag) < 0)
return -errno;
if (tag != ACL_USER_OBJ)
continue;
if (acl_get_permset(i, &permset) < 0)
return -errno;
b = acl_get_perm(permset, ACL_WRITE);
if (b < 0)
return -errno;
if (b)
return 0; /* Already set? Then there's nothing to do. */
if (acl_add_perm(permset, ACL_WRITE) < 0)
return -errno;
break;
}
if (r < 0)
return -errno;
if (acl_set_fd(fd, acl) < 0) {
if (!ERRNO_IS_NOT_SUPPORTED(errno))
return -errno;
return fd_acl_make_writable_fallback(fd);
}
return 1;
}
#endif
int fd_acl_make_read_only_fallback(int fd) {
struct stat st;
assert(fd >= 0);
if (fstat(fd, &st) < 0)
return -errno;
if ((st.st_mode & 0222) == 0)
return 0;
if (fchmod(fd, st.st_mode & 0555) < 0)
return -errno;
return 1;
}
int fd_acl_make_writable_fallback(int fd) {
struct stat st;
assert(fd >= 0);
if (fstat(fd, &st) < 0)
return -errno;
if ((st.st_mode & 0200) != 0) /* already set */
return 0;
if (fchmod(fd, (st.st_mode & 07777) | 0200) < 0)
return -errno;
return 1;
}
| 18,388 | 27.160796 | 119 |
c
|
null |
systemd-main/src/shared/acl-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <unistd.h>
int fd_acl_make_read_only_fallback(int fd);
int fd_acl_make_writable_fallback(int fd);
#if HAVE_ACL
#include <acl/libacl.h>
#include <stdbool.h>
#include <sys/acl.h>
#include "macro.h"
int acl_find_uid(acl_t acl, uid_t uid, acl_entry_t *entry);
int calc_acl_mask_if_needed(acl_t *acl_p);
int add_base_acls_if_needed(acl_t *acl_p, const char *path);
int acl_search_groups(const char* path, char ***ret_groups);
int parse_acl(
const char *text,
acl_t *ret_acl_access,
acl_t *ret_acl_access_exec,
acl_t *ret_acl_default,
bool want_mask);
int acls_for_file(const char *path, acl_type_t type, acl_t new, acl_t *ret);
int fd_add_uid_acl_permission(int fd, uid_t uid, unsigned mask);
int fd_acl_make_read_only(int fd);
int fd_acl_make_writable(int fd);
/* acl_free takes multiple argument types.
* Multiple cleanup functions are necessary. */
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(acl_t, acl_free, NULL);
#define acl_free_charp acl_free
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(char*, acl_free_charp, NULL);
#define acl_free_uid_tp acl_free
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(uid_t*, acl_free_uid_tp, NULL);
#define acl_free_gid_tp acl_free
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(gid_t*, acl_free_gid_tp, NULL);
#else
#define ACL_READ 0x04
#define ACL_WRITE 0x02
#define ACL_EXECUTE 0x01
static inline int fd_add_uid_acl_permission(int fd, uid_t uid, unsigned mask) {
return -EOPNOTSUPP;
}
static inline int fd_acl_make_read_only(int fd) {
return fd_acl_make_read_only_fallback(fd);
}
static inline int fd_acl_make_writable(int fd) {
return fd_acl_make_writable_fallback(fd);
}
#endif
| 1,780 | 28.196721 | 79 |
h
|
null |
systemd-main/src/shared/acpi-fpdt.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include "acpi-fpdt.h"
#include "alloc-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "time-util.h"
struct acpi_table_header {
char signature[4];
uint32_t length;
uint8_t revision;
uint8_t checksum;
char oem_id[6];
char oem_table_id[8];
uint32_t oem_revision;
char asl_compiler_id[4];
uint32_t asl_compiler_revision;
} _packed_;
enum {
ACPI_FPDT_TYPE_BOOT = 0,
ACPI_FPDT_TYPE_S3PERF = 1,
};
struct acpi_fpdt_header {
uint16_t type;
uint8_t length;
uint8_t revision;
uint8_t reserved[4];
uint64_t ptr;
} _packed_;
struct acpi_fpdt_boot_header {
char signature[4];
uint32_t length;
} _packed_;
enum {
ACPI_FPDT_S3PERF_RESUME_REC = 0,
ACPI_FPDT_S3PERF_SUSPEND_REC = 1,
ACPI_FPDT_BOOT_REC = 2,
};
struct acpi_fpdt_boot {
uint16_t type;
uint8_t length;
uint8_t revision;
uint8_t reserved[4];
uint64_t reset_end;
uint64_t load_start;
uint64_t startup_start;
uint64_t exit_services_entry;
uint64_t exit_services_exit;
} _packed;
/* /dev/mem is deprecated on many systems, try using /sys/firmware/acpi/fpdt parsing instead.
* This code requires kernel version 5.12 on x86 based machines or 6.2 for arm64 */
static int acpi_get_boot_usec_kernel_parsed(usec_t *ret_loader_start, usec_t *ret_loader_exit) {
usec_t start, end;
int r;
r = read_timestamp_file("/sys/firmware/acpi/fpdt/boot/exitbootservice_end_ns", &end);
if (r < 0)
return r;
if (end == 0)
/* Non-UEFI compatible boot. */
return -ENODATA;
r = read_timestamp_file("/sys/firmware/acpi/fpdt/boot/bootloader_launch_ns", &start);
if (r < 0)
return r;
if (start == 0 || end < start)
return -EINVAL;
if (end > NSEC_PER_HOUR)
return -EINVAL;
if (ret_loader_start)
*ret_loader_start = start / 1000;
if (ret_loader_exit)
*ret_loader_exit = end / 1000;
return 0;
}
int acpi_get_boot_usec(usec_t *ret_loader_start, usec_t *ret_loader_exit) {
_cleanup_free_ char *buf = NULL;
struct acpi_table_header *tbl;
size_t l;
ssize_t ll;
struct acpi_fpdt_header *rec;
int r;
uint64_t ptr = 0;
_cleanup_close_ int fd = -EBADF;
struct acpi_fpdt_boot_header hbrec;
struct acpi_fpdt_boot brec;
r = acpi_get_boot_usec_kernel_parsed(ret_loader_start, ret_loader_exit);
if (r != -ENOENT) /* fallback to /dev/mem hack only if kernel doesn't support the new sysfs files */
return r;
r = read_full_virtual_file("/sys/firmware/acpi/tables/FPDT", &buf, &l);
if (r < 0)
return r;
if (l < sizeof(struct acpi_table_header) + sizeof(struct acpi_fpdt_header))
return -EINVAL;
tbl = (struct acpi_table_header *)buf;
if (l != tbl->length)
return -EINVAL;
if (memcmp(tbl->signature, "FPDT", 4) != 0)
return -EINVAL;
/* find Firmware Basic Boot Performance Pointer Record */
for (rec = (struct acpi_fpdt_header *)(buf + sizeof(struct acpi_table_header));
(char *)rec + offsetof(struct acpi_fpdt_header, revision) <= buf + l;
rec = (struct acpi_fpdt_header *)((char *)rec + rec->length)) {
if (rec->length <= 0)
break;
if (rec->type != ACPI_FPDT_TYPE_BOOT)
continue;
if (rec->length != sizeof(struct acpi_fpdt_header))
continue;
ptr = rec->ptr;
break;
}
if (ptr == 0)
return -ENODATA;
/* read Firmware Basic Boot Performance Data Record */
fd = open("/dev/mem", O_CLOEXEC|O_RDONLY);
if (fd < 0)
return -errno;
ll = pread(fd, &hbrec, sizeof(struct acpi_fpdt_boot_header), ptr);
if (ll < 0)
return -errno;
if ((size_t) ll != sizeof(struct acpi_fpdt_boot_header))
return -EINVAL;
if (memcmp(hbrec.signature, "FBPT", 4) != 0)
return -EINVAL;
if (hbrec.length < sizeof(struct acpi_fpdt_boot_header) + sizeof(struct acpi_fpdt_boot))
return -EINVAL;
ll = pread(fd, &brec, sizeof(struct acpi_fpdt_boot), ptr + sizeof(struct acpi_fpdt_boot_header));
if (ll < 0)
return -errno;
if ((size_t) ll != sizeof(struct acpi_fpdt_boot))
return -EINVAL;
if (brec.length != sizeof(struct acpi_fpdt_boot))
return -EINVAL;
if (brec.type != ACPI_FPDT_BOOT_REC)
return -EINVAL;
if (brec.exit_services_exit == 0)
/* Non-UEFI compatible boot. */
return -ENODATA;
if (brec.startup_start == 0 || brec.exit_services_exit < brec.startup_start)
return -EINVAL;
if (brec.exit_services_exit > NSEC_PER_HOUR)
return -EINVAL;
if (ret_loader_start)
*ret_loader_start = brec.startup_start / 1000;
if (ret_loader_exit)
*ret_loader_exit = brec.exit_services_exit / 1000;
return 0;
}
| 5,688 | 29.260638 | 108 |
c
|
null |
systemd-main/src/shared/apparmor-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stddef.h>
#include "alloc-util.h"
#include "apparmor-util.h"
#include "fileio.h"
#include "parse-util.h"
bool mac_apparmor_use(void) {
static int cached_use = -1;
if (cached_use < 0) {
_cleanup_free_ char *p = NULL;
cached_use =
read_one_line_file("/sys/module/apparmor/parameters/enabled", &p) >= 0 &&
parse_boolean(p) > 0;
}
return cached_use;
}
| 525 | 21.869565 | 97 |
c
|
null |
systemd-main/src/shared/async.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stddef.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <unistd.h>
#include "async.h"
#include "errno-util.h"
#include "fd-util.h"
#include "log.h"
#include "macro.h"
#include "process-util.h"
#include "signal-util.h"
int asynchronous_sync(pid_t *ret_pid) {
int r;
/* This forks off an invocation of fork() as a child process, in order to initiate synchronization to
* disk. Note that we implement this as helper process rather than thread as we don't want the sync() to hang our
* original process ever, and a thread would do that as the process can't exit with threads hanging in blocking
* syscalls. */
r = safe_fork("(sd-sync)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|(ret_pid ? 0 : FORK_DETACH), ret_pid);
if (r < 0)
return r;
if (r == 0) {
/* Child process */
sync();
_exit(EXIT_SUCCESS);
}
return 0;
}
/* We encode the fd to close in the userdata pointer as an unsigned value. The highest bit indicates whether
* we need to fork again */
#define NEED_DOUBLE_FORK (1U << (sizeof(unsigned) * 8 - 1))
static int close_func(void *p) {
unsigned v = PTR_TO_UINT(p);
(void) prctl(PR_SET_NAME, (unsigned long*) "(sd-close)");
/* Note: 💣 This function is invoked in a child process created via glibc's clone() wrapper. In such
* children memory allocation is not allowed, since glibc does not release malloc mutexes in
* clone() 💣 */
if (v & NEED_DOUBLE_FORK) {
pid_t pid;
v &= ~NEED_DOUBLE_FORK;
/* This inner child will be reparented to the subreaper/PID 1. Here we turn on SIGCHLD, so
* that the reaper knows when it's time to reap. */
pid = clone_with_nested_stack(close_func, SIGCHLD|CLONE_FILES, UINT_TO_PTR(v));
if (pid >= 0)
return 0;
}
close((int) v); /* no assert() here, we are in the child and the result would be eaten up anyway */
return 0;
}
int asynchronous_close(int fd) {
unsigned v;
pid_t pid;
int r;
/* This is supposed to behave similar to safe_close(), but actually invoke close() asynchronously, so
* that it will never block. Ideally the kernel would have an API for this, but it doesn't, so we
* work around it, and hide this as a far away as we can.
*
* It is important to us that we don't use threads (via glibc pthread) in PID 1, hence we'll do a
* minimal subprocess instead which shares our fd table via CLONE_FILES. */
if (fd < 0)
return -EBADF; /* already invalid */
PROTECT_ERRNO;
v = (unsigned) fd;
/* We want to fork off a process that is automatically reaped. For that we'd usually double-fork. But
* we can optimize this a bit: if we are PID 1 or a subreaper anyway (the systemd service manager
* process qualifies as this), we can avoid the double forking, since the double forked process would
* be reparented back to us anyway. */
r = is_reaper_process();
if (r < 0)
log_debug_errno(r, "Cannot determine if we are a reaper process, assuming we are not: %m");
if (r <= 0)
v |= NEED_DOUBLE_FORK;
pid = clone_with_nested_stack(close_func, CLONE_FILES | ((v & NEED_DOUBLE_FORK) ? 0 : SIGCHLD), UINT_TO_PTR(v));
if (pid < 0)
assert_se(close_nointr(fd) != -EBADF); /* local fallback */
else if (v & NEED_DOUBLE_FORK) {
/* Reap the intermediate child. Key here is that we specify __WCLONE, since we didn't ask for
* any signal to be sent to us on process exit, and otherwise waitid() would refuse waiting
* then.
*
* We usually prefer calling waitid(), but before kernel 4.7 it didn't support __WCLONE while
* waitpid() did. Hence let's use waitpid() here, it's good enough for our purposes here. */
for (;;)
if (waitpid(pid, NULL, __WCLONE) >= 0 || errno != EINTR)
break;
}
return -EBADF; /* return an invalidated fd */
}
int asynchronous_rm_rf(const char *p, RemoveFlags flags) {
int r;
assert(p);
/* Forks off a child that destroys the specified path. This will be best effort only, i.e. the child
* will attempt to do its thing, but we won't wait for it or check its success. */
r = safe_fork("(sd-rmrf)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DETACH, NULL);
if (r != 0)
return r;
/* Child */
r = rm_rf(p, flags);
if (r < 0) {
log_debug_errno(r, "Failed to rm -rf '%s', ignoring: %m", p);
_exit(EXIT_FAILURE); /* This is a detached process, hence no one really cares, but who knows
* maybe it's good for debugging/tracing to return an exit code
* indicative of our failure here. */
}
_exit(EXIT_SUCCESS);
}
| 5,367 | 37.898551 | 121 |
c
|
null |
systemd-main/src/shared/async.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
#include "macro.h"
#include "rm-rf.h"
/* These functions implement various potentially slow operations that are executed asynchronously. They are
* carefully written to not use pthreads, but use fork() or clone() (without CLONE_VM) so that the child does
* not share any memory with the parent process, and thus cannot possibly interfere with the malloc()
* synchronization locks.
*
* Background: glibc only synchronizes malloc() locks when doing fork(), but not when doing clone()
* (regardless if through glibc's own wrapper or ours). This means if another thread in the parent has the
* malloc() lock taken while a thread is cloning, the mutex will remain locked in the child (but the other
* thread won't exist there), with no chance to ever be unlocked again. This will result in deadlocks. Hence
* one has to make the choice: either never use threads in the parent, or never do memory allocation in the
* child, or never use clone()/clone3() and stick to fork() only. Because we need clone()/clone3() we opted
* for avoiding threads. */
int asynchronous_sync(pid_t *ret_pid);
int asynchronous_close(int fd);
int asynchronous_rm_rf(const char *p, RemoveFlags flags);
DEFINE_TRIVIAL_CLEANUP_FUNC(int, asynchronous_close);
| 1,327 | 48.185185 | 109 |
h
|
null |
systemd-main/src/shared/barrier.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/eventfd.h>
#include <sys/types.h>
#include <unistd.h>
#include "barrier.h"
#include "errno-util.h"
#include "fd-util.h"
#include "io-util.h"
#include "macro.h"
/**
* Barriers
* This barrier implementation provides a simple synchronization method based
* on file-descriptors that can safely be used between threads and processes. A
* barrier object contains 2 shared counters based on eventfd. Both processes
* can now place barriers and wait for the other end to reach a random or
* specific barrier.
* Barriers are numbered, so you can either wait for the other end to reach any
* barrier or the last barrier that you placed. This way, you can use barriers
* for one-way *and* full synchronization. Note that even-though barriers are
* numbered, these numbers are internal and recycled once both sides reached the
* same barrier (implemented as a simple signed counter). It is thus not
* possible to address barriers by their ID.
*
* Barrier-API: Both ends can place as many barriers via barrier_place() as
* they want and each pair of barriers on both sides will be implicitly linked.
* Each side can use the barrier_wait/sync_*() family of calls to wait for the
* other side to place a specific barrier. barrier_wait_next() waits until the
* other side calls barrier_place(). No links between the barriers are
* considered and this simply serves as most basic asynchronous barrier.
* barrier_sync_next() is like barrier_wait_next() and waits for the other side
* to place their next barrier via barrier_place(). However, it only waits for
* barriers that are linked to a barrier we already placed. If the other side
* already placed more barriers than we did, barrier_sync_next() returns
* immediately.
* barrier_sync() extends barrier_sync_next() and waits until the other end
* placed as many barriers via barrier_place() as we did. If they already placed
* as many as we did (or more), it returns immediately.
*
* Additionally to basic barriers, an abortion event is available.
* barrier_abort() places an abortion event that cannot be undone. An abortion
* immediately cancels all placed barriers and replaces them. Any running and
* following wait/sync call besides barrier_wait_abortion() will immediately
* return false on both sides (otherwise, they always return true).
* barrier_abort() can be called multiple times on both ends and will be a
* no-op if already called on this side.
* barrier_wait_abortion() can be used to wait for the other side to call
* barrier_abort() and is the only wait/sync call that does not return
* immediately if we aborted outself. It only returns once the other side
* called barrier_abort().
*
* Barriers can be used for in-process and inter-process synchronization.
* However, for in-process synchronization you could just use mutexes.
* Therefore, main target is IPC and we require both sides to *not* share the FD
* table. If that's given, barriers provide target tracking: If the remote side
* exit()s, an abortion event is implicitly queued on the other side. This way,
* a sync/wait call will be woken up if the remote side crashed or exited
* unexpectedly. However, note that these abortion events are only queued if the
* barrier-queue has been drained. Therefore, it is safe to place a barrier and
* exit. The other side can safely wait on the barrier even though the exit
* queued an abortion event. Usually, the abortion event would overwrite the
* barrier, however, that's not true for exit-abortion events. Those are only
* queued if the barrier-queue is drained (thus, the receiving side has placed
* more barriers than the remote side).
*/
/**
* barrier_create() - Initialize a barrier object
* @obj: barrier to initialize
*
* This initializes a barrier object. The caller is responsible of allocating
* the memory and keeping it valid. The memory does not have to be zeroed
* beforehand.
* Two eventfd objects are allocated for each barrier. If allocation fails, an
* error is returned.
*
* If this function fails, the barrier is reset to an invalid state so it is
* safe to call barrier_destroy() on the object regardless whether the
* initialization succeeded or not.
*
* The caller is responsible to destroy the object via barrier_destroy() before
* releasing the underlying memory.
*
* Returns: 0 on success, negative error code on failure.
*/
int barrier_create(Barrier *b) {
_unused_ _cleanup_(barrier_destroyp) Barrier *staging = b;
assert(b);
b->me = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (b->me < 0)
return -errno;
b->them = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (b->them < 0)
return -errno;
if (pipe2(b->pipe, O_CLOEXEC | O_NONBLOCK) < 0)
return -errno;
staging = NULL;
return 0;
}
/**
* barrier_destroy() - Destroy a barrier object
* @b: barrier to destroy or NULL
*
* This destroys a barrier object that has previously been passed to
* barrier_create(). The object is released and reset to invalid
* state. Therefore, it is safe to call barrier_destroy() multiple
* times or even if barrier_create() failed. However, barrier must be
* always initialized with BARRIER_NULL.
*
* If @b is NULL, this is a no-op.
*/
Barrier* barrier_destroy(Barrier *b) {
if (!b)
return NULL;
b->me = safe_close(b->me);
b->them = safe_close(b->them);
safe_close_pair(b->pipe);
b->barriers = 0;
return NULL;
}
/**
* barrier_set_role() - Set the local role of the barrier
* @b: barrier to operate on
* @role: role to set on the barrier
*
* This sets the roles on a barrier object. This is needed to know
* which side of the barrier you're on. Usually, the parent creates
* the barrier via barrier_create() and then calls fork() or clone().
* Therefore, the FDs are duplicated and the child retains the same
* barrier object.
*
* Both sides need to call barrier_set_role() after fork() or clone()
* are done. If this is not done, barriers will not work correctly.
*
* Note that barriers could be supported without fork() or clone(). However,
* this is currently not needed so it hasn't been implemented.
*/
void barrier_set_role(Barrier *b, unsigned role) {
assert(b);
assert(IN_SET(role, BARRIER_PARENT, BARRIER_CHILD));
/* make sure this is only called once */
assert(b->pipe[0] >= 0 && b->pipe[1] >= 0);
if (role == BARRIER_PARENT)
b->pipe[1] = safe_close(b->pipe[1]);
else {
b->pipe[0] = safe_close(b->pipe[0]);
/* swap me/them for children */
SWAP_TWO(b->me, b->them);
}
}
/* places barrier; returns false if we aborted, otherwise true */
static bool barrier_write(Barrier *b, uint64_t buf) {
ssize_t len;
/* prevent new sync-points if we already aborted */
if (barrier_i_aborted(b))
return false;
assert(b->me >= 0);
do {
len = write(b->me, &buf, sizeof(buf));
} while (len < 0 && ERRNO_IS_TRANSIENT(errno));
if (len != sizeof(buf))
goto error;
/* lock if we aborted */
if (buf >= (uint64_t)BARRIER_ABORTION) {
if (barrier_they_aborted(b))
b->barriers = BARRIER_WE_ABORTED;
else
b->barriers = BARRIER_I_ABORTED;
} else if (!barrier_is_aborted(b))
b->barriers += buf;
return !barrier_i_aborted(b);
error:
/* If there is an unexpected error, we have to make this fatal. There
* is no way we can recover from sync-errors. Therefore, we close the
* pipe-ends and treat this as abortion. The other end will notice the
* pipe-close and treat it as abortion, too. */
safe_close_pair(b->pipe);
b->barriers = BARRIER_WE_ABORTED;
return false;
}
/* waits for barriers; returns false if they aborted, otherwise true */
static bool barrier_read(Barrier *b, int64_t comp) {
if (barrier_they_aborted(b))
return false;
while (b->barriers > comp) {
struct pollfd pfd[2] = {
{ .fd = b->pipe[0] >= 0 ? b->pipe[0] : b->pipe[1],
.events = POLLHUP },
{ .fd = b->them,
.events = POLLIN }};
uint64_t buf;
int r;
r = ppoll_usec(pfd, ELEMENTSOF(pfd), USEC_INFINITY);
if (r == -EINTR)
continue;
if (r < 0)
goto error;
if (pfd[1].revents) {
ssize_t len;
/* events on @them signal new data for us */
len = read(b->them, &buf, sizeof(buf));
if (len < 0 && ERRNO_IS_TRANSIENT(errno))
continue;
if (len != sizeof(buf))
goto error;
} else if (pfd[0].revents & (POLLHUP | POLLERR | POLLNVAL))
/* POLLHUP on the pipe tells us the other side exited.
* We treat this as implicit abortion. But we only
* handle it if there's no event on the eventfd. This
* guarantees that exit-abortions do not overwrite real
* barriers. */
buf = BARRIER_ABORTION;
else
continue;
/* lock if they aborted */
if (buf >= (uint64_t)BARRIER_ABORTION) {
if (barrier_i_aborted(b))
b->barriers = BARRIER_WE_ABORTED;
else
b->barriers = BARRIER_THEY_ABORTED;
} else if (!barrier_is_aborted(b))
b->barriers -= buf;
}
return !barrier_they_aborted(b);
error:
/* If there is an unexpected error, we have to make this fatal. There
* is no way we can recover from sync-errors. Therefore, we close the
* pipe-ends and treat this as abortion. The other end will notice the
* pipe-close and treat it as abortion, too. */
safe_close_pair(b->pipe);
b->barriers = BARRIER_WE_ABORTED;
return false;
}
/**
* barrier_place() - Place a new barrier
* @b: barrier object
*
* This places a new barrier on the barrier object. If either side already
* aborted, this is a no-op and returns "false". Otherwise, the barrier is
* placed and this returns "true".
*
* Returns: true if barrier was placed, false if either side aborted.
*/
bool barrier_place(Barrier *b) {
assert(b);
if (barrier_is_aborted(b))
return false;
barrier_write(b, BARRIER_SINGLE);
return true;
}
/**
* barrier_abort() - Abort the synchronization
* @b: barrier object to abort
*
* This aborts the barrier-synchronization. If barrier_abort() was already
* called on this side, this is a no-op. Otherwise, the barrier is put into the
* ABORT-state and will stay there. The other side is notified about the
* abortion. Any following attempt to place normal barriers or to wait on normal
* barriers will return immediately as "false".
*
* You can wait for the other side to call barrier_abort(), too. Use
* barrier_wait_abortion() for that.
*
* Returns: false if the other side already aborted, true otherwise.
*/
bool barrier_abort(Barrier *b) {
assert(b);
barrier_write(b, BARRIER_ABORTION);
return !barrier_they_aborted(b);
}
/**
* barrier_wait_next() - Wait for the next barrier of the other side
* @b: barrier to operate on
*
* This waits until the other side places its next barrier. This is independent
* of any barrier-links and just waits for any next barrier of the other side.
*
* If either side aborted, this returns false.
*
* Returns: false if either side aborted, true otherwise.
*/
bool barrier_wait_next(Barrier *b) {
assert(b);
if (barrier_is_aborted(b))
return false;
barrier_read(b, b->barriers - 1);
return !barrier_is_aborted(b);
}
/**
* barrier_wait_abortion() - Wait for the other side to abort
* @b: barrier to operate on
*
* This waits until the other side called barrier_abort(). This can be called
* regardless whether the local side already called barrier_abort() or not.
*
* If the other side has already aborted, this returns immediately.
*
* Returns: false if the local side aborted, true otherwise.
*/
bool barrier_wait_abortion(Barrier *b) {
assert(b);
barrier_read(b, BARRIER_THEY_ABORTED);
return !barrier_i_aborted(b);
}
/**
* barrier_sync_next() - Wait for the other side to place a next linked barrier
* @b: barrier to operate on
*
* This is like barrier_wait_next() and waits for the other side to call
* barrier_place(). However, this only waits for linked barriers. That means, if
* the other side already placed more barriers than (or as much as) we did, this
* returns immediately instead of waiting.
*
* If either side aborted, this returns false.
*
* Returns: false if either side aborted, true otherwise.
*/
bool barrier_sync_next(Barrier *b) {
assert(b);
if (barrier_is_aborted(b))
return false;
barrier_read(b, MAX((int64_t)0, b->barriers - 1));
return !barrier_is_aborted(b);
}
/**
* barrier_sync() - Wait for the other side to place as many barriers as we did
* @b: barrier to operate on
*
* This is like barrier_sync_next() but waits for the other side to call
* barrier_place() as often as we did (in total). If they already placed as much
* as we did (or more), this returns immediately instead of waiting.
*
* If either side aborted, this returns false.
*
* Returns: false if either side aborted, true otherwise.
*/
bool barrier_sync(Barrier *b) {
assert(b);
if (barrier_is_aborted(b))
return false;
barrier_read(b, 0);
return !barrier_is_aborted(b);
}
| 14,504 | 35.721519 | 80 |
c
|
null |
systemd-main/src/shared/barrier.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
#include "macro.h"
/* See source file for an API description. */
typedef struct Barrier Barrier;
enum {
BARRIER_SINGLE = 1LL,
BARRIER_ABORTION = INT64_MAX,
/* bias values to store state; keep @WE < @THEY < @I */
BARRIER_BIAS = INT64_MIN,
BARRIER_WE_ABORTED = BARRIER_BIAS + 1LL,
BARRIER_THEY_ABORTED = BARRIER_BIAS + 2LL,
BARRIER_I_ABORTED = BARRIER_BIAS + 3LL,
};
enum {
BARRIER_PARENT,
BARRIER_CHILD,
};
struct Barrier {
int me;
int them;
int pipe[2];
int64_t barriers;
};
#define BARRIER_NULL {-1, -1, {-1, -1}, 0}
int barrier_create(Barrier *obj);
Barrier* barrier_destroy(Barrier *b);
DEFINE_TRIVIAL_CLEANUP_FUNC(Barrier*, barrier_destroy);
void barrier_set_role(Barrier *b, unsigned role);
bool barrier_place(Barrier *b);
bool barrier_abort(Barrier *b);
bool barrier_wait_next(Barrier *b);
bool barrier_wait_abortion(Barrier *b);
bool barrier_sync_next(Barrier *b);
bool barrier_sync(Barrier *b);
static inline bool barrier_i_aborted(Barrier *b) {
return IN_SET(b->barriers, BARRIER_I_ABORTED, BARRIER_WE_ABORTED);
}
static inline bool barrier_they_aborted(Barrier *b) {
return IN_SET(b->barriers, BARRIER_THEY_ABORTED, BARRIER_WE_ABORTED);
}
static inline bool barrier_we_aborted(Barrier *b) {
return b->barriers == BARRIER_WE_ABORTED;
}
static inline bool barrier_is_aborted(Barrier *b) {
return IN_SET(b->barriers,
BARRIER_I_ABORTED, BARRIER_THEY_ABORTED, BARRIER_WE_ABORTED);
}
static inline bool barrier_place_and_sync(Barrier *b) {
(void) barrier_place(b);
return barrier_sync(b);
}
| 1,903 | 24.386667 | 83 |
h
|
null |
systemd-main/src/shared/base-filesystem.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <syslog.h>
#include <unistd.h>
#include "alloc-util.h"
#include "architecture.h"
#include "base-filesystem.h"
#include "errno-util.h"
#include "fd-util.h"
#include "log.h"
#include "macro.h"
#include "nulstr-util.h"
#include "path-util.h"
#include "string-util.h"
#include "umask-util.h"
#include "user-util.h"
typedef struct BaseFilesystem {
const char *dir; /* directory or symlink to create */
mode_t mode;
const char *target; /* if non-NULL create as symlink to this target */
const char *exists; /* conditionalize this entry on existence of this file */
bool ignore_failure;
} BaseFilesystem;
static const BaseFilesystem table[] = {
{ "bin", 0, "usr/bin\0", NULL },
{ "lib", 0, "usr/lib\0", NULL },
{ "root", 0750, NULL, NULL, true },
{ "sbin", 0, "usr/sbin\0", NULL },
{ "usr", 0755, NULL, NULL },
{ "var", 0755, NULL, NULL },
{ "etc", 0755, NULL, NULL },
{ "proc", 0555, NULL, NULL, true },
{ "sys", 0555, NULL, NULL, true },
{ "dev", 0555, NULL, NULL, true },
{ "run", 0555, NULL, NULL, true },
/* We don't add /tmp/ here for now (even though it's necessary for regular operation), because we
* want to support both cases where /tmp/ is a mount of its own (in which case we probably should set
* the mode to 1555, to indicate that no one should write to it, not even root) and when it's part of
* the rootfs (in which case we should set mode 1777), and we simply don't know what's right. */
/* Various architecture ABIs define the path to the dynamic loader via the /lib64/ subdirectory of
* the root directory. When booting from an otherwise empty root file system (where only /usr/ has
* been mounted into) it is thus necessary to create a symlink pointing to the right subdirectory of
* /usr/ first — otherwise we couldn't invoke any dynamic binary. Let's detect this case here, and
* create the symlink as needed should it be missing. We prefer doing this consistently with Debian's
* multiarch logic, but support Fedora-style and Arch-style multilib too. */
#if defined(__aarch64__)
/* aarch64 ELF ABI actually says dynamic loader is in /lib/, but Fedora puts it in /lib64/ anyway and
* just symlinks /lib/ld-linux-aarch64.so.1 to ../lib64/ld-linux-aarch64.so.1. For this to work
* correctly, /lib64/ must be symlinked to /usr/lib64/. */
{ "lib64", 0, "usr/lib/"LIB_ARCH_TUPLE"\0"
"usr/lib64\0"
"usr/lib\0", "ld-linux-aarch64.so.1" },
# define KNOW_LIB64_DIRS 1
#elif defined(__alpha__)
#elif defined(__arc__) || defined(__tilegx__)
#elif defined(__arm__)
/* No /lib64 on arm. The linker is /lib/ld-linux-armhf.so.3. */
# define KNOW_LIB64_DIRS 1
#elif defined(__i386__) || defined(__x86_64__)
{ "lib64", 0, "usr/lib/"LIB_ARCH_TUPLE"\0"
"usr/lib64\0"
"usr/lib\0", "ld-linux-x86-64.so.2" },
# define KNOW_LIB64_DIRS 1
#elif defined(__ia64__)
#elif defined(__loongarch64)
# define KNOW_LIB64_DIRS 1
# if defined(__loongarch_double_float)
{ "lib64", 0, "usr/lib/"LIB_ARCH_TUPLE"\0"
"usr/lib64\0"
"usr/lib\0", "ld-linux-loongarch-lp64d.so.1" },
# elif defined(__loongarch_single_float)
{ "lib64", 0, "usr/lib/"LIB_ARCH_TUPLE"\0"
"usr/lib64\0"
"usr/lib\0", "ld-linux-loongarch-lp64f.so.1" },
# elif defined(__loongarch_soft_float)
{ "lib64", 0, "usr/lib/"LIB_ARCH_TUPLE"\0"
"usr/lib64\0"
"usr/lib\0", "ld-linux-loongarch-lp64s.so.1" },
# else
# error "Unknown LoongArch ABI"
# endif
#elif defined(__m68k__)
/* No link needed. */
# define KNOW_LIB64_DIRS 1
#elif defined(_MIPS_SIM)
# if _MIPS_SIM == _MIPS_SIM_ABI32
# elif _MIPS_SIM == _MIPS_SIM_NABI32
# elif _MIPS_SIM == _MIPS_SIM_ABI64
# else
# error "Unknown MIPS ABI"
# endif
#elif defined(__powerpc__)
# if defined(__PPC64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
{ "lib64", 0, "usr/lib/"LIB_ARCH_TUPLE"\0"
"usr/lib64\0"
"usr/lib\0", "ld64.so.2" },
# define KNOW_LIB64_DIRS 1
# elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
/* powerpc64-linux-gnu */
# else
/* powerpc-linux-gnu */
# endif
#elif defined(__riscv)
# if __riscv_xlen == 32
# elif __riscv_xlen == 64
/* Same situation as for aarch64 */
{ "lib64", 0, "usr/lib/"LIB_ARCH_TUPLE"\0"
"usr/lib64\0"
"usr/lib\0", "ld-linux-riscv64-lp64d.so.1" },
# define KNOW_LIB64_DIRS 1
# else
# error "Unknown RISC-V ABI"
# endif
#elif defined(__s390__)
/* s390-linux-gnu */
#elif defined(__s390x__)
{ "lib64", 0, "usr/lib/"LIB_ARCH_TUPLE"\0"
"usr/lib64\0"
"usr/lib\0", "ld-lsb-s390x.so.3" },
# define KNOW_LIB64_DIRS 1
#elif defined(__sparc__)
#endif
/* gcc doesn't allow pragma to be used within constructs, hence log about this separately below */
};
#ifndef KNOW_LIB64_DIRS
# pragma message "Please add an entry above specifying whether your architecture uses /lib64/, /lib32/, or no such links."
#endif
int base_filesystem_create_fd(int fd, const char *root, uid_t uid, gid_t gid) {
int r;
assert(fd >= 0);
assert(root);
/* The "root" parameter is decoration only – it's only used as part of log messages */
for (size_t i = 0; i < ELEMENTSOF(table); i++) {
if (faccessat(fd, table[i].dir, F_OK, AT_SYMLINK_NOFOLLOW) >= 0)
continue;
if (table[i].target) { /* Create as symlink? */
const char *target = NULL;
/* check if one of the targets exists */
NULSTR_FOREACH(s, table[i].target) {
if (faccessat(fd, s, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
continue;
/* check if a specific file exists at the target path */
if (table[i].exists) {
_cleanup_free_ char *p = NULL;
p = path_join(s, table[i].exists);
if (!p)
return log_oom();
if (faccessat(fd, p, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
continue;
}
target = s;
break;
}
if (!target)
continue;
r = RET_NERRNO(symlinkat(target, fd, table[i].dir));
} else {
/* Create as directory. */
WITH_UMASK(0000)
r = RET_NERRNO(mkdirat(fd, table[i].dir, table[i].mode));
}
if (r < 0) {
bool ignore = IN_SET(r, -EEXIST, -EROFS) || table[i].ignore_failure;
log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, r,
"Failed to create %s/%s: %m", root, table[i].dir);
if (ignore)
continue;
return r;
}
if (uid_is_valid(uid) || gid_is_valid(gid))
if (fchownat(fd, table[i].dir, uid, gid, AT_SYMLINK_NOFOLLOW) < 0)
return log_error_errno(errno, "Failed to chown %s/%s: %m", root, table[i].dir);
}
return 0;
}
int base_filesystem_create(const char *root, uid_t uid, gid_t gid) {
_cleanup_close_ int fd = -EBADF;
fd = open(ASSERT_PTR(root), O_DIRECTORY|O_CLOEXEC);
if (fd < 0)
return log_error_errno(errno, "Failed to open root file system: %m");
return base_filesystem_create_fd(fd, root, uid, gid);
}
| 8,965 | 41.492891 | 123 |
c
|
null |
systemd-main/src/shared/binfmt-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/vfs.h>
#include "binfmt-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "missing_magic.h"
#include "stat-util.h"
int binfmt_mounted(void) {
_cleanup_close_ int fd = -EBADF;
int r;
fd = RET_NERRNO(open("/proc/sys/fs/binfmt_misc", O_CLOEXEC | O_DIRECTORY | O_PATH));
if (fd == -ENOENT)
return false;
if (fd < 0)
return fd;
r = fd_is_fs_type(fd, BINFMTFS_MAGIC);
if (r <= 0)
return r;
return access_fd(fd, W_OK) >= 0;
}
int disable_binfmt(void) {
int r;
/* Flush out all rules. This is important during shutdown to cover for rules using "F", since those
* might pin a file and thus block us from unmounting stuff cleanly.
*
* We are a bit careful here, since binfmt_misc might still be an autofs which we don't want to
* trigger. */
r = binfmt_mounted();
if (r < 0)
return log_warning_errno(r, "Failed to determine whether binfmt_misc is mounted: %m");
if (r == 0) {
log_debug("binfmt_misc is not mounted in read-write mode, not detaching entries.");
return 0;
}
r = write_string_file("/proc/sys/fs/binfmt_misc/status", "-1", WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0)
return log_warning_errno(r, "Failed to unregister binfmt_misc entries: %m");
log_debug("Unregistered all remaining binfmt_misc entries.");
return 0;
}
| 1,688 | 29.160714 | 107 |
c
|
null |
systemd-main/src/shared/bitmap.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "alloc-util.h"
#include "bitmap.h"
#include "hashmap.h"
#include "macro.h"
#include "memory-util.h"
/* Bitmaps are only meant to store relatively small numbers
* (corresponding to, say, an enum), so it is ok to limit
* the max entry. 64k should be plenty. */
#define BITMAPS_MAX_ENTRY 0xffff
/* This indicates that we reached the end of the bitmap */
#define BITMAP_END (UINT_MAX)
#define BITMAP_NUM_TO_OFFSET(n) ((n) / (sizeof(uint64_t) * 8))
#define BITMAP_NUM_TO_REM(n) ((n) % (sizeof(uint64_t) * 8))
#define BITMAP_OFFSET_TO_NUM(offset, rem) ((offset) * sizeof(uint64_t) * 8 + (rem))
Bitmap* bitmap_new(void) {
return new0(Bitmap, 1);
}
Bitmap* bitmap_copy(Bitmap *b) {
Bitmap *ret;
ret = bitmap_new();
if (!ret)
return NULL;
ret->bitmaps = newdup(uint64_t, b->bitmaps, b->n_bitmaps);
if (!ret->bitmaps)
return mfree(ret);
ret->n_bitmaps = b->n_bitmaps;
return ret;
}
Bitmap* bitmap_free(Bitmap *b) {
if (!b)
return NULL;
free(b->bitmaps);
return mfree(b);
}
int bitmap_ensure_allocated(Bitmap **b) {
Bitmap *a;
assert(b);
if (*b)
return 0;
a = bitmap_new();
if (!a)
return -ENOMEM;
*b = a;
return 0;
}
int bitmap_set(Bitmap *b, unsigned n) {
uint64_t bitmask;
unsigned offset;
assert(b);
/* we refuse to allocate huge bitmaps */
if (n > BITMAPS_MAX_ENTRY)
return -ERANGE;
offset = BITMAP_NUM_TO_OFFSET(n);
if (offset >= b->n_bitmaps) {
if (!GREEDY_REALLOC0(b->bitmaps, offset + 1))
return -ENOMEM;
b->n_bitmaps = offset + 1;
}
bitmask = UINT64_C(1) << BITMAP_NUM_TO_REM(n);
b->bitmaps[offset] |= bitmask;
return 0;
}
void bitmap_unset(Bitmap *b, unsigned n) {
uint64_t bitmask;
unsigned offset;
if (!b)
return;
offset = BITMAP_NUM_TO_OFFSET(n);
if (offset >= b->n_bitmaps)
return;
bitmask = UINT64_C(1) << BITMAP_NUM_TO_REM(n);
b->bitmaps[offset] &= ~bitmask;
}
bool bitmap_isset(const Bitmap *b, unsigned n) {
uint64_t bitmask;
unsigned offset;
if (!b)
return false;
offset = BITMAP_NUM_TO_OFFSET(n);
if (offset >= b->n_bitmaps)
return false;
bitmask = UINT64_C(1) << BITMAP_NUM_TO_REM(n);
return !!(b->bitmaps[offset] & bitmask);
}
bool bitmap_isclear(const Bitmap *b) {
unsigned i;
if (!b)
return true;
for (i = 0; i < b->n_bitmaps; i++)
if (b->bitmaps[i] != 0)
return false;
return true;
}
void bitmap_clear(Bitmap *b) {
if (!b)
return;
b->bitmaps = mfree(b->bitmaps);
b->n_bitmaps = 0;
}
bool bitmap_iterate(const Bitmap *b, Iterator *i, unsigned *n) {
uint64_t bitmask;
unsigned offset, rem;
assert(i);
assert(n);
if (!b || i->idx == BITMAP_END)
return false;
offset = BITMAP_NUM_TO_OFFSET(i->idx);
rem = BITMAP_NUM_TO_REM(i->idx);
bitmask = UINT64_C(1) << rem;
for (; offset < b->n_bitmaps; offset ++) {
if (b->bitmaps[offset]) {
for (; bitmask; bitmask <<= 1, rem ++) {
if (b->bitmaps[offset] & bitmask) {
*n = BITMAP_OFFSET_TO_NUM(offset, rem);
i->idx = *n + 1;
return true;
}
}
}
rem = 0;
bitmask = 1;
}
i->idx = BITMAP_END;
return false;
}
bool bitmap_equal(const Bitmap *a, const Bitmap *b) {
size_t common_n_bitmaps;
const Bitmap *c;
unsigned i;
if (a == b)
return true;
if (!a != !b)
return false;
if (!a)
return true;
common_n_bitmaps = MIN(a->n_bitmaps, b->n_bitmaps);
if (memcmp_safe(a->bitmaps, b->bitmaps, sizeof(uint64_t) * common_n_bitmaps) != 0)
return false;
c = a->n_bitmaps > b->n_bitmaps ? a : b;
for (i = common_n_bitmaps; i < c->n_bitmaps; i++)
if (c->bitmaps[i] != 0)
return false;
return true;
}
| 4,862 | 21.938679 | 90 |
c
|
null |
systemd-main/src/shared/bitmap.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "hashmap.h"
#include "macro.h"
typedef struct Bitmap {
uint64_t *bitmaps;
size_t n_bitmaps;
} Bitmap;
Bitmap* bitmap_new(void);
Bitmap* bitmap_copy(Bitmap *b);
int bitmap_ensure_allocated(Bitmap **b);
Bitmap* bitmap_free(Bitmap *b);
int bitmap_set(Bitmap *b, unsigned n);
void bitmap_unset(Bitmap *b, unsigned n);
bool bitmap_isset(const Bitmap *b, unsigned n);
bool bitmap_isclear(const Bitmap *b);
void bitmap_clear(Bitmap *b);
bool bitmap_iterate(const Bitmap *b, Iterator *i, unsigned *n);
bool bitmap_equal(const Bitmap *a, const Bitmap *b);
#define _BITMAP_FOREACH(n, b, i) \
for (Iterator i = {}; bitmap_iterate((b), &i, (unsigned*)&(n)); )
#define BITMAP_FOREACH(n, b) \
_BITMAP_FOREACH(n, b, UNIQ_T(i, UNIQ))
DEFINE_TRIVIAL_CLEANUP_FUNC(Bitmap*, bitmap_free);
#define _cleanup_bitmap_free_ _cleanup_(bitmap_freep)
| 957 | 24.891892 | 73 |
h
|
null |
systemd-main/src/shared/blkid-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if HAVE_BLKID
# include <blkid.h>
# include "sd-id128.h"
# include "macro.h"
# include "string-util.h"
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(blkid_probe, blkid_free_probe, NULL);
static inline int blkid_partition_get_uuid_id128(blkid_partition p, sd_id128_t *ret) {
const char *s;
assert(p);
s = blkid_partition_get_uuid(p);
if (isempty(s))
return -ENXIO;
return sd_id128_from_string(s, ret);
}
static inline int blkid_partition_get_type_id128(blkid_partition p, sd_id128_t *ret) {
const char *s;
assert(p);
s = blkid_partition_get_type_string(p);
if (isempty(s))
return -ENXIO;
return sd_id128_from_string(s, ret);
}
/* Define symbolic names for blkid_do_safeprobe() return values, since blkid only uses literal numbers. We
* prefix these symbolic definitions with underscores, to not invade libblkid's namespace needlessly. */
enum {
_BLKID_SAFEPROBE_FOUND = 0,
_BLKID_SAFEPROBE_NOT_FOUND = 1,
_BLKID_SAFEPROBE_AMBIGUOUS = -2,
_BLKID_SAFEPROBE_ERROR = -1,
};
#endif
| 1,199 | 24 | 106 |
h
|
null |
systemd-main/src/shared/blockdev-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <linux/blkpg.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <unistd.h>
#include "sd-device.h"
#include "alloc-util.h"
#include "blockdev-util.h"
#include "btrfs-util.h"
#include "device-util.h"
#include "devnum-util.h"
#include "dirent-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "missing_magic.h"
#include "parse-util.h"
static int fd_get_devnum(int fd, BlockDeviceLookupFlag flags, dev_t *ret) {
struct stat st;
dev_t devnum;
int r;
assert(fd >= 0);
assert(ret);
if (fstat(fd, &st) < 0)
return -errno;
if (S_ISBLK(st.st_mode))
devnum = st.st_rdev;
else if (!FLAGS_SET(flags, BLOCK_DEVICE_LOOKUP_BACKING))
return -ENOTBLK;
else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
return -ENOTBLK;
else if (major(st.st_dev) != 0)
devnum = st.st_dev;
else {
/* If major(st.st_dev) is zero, this might mean we are backed by btrfs, which needs special
* handing, to get the backing device node. */
r = btrfs_get_block_device_fd(fd, &devnum);
if (r == -ENOTTY) /* not btrfs */
return -ENOTBLK;
if (r < 0)
return r;
}
*ret = devnum;
return 0;
}
int block_device_is_whole_disk(sd_device *dev) {
const char *s;
int r;
assert(dev);
r = sd_device_get_subsystem(dev, &s);
if (r < 0)
return r;
if (!streq(s, "block"))
return -ENOTBLK;
r = sd_device_get_devtype(dev, &s);
if (r < 0)
return r;
return streq(s, "disk");
}
int block_device_get_whole_disk(sd_device *dev, sd_device **ret) {
int r;
assert(dev);
assert(ret);
/* Do not unref returned sd_device object. */
r = block_device_is_whole_disk(dev);
if (r < 0)
return r;
if (r == 0) {
r = sd_device_get_parent(dev, &dev);
if (r == -ENOENT) /* Already removed? Let's return a recognizable error. */
return -ENODEV;
if (r < 0)
return r;
r = block_device_is_whole_disk(dev);
if (r < 0)
return r;
if (r == 0)
return -ENXIO;
}
*ret = dev;
return 0;
}
static int block_device_get_originating(sd_device *dev, sd_device **ret) {
_cleanup_(sd_device_unrefp) sd_device *first_found = NULL;
const char *suffix;
dev_t devnum = 0; /* avoid false maybe-uninitialized warning */
/* For the specified block device tries to chase it through the layers, in case LUKS-style DM
* stacking is used, trying to find the next underlying layer. */
assert(dev);
assert(ret);
FOREACH_DEVICE_CHILD_WITH_SUFFIX(dev, child, suffix) {
sd_device *child_whole_disk;
dev_t n;
if (!path_startswith(suffix, "slaves"))
continue;
if (block_device_get_whole_disk(child, &child_whole_disk) < 0)
continue;
if (sd_device_get_devnum(child_whole_disk, &n) < 0)
continue;
if (!first_found) {
first_found = sd_device_ref(child);
devnum = n;
continue;
}
/* We found a device backed by multiple other devices. We don't really support automatic
* discovery on such setups, with the exception of dm-verity partitions. In this case there
* are two backing devices: the data partition and the hash partition. We are fine with such
* setups, however, only if both partitions are on the same physical device. Hence, let's
* verify this by iterating over every node in the 'slaves/' directory and comparing them with
* the first that gets returned by readdir(), to ensure they all point to the same device. */
if (n != devnum)
return -ENOTUNIQ;
}
if (!first_found)
return -ENOENT;
*ret = TAKE_PTR(first_found);
return 1; /* found */
}
int block_device_new_from_fd(int fd, BlockDeviceLookupFlag flags, sd_device **ret) {
_cleanup_(sd_device_unrefp) sd_device *dev = NULL;
dev_t devnum;
int r;
assert(fd >= 0);
assert(ret);
r = fd_get_devnum(fd, flags, &devnum);
if (r < 0)
return r;
r = sd_device_new_from_devnum(&dev, 'b', devnum);
if (r < 0)
return r;
if (FLAGS_SET(flags, BLOCK_DEVICE_LOOKUP_ORIGINATING)) {
_cleanup_(sd_device_unrefp) sd_device *dev_origin = NULL;
sd_device *dev_whole_disk;
r = block_device_get_whole_disk(dev, &dev_whole_disk);
if (r < 0)
return r;
r = block_device_get_originating(dev_whole_disk, &dev_origin);
if (r < 0 && r != -ENOENT)
return r;
if (r > 0)
device_unref_and_replace(dev, dev_origin);
}
if (FLAGS_SET(flags, BLOCK_DEVICE_LOOKUP_WHOLE_DISK)) {
sd_device *dev_whole_disk;
r = block_device_get_whole_disk(dev, &dev_whole_disk);
if (r < 0)
return r;
*ret = sd_device_ref(dev_whole_disk);
return 0;
}
*ret = sd_device_ref(dev);
return 0;
}
int block_device_new_from_path(const char *path, BlockDeviceLookupFlag flags, sd_device **ret) {
_cleanup_close_ int fd = -EBADF;
assert(path);
assert(ret);
fd = open(path, O_CLOEXEC|O_PATH);
if (fd < 0)
return -errno;
return block_device_new_from_fd(fd, flags, ret);
}
int block_get_whole_disk(dev_t d, dev_t *ret) {
char p[SYS_BLOCK_PATH_MAX("/partition")];
_cleanup_free_ char *s = NULL;
dev_t devt;
int r;
assert(ret);
if (major(d) == 0)
return -ENODEV;
/* If it has a queue this is good enough for us */
xsprintf_sys_block_path(p, "/queue", d);
if (access(p, F_OK) >= 0) {
*ret = d;
return 0;
}
if (errno != ENOENT)
return -errno;
/* If it is a partition find the originating device */
xsprintf_sys_block_path(p, "/partition", d);
if (access(p, F_OK) < 0)
return -errno;
/* Get parent dev_t */
xsprintf_sys_block_path(p, "/../dev", d);
r = read_one_line_file(p, &s);
if (r < 0)
return r;
r = parse_devnum(s, &devt);
if (r < 0)
return r;
/* Only return this if it is really good enough for us. */
xsprintf_sys_block_path(p, "/queue", devt);
if (access(p, F_OK) < 0)
return -errno;
*ret = devt;
return 1;
}
int get_block_device_fd(int fd, dev_t *ret) {
struct stat st;
int r;
assert(fd >= 0);
assert(ret);
/* Gets the block device directly backing a file system. If the block device is encrypted, returns
* the device mapper block device. */
if (fstat(fd, &st))
return -errno;
if (major(st.st_dev) != 0) {
*ret = st.st_dev;
return 1;
}
r = btrfs_get_block_device_fd(fd, ret);
if (r > 0)
return 1;
if (r != -ENOTTY) /* not btrfs */
return r;
*ret = 0;
return 0;
}
int get_block_device(const char *path, dev_t *ret) {
_cleanup_close_ int fd = -EBADF;
assert(path);
assert(ret);
fd = open(path, O_RDONLY|O_NOFOLLOW|O_CLOEXEC);
if (fd < 0)
return -errno;
return get_block_device_fd(fd, ret);
}
int block_get_originating(dev_t dt, dev_t *ret) {
_cleanup_(sd_device_unrefp) sd_device *dev = NULL, *origin = NULL;
int r;
assert(ret);
r = sd_device_new_from_devnum(&dev, 'b', dt);
if (r < 0)
return r;
r = block_device_get_originating(dev, &origin);
if (r < 0)
return r;
return sd_device_get_devnum(origin, ret);
}
int get_block_device_harder_fd(int fd, dev_t *ret) {
int r;
assert(fd >= 0);
assert(ret);
/* Gets the backing block device for a file system, and handles LUKS encrypted file systems, looking for its
* immediate parent, if there is one. */
r = get_block_device_fd(fd, ret);
if (r <= 0)
return r;
r = block_get_originating(*ret, ret);
if (r < 0)
log_debug_errno(r, "Failed to chase block device, ignoring: %m");
return 1;
}
int get_block_device_harder(const char *path, dev_t *ret) {
_cleanup_close_ int fd = -EBADF;
assert(path);
assert(ret);
fd = open(path, O_RDONLY|O_NOFOLLOW|O_CLOEXEC);
if (fd < 0)
return -errno;
return get_block_device_harder_fd(fd, ret);
}
int lock_whole_block_device(dev_t devt, int operation) {
_cleanup_close_ int lock_fd = -EBADF;
dev_t whole_devt;
int r;
/* Let's get a BSD file lock on the whole block device, as per: https://systemd.io/BLOCK_DEVICE_LOCKING */
r = block_get_whole_disk(devt, &whole_devt);
if (r < 0)
return r;
lock_fd = r = device_open_from_devnum(S_IFBLK, whole_devt, O_RDONLY|O_CLOEXEC|O_NONBLOCK, NULL);
if (r < 0)
return r;
if (flock(lock_fd, operation) < 0)
return -errno;
return TAKE_FD(lock_fd);
}
int blockdev_partscan_enabled(int fd) {
_cleanup_free_ char *p = NULL, *buf = NULL;
unsigned long long ull;
struct stat st;
int r;
/* Checks if partition scanning is correctly enabled on the block device */
if (fstat(fd, &st) < 0)
return -errno;
if (!S_ISBLK(st.st_mode))
return -ENOTBLK;
if (asprintf(&p, "/sys/dev/block/%u:%u/capability", major(st.st_rdev), minor(st.st_rdev)) < 0)
return -ENOMEM;
r = read_one_line_file(p, &buf);
if (r == -ENOENT) /* If the capability file doesn't exist then we are most likely looking at a
* partition block device, not the whole block device. And that means we have no
* partition scanning on for it (we do for its parent, but not for the partition
* itself). */
return false;
if (r < 0)
return r;
r = safe_atollu_full(buf, 16, &ull);
if (r < 0)
return r;
#ifndef GENHD_FL_NO_PART_SCAN
#define GENHD_FL_NO_PART_SCAN (0x0200)
#endif
return !FLAGS_SET(ull, GENHD_FL_NO_PART_SCAN);
}
static int blockdev_is_encrypted(const char *sysfs_path, unsigned depth_left) {
_cleanup_free_ char *p = NULL, *uuids = NULL;
_cleanup_closedir_ DIR *d = NULL;
int r, found_encrypted = false;
assert(sysfs_path);
if (depth_left == 0)
return -EINVAL;
p = path_join(sysfs_path, "dm/uuid");
if (!p)
return -ENOMEM;
r = read_one_line_file(p, &uuids);
if (r != -ENOENT) {
if (r < 0)
return r;
/* The DM device's uuid attribute is prefixed with "CRYPT-" if this is a dm-crypt device. */
if (startswith(uuids, "CRYPT-"))
return true;
}
/* Not a dm-crypt device itself. But maybe it is on top of one? Follow the links in the "slaves/"
* subdir. */
p = mfree(p);
p = path_join(sysfs_path, "slaves");
if (!p)
return -ENOMEM;
d = opendir(p);
if (!d) {
if (errno == ENOENT) /* Doesn't have underlying devices */
return false;
return -errno;
}
for (;;) {
_cleanup_free_ char *q = NULL;
struct dirent *de;
errno = 0;
de = readdir_no_dot(d);
if (!de) {
if (errno != 0)
return -errno;
break; /* No more underlying devices */
}
q = path_join(p, de->d_name);
if (!q)
return -ENOMEM;
r = blockdev_is_encrypted(q, depth_left - 1);
if (r < 0)
return r;
if (r == 0) /* we found one that is not encrypted? then propagate that immediately */
return false;
found_encrypted = true;
}
return found_encrypted;
}
int fd_is_encrypted(int fd) {
char p[SYS_BLOCK_PATH_MAX(NULL)];
dev_t devt;
int r;
r = get_block_device_fd(fd, &devt);
if (r < 0)
return r;
if (r == 0) /* doesn't have a block device */
return false;
xsprintf_sys_block_path(p, NULL, devt);
return blockdev_is_encrypted(p, 10 /* safety net: maximum recursion depth */);
}
int path_is_encrypted(const char *path) {
char p[SYS_BLOCK_PATH_MAX(NULL)];
dev_t devt;
int r;
r = get_block_device(path, &devt);
if (r < 0)
return r;
if (r == 0) /* doesn't have a block device */
return false;
xsprintf_sys_block_path(p, NULL, devt);
return blockdev_is_encrypted(p, 10 /* safety net: maximum recursion depth */);
}
int fd_get_whole_disk(int fd, bool backing, dev_t *ret) {
dev_t devt;
int r;
assert(fd >= 0);
assert(ret);
r = fd_get_devnum(fd, backing ? BLOCK_DEVICE_LOOKUP_BACKING : 0, &devt);
if (r < 0)
return r;
return block_get_whole_disk(devt, ret);
}
int path_get_whole_disk(const char *path, bool backing, dev_t *ret) {
_cleanup_close_ int fd = -EBADF;
fd = open(path, O_CLOEXEC|O_PATH);
if (fd < 0)
return -errno;
return fd_get_whole_disk(fd, backing, ret);
}
int block_device_add_partition(
int fd,
const char *name,
int nr,
uint64_t start,
uint64_t size) {
assert(fd >= 0);
assert(name);
assert(nr > 0);
struct blkpg_partition bp = {
.pno = nr,
.start = start,
.length = size,
};
struct blkpg_ioctl_arg ba = {
.op = BLKPG_ADD_PARTITION,
.data = &bp,
.datalen = sizeof(bp),
};
if (strlen(name) >= sizeof(bp.devname))
return -EINVAL;
strcpy(bp.devname, name);
return RET_NERRNO(ioctl(fd, BLKPG, &ba));
}
int block_device_remove_partition(
int fd,
const char *name,
int nr) {
assert(fd >= 0);
assert(name);
assert(nr > 0);
struct blkpg_partition bp = {
.pno = nr,
};
struct blkpg_ioctl_arg ba = {
.op = BLKPG_DEL_PARTITION,
.data = &bp,
.datalen = sizeof(bp),
};
if (strlen(name) >= sizeof(bp.devname))
return -EINVAL;
strcpy(bp.devname, name);
return RET_NERRNO(ioctl(fd, BLKPG, &ba));
}
int block_device_resize_partition(
int fd,
int nr,
uint64_t start,
uint64_t size) {
assert(fd >= 0);
assert(nr > 0);
struct blkpg_partition bp = {
.pno = nr,
.start = start,
.length = size,
};
struct blkpg_ioctl_arg ba = {
.op = BLKPG_RESIZE_PARTITION,
.data = &bp,
.datalen = sizeof(bp),
};
return RET_NERRNO(ioctl(fd, BLKPG, &ba));
}
int partition_enumerator_new(sd_device *dev, sd_device_enumerator **ret) {
_cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
const char *s;
int r;
assert(dev);
assert(ret);
/* Refuse invocation on partition block device, insist on "whole" device */
r = block_device_is_whole_disk(dev);
if (r < 0)
return r;
if (r == 0)
return -ENXIO; /* return a recognizable error */
r = sd_device_enumerator_new(&e);
if (r < 0)
return r;
r = sd_device_enumerator_allow_uninitialized(e);
if (r < 0)
return r;
r = sd_device_enumerator_add_match_parent(e, dev);
if (r < 0)
return r;
r = sd_device_get_sysname(dev, &s);
if (r < 0)
return r;
/* Also add sysname check for safety. Hopefully, this also improves performance. */
s = strjoina(s, "*");
r = sd_device_enumerator_add_match_sysname(e, s);
if (r < 0)
return r;
r = sd_device_enumerator_add_match_subsystem(e, "block", /* match = */ true);
if (r < 0)
return r;
r = sd_device_enumerator_add_match_property(e, "DEVTYPE", "partition");
if (r < 0)
return r;
*ret = TAKE_PTR(e);
return 0;
}
int block_device_remove_all_partitions(sd_device *dev, int fd) {
_cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
_cleanup_(sd_device_unrefp) sd_device *dev_unref = NULL;
_cleanup_close_ int fd_close = -EBADF;
bool has_partitions = false;
int r, k = 0;
assert(dev || fd >= 0);
if (!dev) {
r = block_device_new_from_fd(fd, 0, &dev_unref);
if (r < 0)
return r;
dev = dev_unref;
}
r = partition_enumerator_new(dev, &e);
if (r < 0)
return r;
if (fd < 0) {
fd_close = sd_device_open(dev, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_RDONLY);
if (fd_close < 0)
return fd_close;
fd = fd_close;
}
FOREACH_DEVICE(e, part) {
const char *v, *devname;
int nr;
has_partitions = true;
r = sd_device_get_devname(part, &devname);
if (r < 0)
return r;
r = sd_device_get_property_value(part, "PARTN", &v);
if (r < 0)
return r;
r = safe_atoi(v, &nr);
if (r < 0)
return r;
r = btrfs_forget_device(devname);
if (r < 0 && r != -ENOENT)
log_debug_errno(r, "Failed to forget btrfs device %s, ignoring: %m", devname);
r = block_device_remove_partition(fd, devname, nr);
if (r == -ENODEV) {
log_debug("Kernel removed partition %s before us, ignoring", devname);
continue;
}
if (r < 0) {
log_debug_errno(r, "Failed to remove partition %s: %m", devname);
k = k < 0 ? k : r;
continue;
}
log_debug("Removed partition %s", devname);
}
return k < 0 ? k : has_partitions;
}
int block_device_has_partitions(sd_device *dev) {
_cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
int r;
assert(dev);
/* Checks if the specified device currently has partitions. */
r = partition_enumerator_new(dev, &e);
if (r < 0)
return r;
return !!sd_device_enumerator_get_device_first(e);
}
int blockdev_reread_partition_table(sd_device *dev) {
_cleanup_close_ int fd = -EBADF;
assert(dev);
/* Try to re-read the partition table. This only succeeds if none of the devices is busy. */
fd = sd_device_open(dev, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
if (fd < 0)
return fd;
if (flock(fd, LOCK_EX|LOCK_NB) < 0)
return -errno;
if (ioctl(fd, BLKRRPART, 0) < 0)
return -errno;
return 0;
}
int blockdev_get_sector_size(int fd, uint32_t *ret) {
int ssz = 0;
assert(fd >= 0);
assert(ret);
if (ioctl(fd, BLKSSZGET, &ssz) < 0)
return -errno;
if (ssz <= 0) /* make sure the field is initialized */
return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Block device reported invalid sector size %i.", ssz);
*ret = ssz;
return 0;
}
int blockdev_get_root(int level, dev_t *ret) {
_cleanup_free_ char *p = NULL;
dev_t devno;
int r;
/* Returns the device node backing the root file system. Traces through
* dm-crypt/dm-verity/... Returns > 0 and the devno of the device on success. If there's no block
* device (or multiple) returns 0 and a devno of 0. Failure otherwise.
*
* If the root mount has been replaced by some form of volatile file system (overlayfs), the original
* root block device node is symlinked in /run/systemd/volatile-root. Let's read that here. */
r = readlink_malloc("/run/systemd/volatile-root", &p);
if (r == -ENOENT) { /* volatile-root not found */
r = get_block_device_harder("/", &devno);
if (r == -EUCLEAN)
return btrfs_log_dev_root(level, r, "root file system");
if (r < 0)
return log_full_errno(level, r, "Failed to determine block device of root file system: %m");
if (r == 0) { /* Not backed by a single block device. (Could be NFS or so, or could be multi-device RAID or so) */
r = get_block_device_harder("/usr", &devno);
if (r == -EUCLEAN)
return btrfs_log_dev_root(level, r, "/usr");
if (r < 0)
return log_full_errno(level, r, "Failed to determine block device of /usr/ file system: %m");
if (r == 0) { /* /usr/ not backed by single block device, either. */
log_debug("Neither root nor /usr/ file system are on a (single) block device.");
if (ret)
*ret = 0;
return 0;
}
}
} else if (r < 0)
return log_full_errno(level, r, "Failed to read symlink /run/systemd/volatile-root: %m");
else {
mode_t m;
r = device_path_parse_major_minor(p, &m, &devno);
if (r < 0)
return log_full_errno(level, r, "Failed to parse major/minor device node: %m");
if (!S_ISBLK(m))
return log_full_errno(level, SYNTHETIC_ERRNO(ENOTBLK), "Volatile root device is of wrong type.");
}
if (ret)
*ret = devno;
return 1;
}
| 24,328 | 28.347407 | 130 |
c
|
null |
systemd-main/src/shared/blockdev-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
#include "sd-device.h"
#include "macro.h"
#include "stdio-util.h"
#include "string-util.h"
#define SYS_BLOCK_PATH_MAX(suffix) \
(STRLEN("/sys/dev/block/") + DECIMAL_STR_MAX(dev_t) + 1 + DECIMAL_STR_MAX(dev_t) + strlen_ptr(suffix))
#define xsprintf_sys_block_path(buf, suffix, devno) \
xsprintf(buf, "/sys/dev/block/%u:%u%s", major(devno), minor(devno), strempty(suffix))
typedef enum BlockDeviceLookupFlag {
BLOCK_DEVICE_LOOKUP_WHOLE_DISK = 1 << 0, /* whole block device, e.g. sda, nvme0n1, or loop0. */
BLOCK_DEVICE_LOOKUP_BACKING = 1 << 1, /* fd may be regular file or directory on file system, in
* which case backing block device is determined. */
BLOCK_DEVICE_LOOKUP_ORIGINATING = 1 << 2, /* Try to find the underlying layer device for stacked
* block device, e.g. LUKS-style DM. */
} BlockDeviceLookupFlag;
int block_device_new_from_fd(int fd, BlockDeviceLookupFlag flag, sd_device **ret);
int block_device_new_from_path(const char *path, BlockDeviceLookupFlag flag, sd_device **ret);
int block_device_is_whole_disk(sd_device *dev);
int block_device_get_whole_disk(sd_device *dev, sd_device **ret);
int block_get_whole_disk(dev_t d, dev_t *ret);
int block_get_originating(dev_t d, dev_t *ret);
int get_block_device_fd(int fd, dev_t *ret);
int get_block_device(const char *path, dev_t *dev);
int get_block_device_harder_fd(int fd, dev_t *dev);
int get_block_device_harder(const char *path, dev_t *dev);
int lock_whole_block_device(dev_t devt, int operation);
int blockdev_partscan_enabled(int fd);
int fd_is_encrypted(int fd);
int path_is_encrypted(const char *path);
int fd_get_whole_disk(int fd, bool backing, dev_t *ret);
int path_get_whole_disk(const char *path, bool backing, dev_t *ret);
int block_device_add_partition(int fd, const char *name, int nr, uint64_t start, uint64_t size);
int block_device_remove_partition(int fd, const char *name, int nr);
int block_device_resize_partition(int fd, int nr, uint64_t start, uint64_t size);
int partition_enumerator_new(sd_device *dev, sd_device_enumerator **ret);
int block_device_remove_all_partitions(sd_device *dev, int fd);
int block_device_has_partitions(sd_device *dev);
int blockdev_reread_partition_table(sd_device *dev);
int blockdev_get_sector_size(int fd, uint32_t *ret);
int blockdev_get_root(int level, dev_t *ret);
| 2,592 | 41.508197 | 110 |
h
|
null |
systemd-main/src/shared/bond-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bond-util.h"
#include "string-table.h"
static const char* const bond_mode_table[_NETDEV_BOND_MODE_MAX] = {
[NETDEV_BOND_MODE_BALANCE_RR] = "balance-rr",
[NETDEV_BOND_MODE_ACTIVE_BACKUP] = "active-backup",
[NETDEV_BOND_MODE_BALANCE_XOR] = "balance-xor",
[NETDEV_BOND_MODE_BROADCAST] = "broadcast",
[NETDEV_BOND_MODE_802_3AD] = "802.3ad",
[NETDEV_BOND_MODE_BALANCE_TLB] = "balance-tlb",
[NETDEV_BOND_MODE_BALANCE_ALB] = "balance-alb",
};
DEFINE_STRING_TABLE_LOOKUP(bond_mode, BondMode);
static const char* const bond_xmit_hash_policy_table[_NETDEV_BOND_XMIT_HASH_POLICY_MAX] = {
[NETDEV_BOND_XMIT_HASH_POLICY_LAYER2] = "layer2",
[NETDEV_BOND_XMIT_HASH_POLICY_LAYER34] = "layer3+4",
[NETDEV_BOND_XMIT_HASH_POLICY_LAYER23] = "layer2+3",
[NETDEV_BOND_XMIT_HASH_POLICY_ENCAP23] = "encap2+3",
[NETDEV_BOND_XMIT_HASH_POLICY_ENCAP34] = "encap3+4",
};
DEFINE_STRING_TABLE_LOOKUP(bond_xmit_hash_policy, BondXmitHashPolicy);
static const char* const bond_lacp_rate_table[_NETDEV_BOND_LACP_RATE_MAX] = {
[NETDEV_BOND_LACP_RATE_SLOW] = "slow",
[NETDEV_BOND_LACP_RATE_FAST] = "fast",
};
DEFINE_STRING_TABLE_LOOKUP(bond_lacp_rate, BondLacpRate);
static const char* const bond_ad_select_table[_NETDEV_BOND_AD_SELECT_MAX] = {
[NETDEV_BOND_AD_SELECT_STABLE] = "stable",
[NETDEV_BOND_AD_SELECT_BANDWIDTH] = "bandwidth",
[NETDEV_BOND_AD_SELECT_COUNT] = "count",
};
DEFINE_STRING_TABLE_LOOKUP(bond_ad_select, BondAdSelect);
static const char* const bond_fail_over_mac_table[_NETDEV_BOND_FAIL_OVER_MAC_MAX] = {
[NETDEV_BOND_FAIL_OVER_MAC_NONE] = "none",
[NETDEV_BOND_FAIL_OVER_MAC_ACTIVE] = "active",
[NETDEV_BOND_FAIL_OVER_MAC_FOLLOW] = "follow",
};
DEFINE_STRING_TABLE_LOOKUP(bond_fail_over_mac, BondFailOverMac);
static const char *const bond_arp_validate_table[_NETDEV_BOND_ARP_VALIDATE_MAX] = {
[NETDEV_BOND_ARP_VALIDATE_NONE] = "none",
[NETDEV_BOND_ARP_VALIDATE_ACTIVE]= "active",
[NETDEV_BOND_ARP_VALIDATE_BACKUP]= "backup",
[NETDEV_BOND_ARP_VALIDATE_ALL]= "all",
};
DEFINE_STRING_TABLE_LOOKUP(bond_arp_validate, BondArpValidate);
static const char *const bond_arp_all_targets_table[_NETDEV_BOND_ARP_ALL_TARGETS_MAX] = {
[NETDEV_BOND_ARP_ALL_TARGETS_ANY] = "any",
[NETDEV_BOND_ARP_ALL_TARGETS_ALL] = "all",
};
DEFINE_STRING_TABLE_LOOKUP(bond_arp_all_targets, BondArpAllTargets);
static const char *const bond_primary_reselect_table[_NETDEV_BOND_PRIMARY_RESELECT_MAX] = {
[NETDEV_BOND_PRIMARY_RESELECT_ALWAYS] = "always",
[NETDEV_BOND_PRIMARY_RESELECT_BETTER]= "better",
[NETDEV_BOND_PRIMARY_RESELECT_FAILURE]= "failure",
};
DEFINE_STRING_TABLE_LOOKUP(bond_primary_reselect, BondPrimaryReselect);
| 2,888 | 38.040541 | 91 |
c
|
null |
systemd-main/src/shared/bond-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <netinet/in.h>
#include <linux/if_bonding.h>
#include "macro.h"
/*
* Maximum number of targets supported by the kernel for a single
* bond netdev.
*/
#define NETDEV_BOND_ARP_TARGETS_MAX 16
typedef enum BondMode {
NETDEV_BOND_MODE_BALANCE_RR = BOND_MODE_ROUNDROBIN,
NETDEV_BOND_MODE_ACTIVE_BACKUP = BOND_MODE_ACTIVEBACKUP,
NETDEV_BOND_MODE_BALANCE_XOR = BOND_MODE_XOR,
NETDEV_BOND_MODE_BROADCAST = BOND_MODE_BROADCAST,
NETDEV_BOND_MODE_802_3AD = BOND_MODE_8023AD,
NETDEV_BOND_MODE_BALANCE_TLB = BOND_MODE_TLB,
NETDEV_BOND_MODE_BALANCE_ALB = BOND_MODE_ALB,
_NETDEV_BOND_MODE_MAX,
_NETDEV_BOND_MODE_INVALID = -EINVAL,
} BondMode;
typedef enum BondXmitHashPolicy {
NETDEV_BOND_XMIT_HASH_POLICY_LAYER2 = BOND_XMIT_POLICY_LAYER2,
NETDEV_BOND_XMIT_HASH_POLICY_LAYER34 = BOND_XMIT_POLICY_LAYER34,
NETDEV_BOND_XMIT_HASH_POLICY_LAYER23 = BOND_XMIT_POLICY_LAYER23,
NETDEV_BOND_XMIT_HASH_POLICY_ENCAP23 = BOND_XMIT_POLICY_ENCAP23,
NETDEV_BOND_XMIT_HASH_POLICY_ENCAP34 = BOND_XMIT_POLICY_ENCAP34,
_NETDEV_BOND_XMIT_HASH_POLICY_MAX,
_NETDEV_BOND_XMIT_HASH_POLICY_INVALID = -EINVAL,
} BondXmitHashPolicy;
typedef enum BondLacpRate {
NETDEV_BOND_LACP_RATE_SLOW,
NETDEV_BOND_LACP_RATE_FAST,
_NETDEV_BOND_LACP_RATE_MAX,
_NETDEV_BOND_LACP_RATE_INVALID = -EINVAL,
} BondLacpRate;
typedef enum BondAdSelect {
NETDEV_BOND_AD_SELECT_STABLE,
NETDEV_BOND_AD_SELECT_BANDWIDTH,
NETDEV_BOND_AD_SELECT_COUNT,
_NETDEV_BOND_AD_SELECT_MAX,
_NETDEV_BOND_AD_SELECT_INVALID = -EINVAL,
} BondAdSelect;
typedef enum BondFailOverMac {
NETDEV_BOND_FAIL_OVER_MAC_NONE,
NETDEV_BOND_FAIL_OVER_MAC_ACTIVE,
NETDEV_BOND_FAIL_OVER_MAC_FOLLOW,
_NETDEV_BOND_FAIL_OVER_MAC_MAX,
_NETDEV_BOND_FAIL_OVER_MAC_INVALID = -EINVAL,
} BondFailOverMac;
typedef enum BondArpValidate {
NETDEV_BOND_ARP_VALIDATE_NONE,
NETDEV_BOND_ARP_VALIDATE_ACTIVE,
NETDEV_BOND_ARP_VALIDATE_BACKUP,
NETDEV_BOND_ARP_VALIDATE_ALL,
_NETDEV_BOND_ARP_VALIDATE_MAX,
_NETDEV_BOND_ARP_VALIDATE_INVALID = -EINVAL,
} BondArpValidate;
typedef enum BondArpAllTargets {
NETDEV_BOND_ARP_ALL_TARGETS_ANY,
NETDEV_BOND_ARP_ALL_TARGETS_ALL,
_NETDEV_BOND_ARP_ALL_TARGETS_MAX,
_NETDEV_BOND_ARP_ALL_TARGETS_INVALID = -EINVAL,
} BondArpAllTargets;
typedef enum BondPrimaryReselect {
NETDEV_BOND_PRIMARY_RESELECT_ALWAYS,
NETDEV_BOND_PRIMARY_RESELECT_BETTER,
NETDEV_BOND_PRIMARY_RESELECT_FAILURE,
_NETDEV_BOND_PRIMARY_RESELECT_MAX,
_NETDEV_BOND_PRIMARY_RESELECT_INVALID = -EINVAL,
} BondPrimaryReselect;
const char *bond_mode_to_string(BondMode d) _const_;
BondMode bond_mode_from_string(const char *d) _pure_;
const char *bond_xmit_hash_policy_to_string(BondXmitHashPolicy d) _const_;
BondXmitHashPolicy bond_xmit_hash_policy_from_string(const char *d) _pure_;
const char *bond_lacp_rate_to_string(BondLacpRate d) _const_;
BondLacpRate bond_lacp_rate_from_string(const char *d) _pure_;
const char *bond_fail_over_mac_to_string(BondFailOverMac d) _const_;
BondFailOverMac bond_fail_over_mac_from_string(const char *d) _pure_;
const char *bond_ad_select_to_string(BondAdSelect d) _const_;
BondAdSelect bond_ad_select_from_string(const char *d) _pure_;
const char *bond_arp_validate_to_string(BondArpValidate d) _const_;
BondArpValidate bond_arp_validate_from_string(const char *d) _pure_;
const char *bond_arp_all_targets_to_string(BondArpAllTargets d) _const_;
BondArpAllTargets bond_arp_all_targets_from_string(const char *d) _pure_;
const char *bond_primary_reselect_to_string(BondPrimaryReselect d) _const_;
BondPrimaryReselect bond_primary_reselect_from_string(const char *d) _pure_;
| 3,970 | 36.11215 | 76 |
h
|
null |
systemd-main/src/shared/boot-entry.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "boot-entry.h"
#include "chase.h"
#include "fd-util.h"
#include "fileio.h"
#include "id128-util.h"
#include "os-util.h"
#include "path-util.h"
#include "string-util.h"
#include "utf8.h"
bool boot_entry_token_valid(const char *p) {
return utf8_is_valid(p) && string_is_safe(p) && filename_is_valid(p);
}
static int entry_token_load(int rfd, const char *etc_kernel, BootEntryTokenType *type, char **token) {
_cleanup_free_ char *buf = NULL, *p = NULL;
_cleanup_fclose_ FILE *f = NULL;
int r;
assert(rfd >= 0 || rfd == AT_FDCWD);
assert(type);
assert(*type == BOOT_ENTRY_TOKEN_AUTO);
assert(token);
if (!etc_kernel)
return 0;
p = path_join(etc_kernel, "entry-token");
if (!p)
return log_oom();
r = chase_and_fopenat_unlocked(rfd, p, CHASE_AT_RESOLVE_IN_ROOT, "re", NULL, &f);
if (r == -ENOENT)
return 0;
if (r < 0)
return log_error_errno(r, "Failed to chase and open '%s': %m", p);
r = read_line(f, NAME_MAX, &buf);
if (r < 0)
return log_error_errno(r, "Failed to read %s: %m", p);
if (isempty(buf))
return 0;
if (!boot_entry_token_valid(buf)) {
log_debug("Invalid entry token specified in %s, ignoring.", p);
return 0;
}
*token = TAKE_PTR(buf);
*type = BOOT_ENTRY_TOKEN_LITERAL;
return 1;
}
static int entry_token_from_machine_id(sd_id128_t machine_id, BootEntryTokenType *type, char **token) {
char *p;
assert(type);
assert(IN_SET(*type, BOOT_ENTRY_TOKEN_AUTO, BOOT_ENTRY_TOKEN_MACHINE_ID));
assert(token);
if (sd_id128_is_null(machine_id))
return 0;
p = strdup(SD_ID128_TO_STRING(machine_id));
if (!p)
return log_oom();
*token = p;
*type = BOOT_ENTRY_TOKEN_MACHINE_ID;
return 1;
}
static int entry_token_from_os_release(int rfd, BootEntryTokenType *type, char **token) {
_cleanup_free_ char *id = NULL, *image_id = NULL;
int r;
assert(rfd >= 0 || rfd == AT_FDCWD);
assert(type);
assert(IN_SET(*type, BOOT_ENTRY_TOKEN_AUTO, BOOT_ENTRY_TOKEN_OS_IMAGE_ID, BOOT_ENTRY_TOKEN_OS_ID));
assert(token);
switch (*type) {
case BOOT_ENTRY_TOKEN_AUTO:
r = parse_os_release_at(rfd,
"IMAGE_ID", &image_id,
"ID", &id);
break;
case BOOT_ENTRY_TOKEN_OS_IMAGE_ID:
r = parse_os_release_at(rfd, "IMAGE_ID", &image_id);
break;
case BOOT_ENTRY_TOKEN_OS_ID:
r = parse_os_release_at(rfd, "ID", &id);
break;
default:
assert_not_reached();
}
if (r == -ENOENT)
return 0;
if (r < 0)
return log_error_errno(r, "Failed to load /etc/os-release: %m");
if (!isempty(image_id) && boot_entry_token_valid(image_id)) {
*token = TAKE_PTR(image_id);
*type = BOOT_ENTRY_TOKEN_OS_IMAGE_ID;
return 1;
}
if (!isempty(id) && boot_entry_token_valid(id)) {
*token = TAKE_PTR(id);
*type = BOOT_ENTRY_TOKEN_OS_ID;
return 1;
}
return 0;
}
int boot_entry_token_ensure_at(
int rfd,
const char *etc_kernel,
sd_id128_t machine_id,
bool machine_id_is_random,
BootEntryTokenType *type,
char **token) {
int r;
assert(rfd >= 0 || rfd == AT_FDCWD);
assert(type);
assert(token);
if (*token)
return 0; /* Already set. */
switch (*type) {
case BOOT_ENTRY_TOKEN_AUTO:
r = entry_token_load(rfd, etc_kernel, type, token);
if (r != 0)
return r;
if (!machine_id_is_random) {
r = entry_token_from_machine_id(machine_id, type, token);
if (r != 0)
return r;
}
r = entry_token_from_os_release(rfd, type, token);
if (r != 0)
return r;
if (machine_id_is_random) {
r = entry_token_from_machine_id(machine_id, type, token);
if (r != 0)
return r;
}
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"No machine ID set, and /etc/os-release carries no ID=/IMAGE_ID= fields.");
case BOOT_ENTRY_TOKEN_MACHINE_ID:
r = entry_token_from_machine_id(machine_id, type, token);
if (r != 0)
return r;
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No machine ID set.");
case BOOT_ENTRY_TOKEN_OS_IMAGE_ID:
r = entry_token_from_os_release(rfd, type, token);
if (r != 0)
return r;
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"IMAGE_ID= field not set in /etc/os-release.");
case BOOT_ENTRY_TOKEN_OS_ID:
r = entry_token_from_os_release(rfd, type, token);
if (r != 0)
return r;
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"ID= field not set in /etc/os-release.");
case BOOT_ENTRY_TOKEN_LITERAL:
/* In this case, the token should be already set by the user input. */
return -EINVAL;
default:
assert_not_reached();
}
}
int boot_entry_token_ensure(
const char *root,
const char *etc_kernel,
sd_id128_t machine_id,
bool machine_id_is_random,
BootEntryTokenType *type,
char **token) {
assert(token);
if (*token)
return 0; /* Already set. */
_cleanup_close_ int rfd = -EBADF;
rfd = open(empty_to_root(root), O_CLOEXEC | O_DIRECTORY | O_PATH);
if (rfd < 0)
return -errno;
return boot_entry_token_ensure_at(rfd, etc_kernel, machine_id, machine_id_is_random, type, token);
}
int parse_boot_entry_token_type(const char *s, BootEntryTokenType *type, char **token) {
assert(s);
assert(type);
assert(token);
/*
* This function is intended to be used in command line parsers, to handle token that are passed in.
*
* NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON SUCCESS!
* Hence, do not pass in uninitialized pointers.
*/
if (streq(s, "machine-id")) {
*type = BOOT_ENTRY_TOKEN_MACHINE_ID;
*token = mfree(*token);
return 0;
}
if (streq(s, "os-image-id")) {
*type = BOOT_ENTRY_TOKEN_OS_IMAGE_ID;
*token = mfree(*token);
return 0;
}
if (streq(s, "os-id")) {
*type = BOOT_ENTRY_TOKEN_OS_ID;
*token = mfree(*token);
return 0;
}
const char *e = startswith(s, "literal:");
if (e) {
if (!boot_entry_token_valid(e))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Invalid entry token literal is specified for --entry-token=.");
*type = BOOT_ENTRY_TOKEN_LITERAL;
return free_and_strdup_warn(token, e);
}
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Unexpected parameter for --entry-token=: %s", s);
}
| 8,193 | 30.155894 | 114 |
c
|
null |
systemd-main/src/shared/boot-entry.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "sd-id128.h"
typedef enum BootEntryTokenType {
BOOT_ENTRY_TOKEN_MACHINE_ID,
BOOT_ENTRY_TOKEN_OS_IMAGE_ID,
BOOT_ENTRY_TOKEN_OS_ID,
BOOT_ENTRY_TOKEN_LITERAL,
BOOT_ENTRY_TOKEN_AUTO,
} BootEntryTokenType;
bool boot_entry_token_valid(const char *p);
int boot_entry_token_ensure(
const char *root,
const char *etc_kernel, /* will be prefixed with root, typically /etc/kernel. */
sd_id128_t machine_id,
bool machine_id_is_random,
BootEntryTokenType *type, /* input and output */
char **token); /* output, but do not pass uninitialized value. */
int boot_entry_token_ensure_at(
int rfd,
const char *etc_kernel,
sd_id128_t machine_id,
bool machine_id_is_random,
BootEntryTokenType *type,
char **token);
int parse_boot_entry_token_type(const char *s, BootEntryTokenType *type, char **token);
| 1,125 | 32.117647 | 98 |
h
|
null |
systemd-main/src/shared/boot-timestamps.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "acpi-fpdt.h"
#include "boot-timestamps.h"
#include "efi-loader.h"
#include "macro.h"
#include "time-util.h"
int boot_timestamps(const dual_timestamp *n, dual_timestamp *firmware, dual_timestamp *loader) {
usec_t x = 0, y = 0, a;
int r;
dual_timestamp _n;
assert(firmware);
assert(loader);
if (!n) {
dual_timestamp_get(&_n);
n = &_n;
}
r = acpi_get_boot_usec(&x, &y);
if (r < 0) {
r = efi_loader_get_boot_usec(&x, &y);
if (r < 0)
return r;
}
/* Let's convert this to timestamps where the firmware
* began/loader began working. To make this more confusing:
* since usec_t is unsigned and the kernel's monotonic clock
* begins at kernel initialization we'll actually initialize
* the monotonic timestamps here as negative of the actual
* value. */
firmware->monotonic = y;
loader->monotonic = y - x;
a = n->monotonic + firmware->monotonic;
firmware->realtime = n->realtime > a ? n->realtime - a : 0;
a = n->monotonic + loader->monotonic;
loader->realtime = n->realtime > a ? n->realtime - a : 0;
return 0;
}
| 1,351 | 27.765957 | 96 |
c
|
null |
systemd-main/src/shared/bootspec.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <sys/types.h>
#include "json.h"
#include "set.h"
#include "string-util.h"
typedef enum BootEntryType {
BOOT_ENTRY_CONF, /* Boot Loader Specification Type #1 entries: *.conf files */
BOOT_ENTRY_UNIFIED, /* Boot Loader Specification Type #2 entries: *.efi files */
BOOT_ENTRY_LOADER, /* Additional entries augmented from LoaderEntries EFI variable (regular entries) */
BOOT_ENTRY_LOADER_AUTO, /* Additional entries augmented from LoaderEntries EFI variable (special "automatic" entries) */
_BOOT_ENTRY_TYPE_MAX,
_BOOT_ENTRY_TYPE_INVALID = -EINVAL,
} BootEntryType;
typedef struct BootEntry {
BootEntryType type;
bool reported_by_loader;
char *id; /* This is the file basename (including extension!) */
char *id_old; /* Old-style ID, for deduplication purposes. */
char *path; /* This is the full path to the drop-in file */
char *root; /* The root path in which the drop-in was found, i.e. to which 'kernel', 'efi' and 'initrd' are relative */
char *title;
char *show_title;
char *sort_key;
char *version;
char *machine_id;
char *architecture;
char **options;
char *kernel; /* linux is #defined to 1, yikes! */
char *efi;
char **initrd;
char *device_tree;
char **device_tree_overlay;
unsigned tries_left;
unsigned tries_done;
} BootEntry;
#define BOOT_ENTRY_INIT(t) \
{ \
.type = (t), \
.tries_left = UINT_MAX, \
.tries_done = UINT_MAX, \
}
typedef struct BootConfig {
char *default_pattern;
char *timeout;
char *editor;
char *auto_entries;
char *auto_firmware;
char *console_mode;
char *beep;
char *entry_oneshot;
char *entry_default;
char *entry_selected;
BootEntry *entries;
size_t n_entries;
ssize_t default_entry;
ssize_t selected_entry;
Set *inodes_seen;
} BootConfig;
#define BOOT_CONFIG_NULL \
{ \
.default_entry = -1, \
.selected_entry = -1, \
}
const char* boot_entry_type_to_string(BootEntryType);
const char* boot_entry_type_json_to_string(BootEntryType);
BootEntry* boot_config_find_entry(BootConfig *config, const char *id);
static inline const BootEntry* boot_config_default_entry(const BootConfig *config) {
assert(config);
if (config->default_entry < 0)
return NULL;
assert((size_t) config->default_entry < config->n_entries);
return config->entries + config->default_entry;
}
void boot_config_free(BootConfig *config);
int boot_loader_read_conf(BootConfig *config, FILE *file, const char *path);
int boot_config_load_type1(
BootConfig *config,
FILE *f,
const char *root,
const char *dir,
const char *id);
int boot_config_finalize(BootConfig *config);
int boot_config_load(BootConfig *config, const char *esp_path, const char *xbootldr_path);
int boot_config_load_auto(BootConfig *config, const char *override_esp_path, const char *override_xbootldr_path);
int boot_config_augment_from_loader(BootConfig *config, char **list, bool only_auto);
int boot_config_select_special_entries(BootConfig *config, bool skip_efivars);
static inline const char* boot_entry_title(const BootEntry *entry) {
assert(entry);
return ASSERT_PTR(entry->show_title ?: entry->title ?: entry->id);
}
int show_boot_entry(
const BootEntry *e,
bool show_as_default,
bool show_as_selected,
bool show_reported);
int show_boot_entries(
const BootConfig *config,
JsonFormatFlags json_format);
int boot_filename_extract_tries(const char *fname, char **ret_stripped, unsigned *ret_tries_left, unsigned *ret_tries_done);
| 4,315 | 32.2 | 131 |
h
|
null |
systemd-main/src/shared/bpf-compat.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/* libbpf has been moving quickly.
* They added new symbols in the 0.x versions and shortly after removed
* deprecated symbols in 1.0.
* We only need bpf_map_create and libbpf_probe_bpf_prog_type so we work
* around the incompatibility here by:
* - declaring both symbols, and looking for either depending on the libbpf
* so version we found
* - having helpers that automatically use the appropriate version behind the
* new API for easy cleanup later
*
* The advantage of doing this instead of only looking for the symbols declared at
* compile time is that we can then load either the old or the new symbols at runtime
* regardless of the version we were compiled with */
/* declare the struct for libbpf <= 0.6.0 -- it causes no harm on newer versions */
struct bpf_map_create_opts;
/* new symbols available from 0.7.0.
* We need the symbols here:
* - after bpf_map_create_opts struct has been defined for older libbpf
* - before the compat static inline helpers that use them.
* When removing this file move these back to bpf-dlopen.h */
extern int (*sym_bpf_map_create)(enum bpf_map_type, const char *, __u32, __u32, __u32, const struct bpf_map_create_opts *);
extern int (*sym_libbpf_probe_bpf_prog_type)(enum bpf_prog_type, const void *);
/* compat symbols removed in libbpf 1.0 */
extern int (*sym_bpf_create_map)(enum bpf_map_type, int key_size, int value_size, int max_entries, __u32 map_flags);
extern bool (*sym_bpf_probe_prog_type)(enum bpf_prog_type, __u32);
/* helpers to use the available variant behind new API */
static inline int compat_bpf_map_create(enum bpf_map_type map_type,
const char *map_name,
__u32 key_size,
__u32 value_size,
__u32 max_entries,
const struct bpf_map_create_opts *opts) {
if (sym_bpf_map_create)
return sym_bpf_map_create(map_type, map_name, key_size,
value_size, max_entries, opts);
return sym_bpf_create_map(map_type, key_size, value_size, max_entries,
0 /* opts->map_flags, but opts is always NULL for us so skip build dependency on the type */);
}
static inline int compat_libbpf_probe_bpf_prog_type(enum bpf_prog_type prog_type, const void *opts) {
if (sym_libbpf_probe_bpf_prog_type)
return sym_libbpf_probe_bpf_prog_type(prog_type, opts);
return sym_bpf_probe_prog_type(prog_type, 0);
}
| 2,556 | 45.490909 | 128 |
h
|
null |
systemd-main/src/shared/bpf-dlopen.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "dlfcn-util.h"
#include "bpf-dlopen.h"
#include "log.h"
#include "strv.h"
#if HAVE_LIBBPF
/* libbpf changed types of function prototypes around, so we need to disable some type checking for older
* libbpf. We consider everything older than 0.7 too old for accurate type checks. */
#if defined(__LIBBPF_CURRENT_VERSION_GEQ)
#if __LIBBPF_CURRENT_VERSION_GEQ(0, 7)
#define MODERN_LIBBPF 1
#endif
#endif
#if !defined(MODERN_LIBBPF)
#define MODERN_LIBBPF 0
#endif
struct bpf_link* (*sym_bpf_program__attach_cgroup)(const struct bpf_program *, int);
struct bpf_link* (*sym_bpf_program__attach_lsm)(const struct bpf_program *);
int (*sym_bpf_link__fd)(const struct bpf_link *);
int (*sym_bpf_link__destroy)(struct bpf_link *);
int (*sym_bpf_map__fd)(const struct bpf_map *);
const char* (*sym_bpf_map__name)(const struct bpf_map *);
int (*sym_bpf_map_create)(enum bpf_map_type, const char *, __u32, __u32, __u32, const struct bpf_map_create_opts *);
int (*sym_bpf_map__set_max_entries)(struct bpf_map *, __u32);
int (*sym_bpf_map_update_elem)(int, const void *, const void *, __u64);
int (*sym_bpf_map_delete_elem)(int, const void *);
int (*sym_bpf_map__set_inner_map_fd)(struct bpf_map *, int);
int (*sym_bpf_object__open_skeleton)(struct bpf_object_skeleton *, const struct bpf_object_open_opts *);
int (*sym_bpf_object__load_skeleton)(struct bpf_object_skeleton *);
int (*sym_bpf_object__attach_skeleton)(struct bpf_object_skeleton *);
void (*sym_bpf_object__detach_skeleton)(struct bpf_object_skeleton *);
void (*sym_bpf_object__destroy_skeleton)(struct bpf_object_skeleton *);
int (*sym_libbpf_probe_bpf_prog_type)(enum bpf_prog_type, const void *);
const char* (*sym_bpf_program__name)(const struct bpf_program *);
libbpf_print_fn_t (*sym_libbpf_set_print)(libbpf_print_fn_t);
long (*sym_libbpf_get_error)(const void *);
/* compat symbols removed in libbpf 1.0 */
int (*sym_bpf_create_map)(enum bpf_map_type, int key_size, int value_size, int max_entries, __u32 map_flags);
bool (*sym_bpf_probe_prog_type)(enum bpf_prog_type, __u32);
_printf_(2,0)
static int bpf_print_func(enum libbpf_print_level level, const char *fmt, va_list ap) {
#if !LOG_TRACE
/* libbpf logs a lot of details at its debug level, which we don't need to see. */
if (level == LIBBPF_DEBUG)
return 0;
#endif
/* All other levels are downgraded to LOG_DEBUG */
/* errno is used here, on the assumption that if the log message uses %m, errno will be set to
* something useful. Otherwise, it shouldn't matter, we may pass 0 or some bogus value. */
return log_internalv(LOG_DEBUG, errno, NULL, 0, NULL, fmt, ap);
}
int dlopen_bpf(void) {
void *dl;
int r;
DISABLE_WARNING_DEPRECATED_DECLARATIONS;
dl = dlopen("libbpf.so.1", RTLD_LAZY);
if (!dl) {
/* libbpf < 1.0.0 (we rely on 0.1.0+) provide most symbols we care about, but
* unfortunately not all until 0.7.0. See bpf-compat.h for more details.
* Once we consider we can assume 0.7+ is present we can just use the same symbol
* list for both files, and when we assume 1.0+ is present we can remove this dlopen */
dl = dlopen("libbpf.so.0", RTLD_LAZY);
if (!dl)
return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"neither libbpf.so.1 nor libbpf.so.0 are installed: %s", dlerror());
/* symbols deprecated in 1.0 we use as compat */
r = dlsym_many_or_warn(
dl, LOG_DEBUG,
#if MODERN_LIBBPF
/* Don't exist anymore in new libbpf, hence cannot type check them */
DLSYM_ARG_FORCE(bpf_create_map),
DLSYM_ARG_FORCE(bpf_probe_prog_type));
#else
DLSYM_ARG(bpf_create_map),
DLSYM_ARG(bpf_probe_prog_type));
#endif
} else {
/* symbols available from 0.7.0 */
r = dlsym_many_or_warn(
dl, LOG_DEBUG,
#if MODERN_LIBBPF
DLSYM_ARG(bpf_map_create),
DLSYM_ARG(libbpf_probe_bpf_prog_type)
#else
/* These symbols did not exist in old libbpf, hence we cannot type check them */
DLSYM_ARG_FORCE(bpf_map_create),
DLSYM_ARG_FORCE(libbpf_probe_bpf_prog_type)
#endif
);
}
r = dlsym_many_or_warn(
dl, LOG_DEBUG,
DLSYM_ARG(bpf_link__destroy),
DLSYM_ARG(bpf_link__fd),
DLSYM_ARG(bpf_map__fd),
DLSYM_ARG(bpf_map__name),
DLSYM_ARG(bpf_map__set_max_entries),
DLSYM_ARG(bpf_map_update_elem),
DLSYM_ARG(bpf_map_delete_elem),
DLSYM_ARG(bpf_map__set_inner_map_fd),
DLSYM_ARG(bpf_object__open_skeleton),
DLSYM_ARG(bpf_object__load_skeleton),
DLSYM_ARG(bpf_object__attach_skeleton),
DLSYM_ARG(bpf_object__detach_skeleton),
DLSYM_ARG(bpf_object__destroy_skeleton),
#if MODERN_LIBBPF
DLSYM_ARG(bpf_program__attach_cgroup),
DLSYM_ARG(bpf_program__attach_lsm),
#else
/* libbpf added a "const" to function parameters where it should not have, ignore this type incompatibility */
DLSYM_ARG_FORCE(bpf_program__attach_cgroup),
DLSYM_ARG_FORCE(bpf_program__attach_lsm),
#endif
DLSYM_ARG(bpf_program__name),
DLSYM_ARG(libbpf_set_print),
DLSYM_ARG(libbpf_get_error));
if (r < 0)
return r;
/* We set the print helper unconditionally. Otherwise libbpf will emit not useful log messages. */
(void) sym_libbpf_set_print(bpf_print_func);
REENABLE_WARNING;
return r;
}
#else
int dlopen_bpf(void) {
return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"libbpf support is not compiled in.");
}
#endif
| 6,521 | 43.367347 | 134 |
c
|
null |
systemd-main/src/shared/bpf-dlopen.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if HAVE_LIBBPF
#include <bpf/bpf.h>
#include <bpf/libbpf.h>
#include "bpf-compat.h"
extern struct bpf_link* (*sym_bpf_program__attach_cgroup)(const struct bpf_program *, int);
extern struct bpf_link* (*sym_bpf_program__attach_lsm)(const struct bpf_program *);
extern int (*sym_bpf_link__fd)(const struct bpf_link *);
extern int (*sym_bpf_link__destroy)(struct bpf_link *);
extern int (*sym_bpf_map__fd)(const struct bpf_map *);
extern const char* (*sym_bpf_map__name)(const struct bpf_map *);
extern int (*sym_bpf_map__set_max_entries)(struct bpf_map *, __u32);
extern int (*sym_bpf_map_update_elem)(int, const void *, const void *, __u64);
extern int (*sym_bpf_map_delete_elem)(int, const void *);
extern int (*sym_bpf_map__set_inner_map_fd)(struct bpf_map *, int);
/* The *_skeleton APIs are autogenerated by bpftool, the targets can be found
* in ./build/src/core/bpf/socket_bind/socket-bind.skel.h */
extern int (*sym_bpf_object__open_skeleton)(struct bpf_object_skeleton *, const struct bpf_object_open_opts *);
extern int (*sym_bpf_object__load_skeleton)(struct bpf_object_skeleton *);
extern int (*sym_bpf_object__attach_skeleton)(struct bpf_object_skeleton *);
extern void (*sym_bpf_object__detach_skeleton)(struct bpf_object_skeleton *);
extern void (*sym_bpf_object__destroy_skeleton)(struct bpf_object_skeleton *);
extern const char* (*sym_bpf_program__name)(const struct bpf_program *);
extern libbpf_print_fn_t (*sym_libbpf_set_print)(libbpf_print_fn_t);
extern long (*sym_libbpf_get_error)(const void *);
#endif
int dlopen_bpf(void);
| 1,618 | 45.257143 | 111 |
h
|
null |
systemd-main/src/shared/bpf-link.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bpf-dlopen.h"
#include "bpf-link.h"
#include "serialize.h"
bool bpf_can_link_program(struct bpf_program *prog) {
_cleanup_(bpf_link_freep) struct bpf_link *link = NULL;
assert(prog);
if (dlopen_bpf() < 0)
return false;
/* Pass invalid cgroup fd intentionally. */
link = sym_bpf_program__attach_cgroup(prog, /*cgroup_fd=*/-1);
/* EBADF indicates that bpf_link is supported by kernel. */
return sym_libbpf_get_error(link) == -EBADF;
}
int bpf_serialize_link(FILE *f, FDSet *fds, const char *key, struct bpf_link *link) {
assert(key);
if (!link)
return -ENOENT;
if (sym_libbpf_get_error(link) != 0)
return -EINVAL;
return serialize_fd(f, fds, key, sym_bpf_link__fd(link));
}
struct bpf_link *bpf_link_free(struct bpf_link *link) {
/* If libbpf wasn't dlopen()ed, sym_bpf_link__destroy might be unresolved (NULL), so let's not try to
* call it if link is NULL. link might also be a non-null "error pointer", but such a value can only
* originate from a call to libbpf, but that means that libbpf is available, and we can let
* bpf_link__destroy() handle it. */
if (link)
(void) sym_bpf_link__destroy(link);
return NULL;
}
| 1,392 | 30.659091 | 109 |
c
|
null |
systemd-main/src/shared/bpf-program.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "alloc-util.h"
#include "bpf-program.h"
#include "errno-util.h"
#include "escape.h"
#include "fd-util.h"
#include "memory-util.h"
#include "missing_syscall.h"
#include "path-util.h"
#include "serialize.h"
#include "string-table.h"
static const char *const bpf_cgroup_attach_type_table[__MAX_BPF_ATTACH_TYPE] = {
[BPF_CGROUP_INET_INGRESS] = "ingress",
[BPF_CGROUP_INET_EGRESS] = "egress",
[BPF_CGROUP_INET_SOCK_CREATE] = "sock_create",
[BPF_CGROUP_SOCK_OPS] = "sock_ops",
[BPF_CGROUP_DEVICE] = "device",
[BPF_CGROUP_INET4_BIND] = "bind4",
[BPF_CGROUP_INET6_BIND] = "bind6",
[BPF_CGROUP_INET4_CONNECT] = "connect4",
[BPF_CGROUP_INET6_CONNECT] = "connect6",
[BPF_CGROUP_INET4_POST_BIND] = "post_bind4",
[BPF_CGROUP_INET6_POST_BIND] = "post_bind6",
[BPF_CGROUP_UDP4_SENDMSG] = "sendmsg4",
[BPF_CGROUP_UDP6_SENDMSG] = "sendmsg6",
[BPF_CGROUP_SYSCTL] = "sysctl",
[BPF_CGROUP_UDP4_RECVMSG] = "recvmsg4",
[BPF_CGROUP_UDP6_RECVMSG] = "recvmsg6",
[BPF_CGROUP_GETSOCKOPT] = "getsockopt",
[BPF_CGROUP_SETSOCKOPT] = "setsockopt",
};
DEFINE_STRING_TABLE_LOOKUP(bpf_cgroup_attach_type, int);
DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(bpf_program_hash_ops, void, trivial_hash_func, trivial_compare_func, bpf_program_free);
BPFProgram *bpf_program_free(BPFProgram *p) {
if (!p)
return NULL;
/* Unfortunately, the kernel currently doesn't implicitly detach BPF programs from their cgroups when the last
* fd to the BPF program is closed. This has nasty side-effects since this means that abnormally terminated
* programs that attached one of their BPF programs to a cgroup will leave this program pinned for good with
* zero chance of recovery, until the cgroup is removed. This is particularly problematic if the cgroup in
* question is the root cgroup (or any other cgroup belonging to a service that cannot be restarted during
* operation, such as dbus), as the memory for the BPF program can only be reclaimed through a reboot. To
* counter this, we track closely to which cgroup a program was attached to and will detach it on our own
* whenever we close the BPF fd. */
(void) bpf_program_cgroup_detach(p);
safe_close(p->kernel_fd);
free(p->prog_name);
free(p->instructions);
free(p->attached_path);
return mfree(p);
}
/* struct bpf_prog_info info must be initialized since its value is both input and output
* for BPF_OBJ_GET_INFO_BY_FD syscall. */
static int bpf_program_get_info_by_fd(int prog_fd, struct bpf_prog_info *info, uint32_t info_len) {
union bpf_attr attr;
/* Explicitly memset to zero since some compilers may produce non-zero-initialized padding when
* structured initialization is used.
* Refer to https://github.com/systemd/systemd/issues/18164
*/
zero(attr);
attr.info.bpf_fd = prog_fd;
attr.info.info_len = info_len;
attr.info.info = PTR_TO_UINT64(info);
return RET_NERRNO(bpf(BPF_OBJ_GET_INFO_BY_FD, &attr, sizeof(attr)));
}
int bpf_program_new(uint32_t prog_type, const char *prog_name, BPFProgram **ret) {
_cleanup_(bpf_program_freep) BPFProgram *p = NULL;
_cleanup_free_ char *name = NULL;
if (prog_name) {
if (strlen(prog_name) >= BPF_OBJ_NAME_LEN)
return -ENAMETOOLONG;
name = strdup(prog_name);
if (!name)
return -ENOMEM;
}
p = new(BPFProgram, 1);
if (!p)
return -ENOMEM;
*p = (BPFProgram) {
.prog_type = prog_type,
.kernel_fd = -EBADF,
.prog_name = TAKE_PTR(name),
};
*ret = TAKE_PTR(p);
return 0;
}
int bpf_program_new_from_bpffs_path(const char *path, BPFProgram **ret) {
_cleanup_(bpf_program_freep) BPFProgram *p = NULL;
struct bpf_prog_info info = {};
int r;
assert(path);
assert(ret);
p = new(BPFProgram, 1);
if (!p)
return -ENOMEM;
*p = (BPFProgram) {
.prog_type = BPF_PROG_TYPE_UNSPEC,
.kernel_fd = -EBADF,
};
r = bpf_program_load_from_bpf_fs(p, path);
if (r < 0)
return r;
r = bpf_program_get_info_by_fd(p->kernel_fd, &info, sizeof(info));
if (r < 0)
return r;
p->prog_type = info.type;
*ret = TAKE_PTR(p);
return 0;
}
int bpf_program_add_instructions(BPFProgram *p, const struct bpf_insn *instructions, size_t count) {
assert(p);
if (p->kernel_fd >= 0) /* don't allow modification after we uploaded things to the kernel */
return -EBUSY;
if (!GREEDY_REALLOC(p->instructions, p->n_instructions + count))
return -ENOMEM;
memcpy(p->instructions + p->n_instructions, instructions, sizeof(struct bpf_insn) * count);
p->n_instructions += count;
return 0;
}
int bpf_program_load_kernel(BPFProgram *p, char *log_buf, size_t log_size) {
union bpf_attr attr;
assert(p);
if (p->kernel_fd >= 0) { /* make this idempotent */
memzero(log_buf, log_size);
return 0;
}
// FIXME: Clang doesn't 0-pad with structured initialization, causing
// the kernel to reject the bpf_attr as invalid. See:
// https://github.com/torvalds/linux/blob/v5.9/kernel/bpf/syscall.c#L65
// Ideally it should behave like GCC, so that we can remove these workarounds.
zero(attr);
attr.prog_type = p->prog_type;
attr.insns = PTR_TO_UINT64(p->instructions);
attr.insn_cnt = p->n_instructions;
attr.license = PTR_TO_UINT64("GPL");
attr.log_buf = PTR_TO_UINT64(log_buf);
attr.log_level = !!log_buf;
attr.log_size = log_size;
if (p->prog_name)
strncpy(attr.prog_name, p->prog_name, BPF_OBJ_NAME_LEN - 1);
p->kernel_fd = bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
if (p->kernel_fd < 0)
return -errno;
return 0;
}
int bpf_program_load_from_bpf_fs(BPFProgram *p, const char *path) {
union bpf_attr attr;
assert(p);
if (p->kernel_fd >= 0) /* don't overwrite an assembled or loaded program */
return -EBUSY;
zero(attr);
attr.pathname = PTR_TO_UINT64(path);
p->kernel_fd = bpf(BPF_OBJ_GET, &attr, sizeof(attr));
if (p->kernel_fd < 0)
return -errno;
return 0;
}
int bpf_program_cgroup_attach(BPFProgram *p, int type, const char *path, uint32_t flags) {
_cleanup_free_ char *copy = NULL;
_cleanup_close_ int fd = -EBADF;
union bpf_attr attr;
int r;
assert(p);
assert(type >= 0);
assert(path);
if (!IN_SET(flags, 0, BPF_F_ALLOW_OVERRIDE, BPF_F_ALLOW_MULTI))
return -EINVAL;
/* We need to track which cgroup the program is attached to, and we can only track one attachment, hence let's
* refuse this early. */
if (p->attached_path) {
if (!path_equal(p->attached_path, path))
return -EBUSY;
if (p->attached_type != type)
return -EBUSY;
if (p->attached_flags != flags)
return -EBUSY;
/* Here's a shortcut: if we previously attached this program already, then we don't have to do so
* again. Well, with one exception: if we are in BPF_F_ALLOW_OVERRIDE mode then someone else might have
* replaced our program since the last time, hence let's reattach it again, just to be safe. In flags
* == 0 mode this is not an issue since nobody else can replace our program in that case, and in flags
* == BPF_F_ALLOW_MULTI mode any other's program would be installed in addition to ours hence ours
* would remain in effect. */
if (flags != BPF_F_ALLOW_OVERRIDE)
return 0;
}
/* Ensure we have a kernel object for this. */
r = bpf_program_load_kernel(p, NULL, 0);
if (r < 0)
return r;
copy = strdup(path);
if (!copy)
return -ENOMEM;
fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
if (fd < 0)
return -errno;
zero(attr);
attr.attach_type = type;
attr.target_fd = fd;
attr.attach_bpf_fd = p->kernel_fd;
attr.attach_flags = flags;
if (bpf(BPF_PROG_ATTACH, &attr, sizeof(attr)) < 0)
return -errno;
free_and_replace(p->attached_path, copy);
p->attached_type = type;
p->attached_flags = flags;
return 0;
}
int bpf_program_cgroup_detach(BPFProgram *p) {
_cleanup_close_ int fd = -EBADF;
assert(p);
if (!p->attached_path)
return -EUNATCH;
fd = open(p->attached_path, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
if (fd < 0) {
if (errno != ENOENT)
return -errno;
/* If the cgroup does not exist anymore, then we don't have to explicitly detach, it got detached
* implicitly by the removal, hence don't complain */
} else {
union bpf_attr attr;
zero(attr);
attr.attach_type = p->attached_type;
attr.target_fd = fd;
attr.attach_bpf_fd = p->kernel_fd;
if (bpf(BPF_PROG_DETACH, &attr, sizeof(attr)) < 0)
return -errno;
}
p->attached_path = mfree(p->attached_path);
return 0;
}
int bpf_map_new(
const char *name,
enum bpf_map_type type,
size_t key_size,
size_t value_size,
size_t max_entries,
uint32_t flags) {
union bpf_attr attr;
const char *n = name;
zero(attr);
attr.map_type = type;
attr.key_size = key_size;
attr.value_size = value_size;
attr.max_entries = max_entries;
attr.map_flags = flags;
/* The map name is primarily informational for debugging purposes, and typically too short
* to carry the full unit name, hence we employ a trivial lossy escaping to make it fit
* (truncation + only alphanumerical, "." and "_" are allowed as per
* https://www.kernel.org/doc/html/next/bpf/maps.html#usage-notes) */
for (size_t i = 0; i < sizeof(attr.map_name) - 1 && *n; i++, n++)
attr.map_name[i] = strchr(ALPHANUMERICAL ".", *n) ? *n : '_';
return RET_NERRNO(bpf(BPF_MAP_CREATE, &attr, sizeof(attr)));
}
int bpf_map_update_element(int fd, const void *key, void *value) {
union bpf_attr attr;
zero(attr);
attr.map_fd = fd;
attr.key = PTR_TO_UINT64(key);
attr.value = PTR_TO_UINT64(value);
return RET_NERRNO(bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr)));
}
int bpf_map_lookup_element(int fd, const void *key, void *value) {
union bpf_attr attr;
zero(attr);
attr.map_fd = fd;
attr.key = PTR_TO_UINT64(key);
attr.value = PTR_TO_UINT64(value);
return RET_NERRNO(bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr)));
}
int bpf_program_pin(int prog_fd, const char *bpffs_path) {
union bpf_attr attr;
zero(attr);
attr.pathname = PTR_TO_UINT64((void *) bpffs_path);
attr.bpf_fd = prog_fd;
return RET_NERRNO(bpf(BPF_OBJ_PIN, &attr, sizeof(attr)));
}
int bpf_program_get_id_by_fd(int prog_fd, uint32_t *ret_id) {
struct bpf_prog_info info = {};
int r;
assert(ret_id);
r = bpf_program_get_info_by_fd(prog_fd, &info, sizeof(info));
if (r < 0)
return r;
*ret_id = info.id;
return 0;
};
int bpf_program_serialize_attachment(
FILE *f,
FDSet *fds,
const char *key,
BPFProgram *p) {
_cleanup_free_ char *escaped = NULL;
int copy, r;
if (!p || !p->attached_path)
return 0;
assert(p->kernel_fd >= 0);
escaped = cescape(p->attached_path);
if (!escaped)
return -ENOMEM;
copy = fdset_put_dup(fds, p->kernel_fd);
if (copy < 0)
return log_error_errno(copy, "Failed to add BPF kernel fd to serialize: %m");
r = serialize_item_format(
f,
key,
"%i %s %s",
copy,
bpf_cgroup_attach_type_to_string(p->attached_type),
escaped);
if (r < 0)
return r;
/* After serialization, let's forget the fact that this program is attached. The attachment — if you
* so will — is now 'owned' by the serialization, and not us anymore. Why does that matter? Because
* of BPF's less-than-ideal lifecycle handling: to detach a program from a cgroup we have to
* explicitly do so, it's not done implicitly on close(). Now, since we are serializing here we don't
* want the program to be detached while freeing things, so that the attachment can be retained after
* deserializing again. bpf_program_free() implicitly detaches things, if attached_path is non-NULL,
* hence we set it to NULL here. */
p->attached_path = mfree(p->attached_path);
return 0;
}
int bpf_program_serialize_attachment_set(FILE *f, FDSet *fds, const char *key, Set *set) {
BPFProgram *p;
int r;
SET_FOREACH(p, set) {
r = bpf_program_serialize_attachment(f, fds, key, p);
if (r < 0)
return r;
}
return 0;
}
int bpf_program_deserialize_attachment(const char *v, FDSet *fds, BPFProgram **bpfp) {
_cleanup_free_ char *sfd = NULL, *sat = NULL, *unescaped = NULL;
_cleanup_(bpf_program_freep) BPFProgram *p = NULL;
_cleanup_close_ int fd = -EBADF;
ssize_t l;
int ifd, at, r;
assert(v);
assert(bpfp);
/* Extract first word: the fd number */
r = extract_first_word(&v, &sfd, NULL, 0);
if (r < 0)
return r;
if (r == 0)
return -EINVAL;
ifd = parse_fd(sfd);
if (ifd < 0)
return r;
/* Extract second word: the attach type */
r = extract_first_word(&v, &sat, NULL, 0);
if (r < 0)
return r;
if (r == 0)
return -EINVAL;
at = bpf_cgroup_attach_type_from_string(sat);
if (at < 0)
return at;
/* The rest is the path */
if (isempty(v))
return -EINVAL;
l = cunescape(v, 0, &unescaped);
if (l < 0)
return l;
fd = fdset_remove(fds, ifd);
if (fd < 0)
return fd;
p = new(BPFProgram, 1);
if (!p)
return -ENOMEM;
*p = (BPFProgram) {
.kernel_fd = TAKE_FD(fd),
.prog_type = BPF_PROG_TYPE_UNSPEC,
.attached_path = TAKE_PTR(unescaped),
.attached_type = at,
};
if (*bpfp)
bpf_program_free(*bpfp);
*bpfp = TAKE_PTR(p);
return 0;
}
int bpf_program_deserialize_attachment_set(const char *v, FDSet *fds, Set **bpfsetp) {
BPFProgram *p = NULL;
int r;
assert(v);
assert(bpfsetp);
r = bpf_program_deserialize_attachment(v, fds, &p);
if (r < 0)
return r;
r = set_ensure_consume(bpfsetp, &bpf_program_hash_ops, p);
if (r < 0)
return r;
return 0;
}
| 16,524 | 31.149805 | 123 |
c
|
null |
systemd-main/src/shared/bpf-program.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/bpf.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/syscall.h>
#include "fdset.h"
#include "list.h"
#include "macro.h"
typedef struct BPFProgram BPFProgram;
/* This encapsulates three different concepts: the loaded BPF program, the BPF code, and the attachment to a
* cgroup. Typically our BPF programs go through all three stages: we build the code, we load it, and finally
* we attach it, but it might happen that we operate with programs that aren't loaded or aren't attached, or
* where we don't have the code. */
struct BPFProgram {
/* The loaded BPF program, if loaded */
int kernel_fd;
uint32_t prog_type;
char *prog_name;
/* The code of it BPF program, if known */
size_t n_instructions;
struct bpf_insn *instructions;
/* The cgroup path the program is attached to, if it is attached. If non-NULL bpf_program_unref()
* will detach on destruction. */
char *attached_path;
int attached_type;
uint32_t attached_flags;
};
int bpf_program_new(uint32_t prog_type, const char *prog_name, BPFProgram **ret);
int bpf_program_new_from_bpffs_path(const char *path, BPFProgram **ret);
BPFProgram *bpf_program_free(BPFProgram *p);
int bpf_program_add_instructions(BPFProgram *p, const struct bpf_insn *insn, size_t count);
int bpf_program_load_kernel(BPFProgram *p, char *log_buf, size_t log_size);
int bpf_program_load_from_bpf_fs(BPFProgram *p, const char *path);
int bpf_program_cgroup_attach(BPFProgram *p, int type, const char *path, uint32_t flags);
int bpf_program_cgroup_detach(BPFProgram *p);
int bpf_program_pin(int prog_fd, const char *bpffs_path);
int bpf_program_get_id_by_fd(int prog_fd, uint32_t *ret_id);
int bpf_program_serialize_attachment(FILE *f, FDSet *fds, const char *key, BPFProgram *p);
int bpf_program_serialize_attachment_set(FILE *f, FDSet *fds, const char *key, Set *set);
int bpf_program_deserialize_attachment(const char *v, FDSet *fds, BPFProgram **bpfp);
int bpf_program_deserialize_attachment_set(const char *v, FDSet *fds, Set **bpfsetp);
extern const struct hash_ops bpf_program_hash_ops;
int bpf_map_new(const char *name, enum bpf_map_type type, size_t key_size, size_t value_size,
size_t max_entries, uint32_t flags);
int bpf_map_update_element(int fd, const void *key, void *value);
int bpf_map_lookup_element(int fd, const void *key, void *value);
int bpf_cgroup_attach_type_from_string(const char *str) _pure_;
const char *bpf_cgroup_attach_type_to_string(int attach_type) _const_;
DEFINE_TRIVIAL_CLEANUP_FUNC(BPFProgram*, bpf_program_free);
| 2,695 | 39.848485 | 109 |
h
|
null |
systemd-main/src/shared/bridge-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <netinet/in.h>
#include <linux/if_bridge.h>
#include "conf-parser.h"
typedef enum BridgeState {
NETDEV_BRIDGE_STATE_DISABLED = BR_STATE_DISABLED,
NETDEV_BRIDGE_STATE_LISTENING = BR_STATE_LISTENING,
NETDEV_BRIDGE_STATE_LEARNING = BR_STATE_LEARNING,
NETDEV_BRIDGE_STATE_FORWARDING = BR_STATE_FORWARDING,
NETDEV_BRIDGE_STATE_BLOCKING = BR_STATE_BLOCKING,
_NETDEV_BRIDGE_STATE_MAX,
_NETDEV_BRIDGE_STATE_INVALID = -EINVAL,
} BridgeState;
const char *bridge_state_to_string(BridgeState d) _const_;
BridgeState bridge_state_from_string(const char *d) _pure_;
| 692 | 32 | 61 |
h
|
null |
systemd-main/src/shared/bus-get-properties.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bus-get-properties.h"
#include "rlimit-util.h"
#include "stdio-util.h"
#include "string-util.h"
int bus_property_get_bool(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
int b = *(bool*) userdata;
return sd_bus_message_append_basic(reply, 'b', &b);
}
int bus_property_set_bool(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *value,
void *userdata,
sd_bus_error *error) {
int b, r;
r = sd_bus_message_read(value, "b", &b);
if (r < 0)
return r;
*(bool*) userdata = b;
return 0;
}
int bus_property_get_tristate(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
/* Defaults to false. */
int b = (*(int*) userdata) > 0;
return sd_bus_message_append_basic(reply, 'b', &b);
}
int bus_property_get_id128(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
sd_id128_t *id = userdata;
if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
return sd_bus_message_append(reply, "ay", 0);
else
return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
}
#if __SIZEOF_SIZE_T__ != 8
int bus_property_get_size(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
uint64_t sz = *(size_t*) userdata;
return sd_bus_message_append_basic(reply, 't', &sz);
}
#endif
#if __SIZEOF_LONG__ != 8
int bus_property_get_long(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
int64_t l = *(long*) userdata;
return sd_bus_message_append_basic(reply, 'x', &l);
}
int bus_property_get_ulong(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
uint64_t ul = *(unsigned long*) userdata;
return sd_bus_message_append_basic(reply, 't', &ul);
}
#endif
int bus_property_get_rlimit(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
const char *is_soft;
struct rlimit *rl;
uint64_t u;
rlim_t x;
assert(bus);
assert(reply);
assert(userdata);
is_soft = endswith(property, "Soft");
rl = *(struct rlimit**) userdata;
if (rl)
x = is_soft ? rl->rlim_cur : rl->rlim_max;
else {
struct rlimit buf = {};
const char *s, *p;
int z;
/* Chop off "Soft" suffix */
s = is_soft ? strndupa_safe(property, is_soft - property) : property;
/* Skip over any prefix, such as "Default" */
assert_se(p = strstrafter(s, "Limit"));
z = rlimit_from_string(p);
assert(z >= 0);
(void) getrlimit(z, &buf);
x = is_soft ? buf.rlim_cur : buf.rlim_max;
}
/* rlim_t might have different sizes, let's map RLIMIT_INFINITY to UINT64_MAX, so that it is the same on all
* archs */
u = x == RLIM_INFINITY ? UINT64_MAX : (uint64_t) x;
return sd_bus_message_append(reply, "t", u);
}
| 4,592 | 26.502994 | 116 |
c
|
null |
systemd-main/src/shared/bus-log-control-api.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "bus-get-properties.h"
#include "bus-log-control-api.h"
#include "bus-util.h"
#include "log.h"
#include "sd-bus.h"
#include "syslog-util.h"
int bus_property_get_log_level(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *reply,
void *userdata,
sd_bus_error *error) {
_cleanup_free_ char *t = NULL;
int r;
assert(bus);
assert(reply);
r = log_level_to_string_alloc(log_get_max_level(), &t);
if (r < 0)
return r;
return sd_bus_message_append(reply, "s", t);
}
int bus_property_set_log_level(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *value,
void *userdata,
sd_bus_error *error) {
const char *t;
int r;
assert(bus);
assert(value);
r = sd_bus_message_read(value, "s", &t);
if (r < 0)
return r;
r = log_level_from_string(t);
if (r < 0)
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid log level '%s'", t);
log_info("Setting log level to %s.", t);
log_set_max_level(r);
return 0;
}
BUS_DEFINE_PROPERTY_GET_GLOBAL(bus_property_get_log_target, "s", log_target_to_string(log_get_target()));
int bus_property_set_log_target(
sd_bus *bus,
const char *path,
const char *interface,
const char *property,
sd_bus_message *value,
void *userdata,
sd_bus_error *error) {
LogTarget target;
const char *t;
int r;
assert(bus);
assert(value);
r = sd_bus_message_read(value, "s", &t);
if (r < 0)
return r;
target = log_target_from_string(t);
if (target < 0)
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid log target '%s'", t);
log_info("Setting log target to %s.", log_target_to_string(target));
log_set_target_and_open(target);
return 0;
}
BUS_DEFINE_PROPERTY_GET_GLOBAL(bus_property_get_syslog_identifier, "s", program_invocation_short_name);
static const sd_bus_vtable log_control_vtable[] = {
SD_BUS_VTABLE_START(0),
SD_BUS_WRITABLE_PROPERTY("LogLevel", "s", bus_property_get_log_level, bus_property_set_log_level, 0, 0),
SD_BUS_WRITABLE_PROPERTY("LogTarget", "s", bus_property_get_log_target, bus_property_set_log_target, 0, 0),
SD_BUS_PROPERTY("SyslogIdentifier", "s", bus_property_get_syslog_identifier, 0, 0),
/* One of those days we might want to add a similar, second interface to cover common service
* operations such as Reload(), Reexecute(), Exit() … and maybe some properties exposing version
* number and other meta-data of the service. */
SD_BUS_VTABLE_END,
};
const BusObjectImplementation log_control_object = {
"/org/freedesktop/LogControl1",
"org.freedesktop.LogControl1",
.vtables = BUS_VTABLES(log_control_vtable),
};
| 3,406 | 28.626087 | 115 |
c
|
null |
systemd-main/src/shared/bus-map-properties.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bus-map-properties.h"
#include "alloc-util.h"
#include "bus-util.h"
#include "strv.h"
#include "bus-message.h"
int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
sd_id128_t *p = userdata;
const void *v;
size_t n;
int r;
r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
if (r < 0)
return bus_log_parse_error_debug(r);
if (n == 0)
*p = SD_ID128_NULL;
else if (n == 16)
memcpy((*p).bytes, v, n);
else
return -EINVAL;
return 0;
}
int bus_map_strv_sort(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
_cleanup_strv_free_ char **l = NULL;
char ***p = userdata;
int r;
r = sd_bus_message_read_strv_extend(m, &l);
if (r < 0)
return bus_log_parse_error_debug(r);
r = strv_extend_strv(p, l, false);
if (r < 0)
return bus_log_parse_error_debug(r);
strv_sort(*p);
return 0;
}
static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, unsigned flags, sd_bus_error *error, void *userdata) {
char type;
int r;
r = sd_bus_message_peek_type(m, &type, NULL);
if (r < 0)
return bus_log_parse_error_debug(r);
switch (type) {
case SD_BUS_TYPE_STRING:
case SD_BUS_TYPE_OBJECT_PATH: {
const char **p = userdata;
const char *s;
r = sd_bus_message_read_basic(m, type, &s);
if (r < 0)
return bus_log_parse_error_debug(r);
if (isempty(s))
s = NULL;
if (flags & BUS_MAP_STRDUP)
return free_and_strdup((char **) userdata, s);
*p = s;
return 0;
}
case SD_BUS_TYPE_ARRAY: {
_cleanup_strv_free_ char **l = NULL;
char ***p = userdata;
r = sd_bus_message_read_strv_extend(m, &l);
if (r < 0)
return bus_log_parse_error_debug(r);
return strv_extend_strv(p, l, false);
}
case SD_BUS_TYPE_BOOLEAN: {
int b;
r = sd_bus_message_read_basic(m, type, &b);
if (r < 0)
return bus_log_parse_error_debug(r);
if (flags & BUS_MAP_BOOLEAN_AS_BOOL)
*(bool*) userdata = b;
else
*(int*) userdata = b;
return 0;
}
case SD_BUS_TYPE_INT32:
case SD_BUS_TYPE_UINT32: {
uint32_t u, *p = userdata;
r = sd_bus_message_read_basic(m, type, &u);
if (r < 0)
return bus_log_parse_error_debug(r);
*p = u;
return 0;
}
case SD_BUS_TYPE_INT64:
case SD_BUS_TYPE_UINT64: {
uint64_t t, *p = userdata;
r = sd_bus_message_read_basic(m, type, &t);
if (r < 0)
return bus_log_parse_error_debug(r);
*p = t;
return 0;
}
case SD_BUS_TYPE_DOUBLE: {
double d, *p = userdata;
r = sd_bus_message_read_basic(m, type, &d);
if (r < 0)
return bus_log_parse_error_debug(r);
*p = d;
return 0;
}}
return -EOPNOTSUPP;
}
int bus_message_map_all_properties(
sd_bus_message *m,
const struct bus_properties_map *map,
unsigned flags,
sd_bus_error *error,
void *userdata) {
int r;
assert(m);
assert(map);
r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
if (r < 0)
return bus_log_parse_error_debug(r);
while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
const struct bus_properties_map *prop;
const char *member;
const char *contents;
void *v;
unsigned i;
r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
if (r < 0)
return bus_log_parse_error_debug(r);
for (i = 0, prop = NULL; map[i].member; i++)
if (streq(map[i].member, member)) {
prop = &map[i];
break;
}
if (prop) {
r = sd_bus_message_peek_type(m, NULL, &contents);
if (r < 0)
return bus_log_parse_error_debug(r);
r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
if (r < 0)
return bus_log_parse_error_debug(r);
v = (uint8_t *)userdata + prop->offset;
if (map[i].set)
r = prop->set(sd_bus_message_get_bus(m), member, m, error, v);
else
r = map_basic(sd_bus_message_get_bus(m), member, m, flags, error, v);
if (r < 0)
return bus_log_parse_error_debug(r);
r = sd_bus_message_exit_container(m);
if (r < 0)
return bus_log_parse_error_debug(r);
} else {
r = sd_bus_message_skip(m, "v");
if (r < 0)
return bus_log_parse_error_debug(r);
}
r = sd_bus_message_exit_container(m);
if (r < 0)
return bus_log_parse_error_debug(r);
}
if (r < 0)
return bus_log_parse_error_debug(r);
r = sd_bus_message_exit_container(m);
if (r < 0)
return bus_log_parse_error_debug(r);
return r;
}
int bus_map_all_properties(
sd_bus *bus,
const char *destination,
const char *path,
const struct bus_properties_map *map,
unsigned flags,
sd_bus_error *error,
sd_bus_message **reply,
void *userdata) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
int r;
assert(bus);
assert(destination);
assert(path);
assert(map);
assert(reply || (flags & BUS_MAP_STRDUP));
r = sd_bus_call_method(
bus,
destination,
path,
"org.freedesktop.DBus.Properties",
"GetAll",
error,
&m,
"s", "");
if (r < 0)
return r;
r = bus_message_map_all_properties(m, map, flags, error, userdata);
if (r < 0)
return r;
if (reply)
*reply = sd_bus_message_ref(m);
return r;
}
| 7,580 | 29.083333 | 127 |
c
|
null |
systemd-main/src/shared/bus-message-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bus-message-util.h"
#include "resolve-util.h"
int bus_message_read_ifindex(sd_bus_message *message, sd_bus_error *error, int *ret) {
int ifindex, r;
assert(message);
assert(ret);
assert_cc(sizeof(int) == sizeof(int32_t));
r = sd_bus_message_read(message, "i", &ifindex);
if (r < 0)
return r;
if (ifindex <= 0)
return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid interface index");
*ret = ifindex;
return 0;
}
int bus_message_read_family(sd_bus_message *message, sd_bus_error *error, int *ret) {
int family, r;
assert(message);
assert(ret);
assert_cc(sizeof(int) == sizeof(int32_t));
r = sd_bus_message_read(message, "i", &family);
if (r < 0)
return r;
if (!IN_SET(family, AF_INET, AF_INET6))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Unknown address family %i", family);
*ret = family;
return 0;
}
int bus_message_read_in_addr_auto(sd_bus_message *message, sd_bus_error *error, int *ret_family, union in_addr_union *ret_addr) {
int family, r;
const void *d;
size_t sz;
assert(message);
r = sd_bus_message_read(message, "i", &family);
if (r < 0)
return r;
r = sd_bus_message_read_array(message, 'y', &d, &sz);
if (r < 0)
return r;
if (!IN_SET(family, AF_INET, AF_INET6))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Unknown address family %i", family);
if (sz != FAMILY_ADDRESS_SIZE(family))
return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid address size");
if (ret_family)
*ret_family = family;
if (ret_addr)
memcpy(ret_addr, d, sz);
return 0;
}
static int bus_message_read_dns_one(
sd_bus_message *message,
sd_bus_error *error,
bool extended,
int *ret_family,
union in_addr_union *ret_address,
uint16_t *ret_port,
const char **ret_server_name) {
const char *server_name = NULL;
union in_addr_union a;
uint16_t port = 0;
int family, r;
assert(message);
assert(ret_family);
assert(ret_address);
assert(ret_port);
assert(ret_server_name);
r = sd_bus_message_enter_container(message, 'r', extended ? "iayqs" : "iay");
if (r <= 0)
return r;
r = bus_message_read_in_addr_auto(message, error, &family, &a);
if (r < 0)
return r;
if (!dns_server_address_valid(family, &a)) {
r = sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid DNS server address");
assert(r < 0);
return r;
}
if (extended) {
r = sd_bus_message_read(message, "q", &port);
if (r < 0)
return r;
if (IN_SET(port, 53, 853))
port = 0;
r = sd_bus_message_read(message, "s", &server_name);
if (r < 0)
return r;
}
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
*ret_family = family;
*ret_address = a;
*ret_port = port;
*ret_server_name = server_name;
return 1;
}
int bus_message_read_dns_servers(
sd_bus_message *message,
sd_bus_error *error,
bool extended,
struct in_addr_full ***ret_dns,
size_t *ret_n_dns) {
struct in_addr_full **dns = NULL;
size_t n = 0;
int r;
assert(message);
assert(ret_dns);
assert(ret_n_dns);
r = sd_bus_message_enter_container(message, 'a', extended ? "(iayqs)" : "(iay)");
if (r < 0)
return r;
for (;;) {
const char *server_name;
union in_addr_union a;
uint16_t port;
int family;
r = bus_message_read_dns_one(message, error, extended, &family, &a, &port, &server_name);
if (r < 0)
goto clear;
if (r == 0)
break;
if (!GREEDY_REALLOC(dns, n+1)) {
r = -ENOMEM;
goto clear;
}
r = in_addr_full_new(family, &a, port, 0, server_name, dns + n);
if (r < 0)
goto clear;
n++;
}
*ret_dns = TAKE_PTR(dns);
*ret_n_dns = n;
return 0;
clear:
for (size_t i = 0; i < n; i++)
in_addr_full_free(dns[i]);
free(dns);
return r;
}
| 5,192 | 26.919355 | 129 |
c
|
null |
systemd-main/src/shared/bus-message-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "in-addr-util.h"
#include "socket-netlink.h"
int bus_message_read_ifindex(sd_bus_message *message, sd_bus_error *error, int *ret);
int bus_message_read_family(sd_bus_message *message, sd_bus_error *error, int *ret);
int bus_message_read_in_addr_auto(sd_bus_message *message, sd_bus_error *error, int *ret_family, union in_addr_union *ret_addr);
int bus_message_read_dns_servers(
sd_bus_message *message,
sd_bus_error *error,
bool extended,
struct in_addr_full ***ret_dns,
size_t *ret_n_dns);
| 707 | 36.263158 | 128 |
h
|
null |
systemd-main/src/shared/bus-object.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bus-introspect.h"
#include "bus-object.h"
#include "macro.h"
#include "string-util.h"
#include "strv.h"
int bus_add_implementation(sd_bus *bus, const BusObjectImplementation *impl, void *userdata) {
int r;
log_debug("Registering bus object implementation for path=%s iface=%s", impl->path, impl->interface);
for (const sd_bus_vtable **p = impl->vtables; p && *p; p++) {
r = sd_bus_add_object_vtable(bus, NULL,
impl->path,
impl->interface,
*p,
userdata);
if (r < 0)
return log_error_errno(r, "Failed to register bus path %s with interface %s: %m",
impl->path,
impl->interface);
}
for (const BusObjectVtablePair *p = impl->fallback_vtables; p && p->vtable; p++) {
r = sd_bus_add_fallback_vtable(bus, NULL,
impl->path,
impl->interface,
p->vtable,
p->object_find,
userdata);
if (r < 0)
return log_error_errno(r, "Failed to register bus path %s with interface %s: %m",
impl->path,
impl->interface);
}
if (impl->node_enumerator) {
r = sd_bus_add_node_enumerator(bus, NULL,
impl->path,
impl->node_enumerator,
userdata);
if (r < 0)
return log_error_errno(r, "Failed to add node enumerator for %s: %m",
impl->path);
}
if (impl->manager) {
r = sd_bus_add_object_manager(bus, NULL, impl->path);
if (r < 0)
return log_error_errno(r, "Failed to add object manager for %s: %m", impl->path);
}
for (size_t i = 0; impl->children && impl->children[i]; i++) {
r = bus_add_implementation(bus, impl->children[i], userdata);
if (r < 0)
return r;
}
return 0;
}
static const BusObjectImplementation* find_implementation(
const char *pattern,
const BusObjectImplementation* const* bus_objects) {
for (size_t i = 0; bus_objects && bus_objects[i]; i++) {
const BusObjectImplementation *impl = bus_objects[i];
if (STR_IN_SET(pattern, impl->path, impl->interface))
return impl;
impl = find_implementation(pattern, impl->children);
if (impl)
return impl;
}
return NULL;
}
static int bus_introspect_implementation(
struct introspect *intro,
const BusObjectImplementation *impl) {
int r;
for (const sd_bus_vtable **p = impl->vtables; p && *p; p++) {
r = introspect_write_interface(intro, impl->interface, *p);
if (r < 0)
return log_error_errno(r, "Failed to write introspection data: %m");
}
for (const BusObjectVtablePair *p = impl->fallback_vtables; p && p->vtable; p++) {
r = introspect_write_interface(intro, impl->interface, p->vtable);
if (r < 0)
return log_error_errno(r, "Failed to write introspection data: %m");
}
return 0;
}
static void list_paths(
FILE *out,
const BusObjectImplementation* const* bus_objects) {
for (size_t i = 0; bus_objects[i]; i++) {
fprintf(out, "%s\t%s\n", bus_objects[i]->path, bus_objects[i]->interface);
if (bus_objects[i]->children)
list_paths(out, bus_objects[i]->children);
}
}
int bus_introspect_implementations(
FILE *out,
const char *pattern,
const BusObjectImplementation* const* bus_objects) {
const BusObjectImplementation *impl, *main_impl = NULL;
_cleanup_free_ char *s = NULL;
int r;
if (streq(pattern, "list")) {
list_paths(out, bus_objects);
return 0;
}
struct introspect intro = {};
bool is_interface = sd_bus_interface_name_is_valid(pattern);
impl = find_implementation(pattern, bus_objects);
if (!impl)
return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
"%s %s not found",
is_interface ? "Interface" : "Object path",
pattern);
/* We use trusted=false here to get all the @org.freedesktop.systemd1.Privileged annotations. */
r = introspect_begin(&intro, false);
if (r < 0)
return log_error_errno(r, "Failed to write introspection data: %m");
r = introspect_write_default_interfaces(&intro, impl->manager);
if (r < 0)
return log_error_errno(r, "Failed to write introspection data: %m");
/* Check if there is a non-fallback path that applies to the given interface, also
* print it. This is useful in the case of units: o.fd.systemd1.Service is declared
* as a fallback vtable for o/fd/systemd1/unit, and we also want to print
* o.fd.systemd1.Unit, which is the non-fallback implementation. */
if (impl->fallback_vtables && is_interface)
main_impl = find_implementation(impl->path, bus_objects);
if (main_impl)
bus_introspect_implementation(&intro, main_impl);
if (impl != main_impl)
bus_introspect_implementation(&intro, impl);
_cleanup_ordered_set_free_ OrderedSet *nodes = NULL;
for (size_t i = 0; impl->children && impl->children[i]; i++) {
r = ordered_set_put_strdup(&nodes, impl->children[i]->path);
if (r < 0)
return log_oom();
}
r = introspect_write_child_nodes(&intro, nodes, impl->path);
if (r < 0)
return r;
r = introspect_finish(&intro, &s);
if (r < 0)
return log_error_errno(r, "Failed to write introspection data: %m");
fputs(s, out);
return 0;
}
| 6,935 | 37.966292 | 109 |
c
|
null |
systemd-main/src/shared/bus-object.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stdio.h>
#include "sd-bus.h"
typedef struct BusObjectImplementation BusObjectImplementation;
typedef struct BusObjectVtablePair {
const sd_bus_vtable *vtable;
sd_bus_object_find_t object_find;
} BusObjectVtablePair;
struct BusObjectImplementation {
const char *path;
const char *interface;
const sd_bus_vtable **vtables;
const BusObjectVtablePair *fallback_vtables;
sd_bus_node_enumerator_t node_enumerator;
bool manager;
const BusObjectImplementation **children;
};
#define BUS_VTABLES(...) ((const sd_bus_vtable* []){ __VA_ARGS__, NULL })
#define BUS_FALLBACK_VTABLES(...) ((const BusObjectVtablePair[]) { __VA_ARGS__, {} })
#define BUS_IMPLEMENTATIONS(...) ((const BusObjectImplementation* []) { __VA_ARGS__, NULL })
int bus_add_implementation(sd_bus *bus, const BusObjectImplementation *impl, void *userdata);
int bus_introspect_implementations(
FILE *out,
const char *pattern,
const BusObjectImplementation* const* bus_objects);
| 1,154 | 32 | 93 |
h
|
null |
systemd-main/src/shared/bus-unit-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "install.h"
#include "unit-def.h"
typedef struct UnitInfo {
const char *machine;
const char *id;
const char *description;
const char *load_state;
const char *active_state;
const char *sub_state;
const char *following;
const char *unit_path;
uint32_t job_id;
const char *job_type;
const char *job_path;
} UnitInfo;
int bus_parse_unit_info(sd_bus_message *message, UnitInfo *u);
int bus_append_unit_property_assignment(sd_bus_message *m, UnitType t, const char *assignment);
int bus_append_unit_property_assignment_many(sd_bus_message *m, UnitType t, char **l);
int bus_deserialize_and_dump_unit_file_changes(sd_bus_message *m, bool quiet);
int unit_load_state(sd_bus *bus, const char *name, char **load_state);
int unit_info_compare(const UnitInfo *a, const UnitInfo *b);
int bus_service_manager_reload(sd_bus *bus);
| 1,004 | 27.714286 | 95 |
h
|
null |
systemd-main/src/shared/bus-wait-for-jobs.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "bus-wait-for-jobs.h"
#include "set.h"
#include "bus-util.h"
#include "bus-internal.h"
#include "unit-def.h"
#include "escape.h"
#include "strv.h"
typedef struct BusWaitForJobs {
sd_bus *bus;
/* The set of jobs to wait for, as bus object paths */
Set *jobs;
/* The unit name and job result of the last Job message */
char *name;
char *result;
sd_bus_slot *slot_job_removed;
sd_bus_slot *slot_disconnected;
} BusWaitForJobs;
static int match_disconnected(sd_bus_message *m, void *userdata, sd_bus_error *error) {
assert(m);
log_error("Warning! D-Bus connection terminated.");
sd_bus_close(sd_bus_message_get_bus(m));
return 0;
}
static int match_job_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
const char *path, *unit, *result;
BusWaitForJobs *d = ASSERT_PTR(userdata);
uint32_t id;
char *found;
int r;
assert(m);
r = sd_bus_message_read(m, "uoss", &id, &path, &unit, &result);
if (r < 0) {
bus_log_parse_error(r);
return 0;
}
found = set_remove(d->jobs, (char*) path);
if (!found)
return 0;
free(found);
(void) free_and_strdup(&d->result, empty_to_null(result));
(void) free_and_strdup(&d->name, empty_to_null(unit));
return 0;
}
BusWaitForJobs* bus_wait_for_jobs_free(BusWaitForJobs *d) {
if (!d)
return NULL;
set_free(d->jobs);
sd_bus_slot_unref(d->slot_disconnected);
sd_bus_slot_unref(d->slot_job_removed);
sd_bus_unref(d->bus);
free(d->name);
free(d->result);
return mfree(d);
}
int bus_wait_for_jobs_new(sd_bus *bus, BusWaitForJobs **ret) {
_cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *d = NULL;
int r;
assert(bus);
assert(ret);
d = new(BusWaitForJobs, 1);
if (!d)
return -ENOMEM;
*d = (BusWaitForJobs) {
.bus = sd_bus_ref(bus),
};
/* When we are a bus client we match by sender. Direct
* connections OTOH have no initialized sender field, and
* hence we ignore the sender then */
r = sd_bus_match_signal_async(
bus,
&d->slot_job_removed,
bus->bus_client ? "org.freedesktop.systemd1" : NULL,
"/org/freedesktop/systemd1",
"org.freedesktop.systemd1.Manager",
"JobRemoved",
match_job_removed, NULL, d);
if (r < 0)
return r;
r = sd_bus_match_signal_async(
bus,
&d->slot_disconnected,
"org.freedesktop.DBus.Local",
NULL,
"org.freedesktop.DBus.Local",
"Disconnected",
match_disconnected, NULL, d);
if (r < 0)
return r;
*ret = TAKE_PTR(d);
return 0;
}
static int bus_process_wait(sd_bus *bus) {
int r;
for (;;) {
r = sd_bus_process(bus, NULL);
if (r < 0)
return r;
if (r > 0)
return 0;
r = sd_bus_wait(bus, UINT64_MAX);
if (r < 0)
return r;
}
}
static int bus_job_get_service_result(BusWaitForJobs *d, char **result) {
_cleanup_free_ char *dbus_path = NULL;
assert(d);
assert(d->name);
assert(result);
if (!endswith(d->name, ".service"))
return -EINVAL;
dbus_path = unit_dbus_path_from_name(d->name);
if (!dbus_path)
return -ENOMEM;
return sd_bus_get_property_string(d->bus,
"org.freedesktop.systemd1",
dbus_path,
"org.freedesktop.systemd1.Service",
"Result",
NULL,
result);
}
static void log_job_error_with_service_result(const char* service, const char *result, const char* const* extra_args) {
_cleanup_free_ char *service_shell_quoted = NULL;
const char *systemctl = "systemctl", *journalctl = "journalctl";
static const struct {
const char *result, *explanation;
} explanations[] = {
{ "resources", "of unavailable resources or another system error" },
{ "protocol", "the service did not take the steps required by its unit configuration" },
{ "timeout", "a timeout was exceeded" },
{ "exit-code", "the control process exited with error code" },
{ "signal", "a fatal signal was delivered to the control process" },
{ "core-dump", "a fatal signal was delivered causing the control process to dump core" },
{ "watchdog", "the service failed to send watchdog ping" },
{ "start-limit", "start of the service was attempted too often" }
};
assert(service);
service_shell_quoted = shell_maybe_quote(service, 0);
if (!strv_isempty((char**) extra_args)) {
_cleanup_free_ char *t = NULL;
t = strv_join((char**) extra_args, " ");
systemctl = strjoina("systemctl ", t ?: "<args>");
journalctl = strjoina("journalctl ", t ?: "<args>");
}
if (!isempty(result)) {
size_t i;
for (i = 0; i < ELEMENTSOF(explanations); ++i)
if (streq(result, explanations[i].result))
break;
if (i < ELEMENTSOF(explanations)) {
log_error("Job for %s failed because %s.\n"
"See \"%s status %s\" and \"%s -xeu %s\" for details.\n",
service,
explanations[i].explanation,
systemctl,
service_shell_quoted ?: "<service>",
journalctl,
service_shell_quoted ?: "<service>");
goto finish;
}
}
log_error("Job for %s failed.\n"
"See \"%s status %s\" and \"%s -xeu %s\" for details.\n",
service,
systemctl,
service_shell_quoted ?: "<service>",
journalctl,
service_shell_quoted ?: "<service>");
finish:
/* For some results maybe additional explanation is required */
if (streq_ptr(result, "start-limit"))
log_info("To force a start use \"%1$s reset-failed %2$s\"\n"
"followed by \"%1$s start %2$s\" again.",
systemctl,
service_shell_quoted ?: "<service>");
}
static int check_wait_response(BusWaitForJobs *d, bool quiet, const char* const* extra_args) {
assert(d);
assert(d->name);
assert(d->result);
if (!quiet) {
if (streq(d->result, "canceled"))
log_error("Job for %s canceled.", strna(d->name));
else if (streq(d->result, "timeout"))
log_error("Job for %s timed out.", strna(d->name));
else if (streq(d->result, "dependency"))
log_error("A dependency job for %s failed. See 'journalctl -xe' for details.", strna(d->name));
else if (streq(d->result, "invalid"))
log_error("%s is not active, cannot reload.", strna(d->name));
else if (streq(d->result, "assert"))
log_error("Assertion failed on job for %s.", strna(d->name));
else if (streq(d->result, "unsupported"))
log_error("Operation on or unit type of %s not supported on this system.", strna(d->name));
else if (streq(d->result, "collected"))
log_error("Queued job for %s was garbage collected.", strna(d->name));
else if (streq(d->result, "once"))
log_error("Unit %s was started already once and can't be started again.", strna(d->name));
else if (!STR_IN_SET(d->result, "done", "skipped")) {
if (d->name && endswith(d->name, ".service")) {
_cleanup_free_ char *result = NULL;
int q;
q = bus_job_get_service_result(d, &result);
if (q < 0)
log_debug_errno(q, "Failed to get Result property of unit %s: %m", d->name);
log_job_error_with_service_result(d->name, result, extra_args);
} else
log_error("Job failed. See \"journalctl -xe\" for details.");
}
}
if (STR_IN_SET(d->result, "canceled", "collected"))
return -ECANCELED;
else if (streq(d->result, "timeout"))
return -ETIME;
else if (streq(d->result, "dependency"))
return -EIO;
else if (streq(d->result, "invalid"))
return -ENOEXEC;
else if (streq(d->result, "assert"))
return -EPROTO;
else if (streq(d->result, "unsupported"))
return -EOPNOTSUPP;
else if (streq(d->result, "once"))
return -ESTALE;
else if (STR_IN_SET(d->result, "done", "skipped"))
return 0;
return log_debug_errno(SYNTHETIC_ERRNO(EIO),
"Unexpected job result, assuming server side newer than us: %s", d->result);
}
int bus_wait_for_jobs(BusWaitForJobs *d, bool quiet, const char* const* extra_args) {
int r = 0;
assert(d);
while (!set_isempty(d->jobs)) {
int q;
q = bus_process_wait(d->bus);
if (q < 0)
return log_error_errno(q, "Failed to wait for response: %m");
if (d->name && d->result) {
q = check_wait_response(d, quiet, extra_args);
/* Return the first error as it is most likely to be
* meaningful. */
if (q < 0 && r == 0)
r = q;
log_full_errno_zerook(LOG_DEBUG, q,
"Got result %s/%m for job %s", d->result, d->name);
}
d->name = mfree(d->name);
d->result = mfree(d->result);
}
return r;
}
int bus_wait_for_jobs_add(BusWaitForJobs *d, const char *path) {
assert(d);
return set_put_strdup(&d->jobs, path);
}
int bus_wait_for_jobs_one(BusWaitForJobs *d, const char *path, bool quiet, const char* const* extra_args) {
int r;
r = bus_wait_for_jobs_add(d, path);
if (r < 0)
return log_oom();
return bus_wait_for_jobs(d, quiet, extra_args);
}
| 11,753 | 34.191617 | 119 |
c
|
null |
systemd-main/src/shared/bus-wait-for-jobs.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-bus.h"
#include "macro.h"
typedef struct BusWaitForJobs BusWaitForJobs;
int bus_wait_for_jobs_new(sd_bus *bus, BusWaitForJobs **ret);
BusWaitForJobs* bus_wait_for_jobs_free(BusWaitForJobs *d);
int bus_wait_for_jobs_add(BusWaitForJobs *d, const char *path);
int bus_wait_for_jobs(BusWaitForJobs *d, bool quiet, const char* const* extra_args);
int bus_wait_for_jobs_one(BusWaitForJobs *d, const char *path, bool quiet, const char* const* extra_args);
DEFINE_TRIVIAL_CLEANUP_FUNC(BusWaitForJobs*, bus_wait_for_jobs_free);
| 599 | 34.294118 | 106 |
h
|
null |
systemd-main/src/shared/bus-wait-for-units.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "bus-error.h"
#include "bus-map-properties.h"
#include "bus-wait-for-units.h"
#include "hashmap.h"
#include "string-util.h"
#include "strv.h"
#include "unit-def.h"
typedef struct WaitForItem {
BusWaitForUnits *parent;
BusWaitForUnitsFlags flags;
char *bus_path;
sd_bus_slot *slot_get_all;
sd_bus_slot *slot_properties_changed;
bus_wait_for_units_unit_callback unit_callback;
void *userdata;
char *active_state;
uint32_t job_id;
char *clean_result;
} WaitForItem;
typedef struct BusWaitForUnits {
sd_bus *bus;
sd_bus_slot *slot_disconnected;
Hashmap *items;
bus_wait_for_units_ready_callback ready_callback;
void *userdata;
WaitForItem *current;
BusWaitForUnitsState state;
bool has_failed:1;
} BusWaitForUnits;
static WaitForItem *wait_for_item_free(WaitForItem *item) {
int r;
if (!item)
return NULL;
if (item->parent) {
if (FLAGS_SET(item->flags, BUS_WAIT_REFFED) && item->bus_path && item->parent->bus) {
r = sd_bus_call_method_async(
item->parent->bus,
NULL,
"org.freedesktop.systemd1",
item->bus_path,
"org.freedesktop.systemd1.Unit",
"Unref",
NULL,
NULL,
NULL);
if (r < 0)
log_debug_errno(r, "Failed to drop reference to unit %s, ignoring: %m", item->bus_path);
}
assert_se(hashmap_remove(item->parent->items, item->bus_path) == item);
if (item->parent->current == item)
item->parent->current = NULL;
}
sd_bus_slot_unref(item->slot_properties_changed);
sd_bus_slot_unref(item->slot_get_all);
free(item->bus_path);
free(item->active_state);
free(item->clean_result);
return mfree(item);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(WaitForItem*, wait_for_item_free);
static void call_unit_callback_and_wait(BusWaitForUnits *d, WaitForItem *item, bool good) {
d->current = item;
if (item->unit_callback)
item->unit_callback(d, item->bus_path, good, item->userdata);
wait_for_item_free(item);
}
static void bus_wait_for_units_clear(BusWaitForUnits *d) {
WaitForItem *item;
assert(d);
d->slot_disconnected = sd_bus_slot_unref(d->slot_disconnected);
d->bus = sd_bus_unref(d->bus);
while ((item = hashmap_first(d->items)))
call_unit_callback_and_wait(d, item, false);
d->items = hashmap_free(d->items);
}
static int match_disconnected(sd_bus_message *m, void *userdata, sd_bus_error *error) {
BusWaitForUnits *d = ASSERT_PTR(userdata);
assert(m);
log_error("Warning! D-Bus connection terminated.");
bus_wait_for_units_clear(d);
if (d->ready_callback)
d->ready_callback(d, false, d->userdata);
else /* If no ready callback is specified close the connection so that the event loop exits */
sd_bus_close(sd_bus_message_get_bus(m));
return 0;
}
int bus_wait_for_units_new(sd_bus *bus, BusWaitForUnits **ret) {
_cleanup_(bus_wait_for_units_freep) BusWaitForUnits *d = NULL;
int r;
assert(bus);
assert(ret);
d = new(BusWaitForUnits, 1);
if (!d)
return -ENOMEM;
*d = (BusWaitForUnits) {
.state = BUS_WAIT_SUCCESS,
.bus = sd_bus_ref(bus),
};
r = sd_bus_match_signal_async(
bus,
&d->slot_disconnected,
"org.freedesktop.DBus.Local",
NULL,
"org.freedesktop.DBus.Local",
"Disconnected",
match_disconnected, NULL, d);
if (r < 0)
return r;
*ret = TAKE_PTR(d);
return 0;
}
BusWaitForUnits* bus_wait_for_units_free(BusWaitForUnits *d) {
if (!d)
return NULL;
bus_wait_for_units_clear(d);
sd_bus_slot_unref(d->slot_disconnected);
sd_bus_unref(d->bus);
return mfree(d);
}
static bool bus_wait_for_units_is_ready(BusWaitForUnits *d) {
assert(d);
if (!d->bus) /* Disconnected? */
return true;
return hashmap_isempty(d->items);
}
void bus_wait_for_units_set_ready_callback(BusWaitForUnits *d, bus_wait_for_units_ready_callback callback, void *userdata) {
assert(d);
d->ready_callback = callback;
d->userdata = userdata;
}
static void bus_wait_for_units_check_ready(BusWaitForUnits *d) {
assert(d);
if (!bus_wait_for_units_is_ready(d))
return;
d->state = d->has_failed ? BUS_WAIT_FAILURE : BUS_WAIT_SUCCESS;
if (d->ready_callback)
d->ready_callback(d, d->state, d->userdata);
}
static void wait_for_item_check_ready(WaitForItem *item) {
BusWaitForUnits *d;
assert(item);
assert_se(d = item->parent);
if (FLAGS_SET(item->flags, BUS_WAIT_FOR_MAINTENANCE_END)) {
if (item->clean_result && !streq(item->clean_result, "success"))
d->has_failed = true;
if (!item->active_state || streq(item->active_state, "maintenance"))
return;
}
if (FLAGS_SET(item->flags, BUS_WAIT_NO_JOB) && item->job_id != 0)
return;
if (FLAGS_SET(item->flags, BUS_WAIT_FOR_INACTIVE)) {
if (streq_ptr(item->active_state, "failed"))
d->has_failed = true;
else if (!streq_ptr(item->active_state, "inactive"))
return;
}
call_unit_callback_and_wait(d, item, true);
bus_wait_for_units_check_ready(d);
}
static int property_map_job(
sd_bus *bus,
const char *member,
sd_bus_message *m,
sd_bus_error *error,
void *userdata) {
WaitForItem *item = ASSERT_PTR(userdata);
const char *path;
uint32_t id;
int r;
r = sd_bus_message_read(m, "(uo)", &id, &path);
if (r < 0)
return r;
item->job_id = id;
return 0;
}
static int wait_for_item_parse_properties(WaitForItem *item, sd_bus_message *m) {
static const struct bus_properties_map map[] = {
{ "ActiveState", "s", NULL, offsetof(WaitForItem, active_state) },
{ "Job", "(uo)", property_map_job, 0 },
{ "CleanResult", "s", NULL, offsetof(WaitForItem, clean_result) },
{}
};
int r;
assert(item);
assert(m);
r = bus_message_map_all_properties(m, map, BUS_MAP_STRDUP, NULL, item);
if (r < 0)
return r;
wait_for_item_check_ready(item);
return 0;
}
static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
WaitForItem *item = ASSERT_PTR(userdata);
const char *interface;
int r;
r = sd_bus_message_read(m, "s", &interface);
if (r < 0) {
log_debug_errno(r, "Failed to parse PropertiesChanged signal: %m");
return 0;
}
if (!streq(interface, "org.freedesktop.systemd1.Unit"))
return 0;
r = wait_for_item_parse_properties(item, m);
if (r < 0)
log_debug_errno(r, "Failed to process PropertiesChanged signal: %m");
return 0;
}
static int on_get_all_properties(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
WaitForItem *item = ASSERT_PTR(userdata);
const sd_bus_error *e;
int r;
e = sd_bus_message_get_error(m);
if (e) {
BusWaitForUnits *d = item->parent;
d->has_failed = true;
r = sd_bus_error_get_errno(e);
log_debug_errno(r, "GetAll() failed for %s: %s",
item->bus_path, bus_error_message(e, r));
call_unit_callback_and_wait(d, item, false);
bus_wait_for_units_check_ready(d);
return 0;
}
r = wait_for_item_parse_properties(item, m);
if (r < 0)
log_debug_errno(r, "Failed to process GetAll method reply: %m");
return 0;
}
int bus_wait_for_units_add_unit(
BusWaitForUnits *d,
const char *unit,
BusWaitForUnitsFlags flags,
bus_wait_for_units_unit_callback callback,
void *userdata) {
_cleanup_(wait_for_item_freep) WaitForItem *item = NULL;
int r;
assert(d);
assert(unit);
assert(flags != 0);
r = hashmap_ensure_allocated(&d->items, &string_hash_ops);
if (r < 0)
return r;
item = new(WaitForItem, 1);
if (!item)
return -ENOMEM;
*item = (WaitForItem) {
.flags = flags,
.bus_path = unit_dbus_path_from_name(unit),
.unit_callback = callback,
.userdata = userdata,
.job_id = UINT32_MAX,
};
if (!item->bus_path)
return -ENOMEM;
if (!FLAGS_SET(item->flags, BUS_WAIT_REFFED)) {
r = sd_bus_call_method_async(
d->bus,
NULL,
"org.freedesktop.systemd1",
item->bus_path,
"org.freedesktop.systemd1.Unit",
"Ref",
NULL,
NULL,
NULL);
if (r < 0)
return log_debug_errno(r, "Failed to add reference to unit %s: %m", unit);
item->flags |= BUS_WAIT_REFFED;
}
r = sd_bus_match_signal_async(
d->bus,
&item->slot_properties_changed,
"org.freedesktop.systemd1",
item->bus_path,
"org.freedesktop.DBus.Properties",
"PropertiesChanged",
on_properties_changed,
NULL,
item);
if (r < 0)
return log_debug_errno(r, "Failed to request match for PropertiesChanged signal: %m");
r = sd_bus_call_method_async(
d->bus,
&item->slot_get_all,
"org.freedesktop.systemd1",
item->bus_path,
"org.freedesktop.DBus.Properties",
"GetAll",
on_get_all_properties,
item,
"s", FLAGS_SET(item->flags, BUS_WAIT_FOR_MAINTENANCE_END) ? NULL : "org.freedesktop.systemd1.Unit");
if (r < 0)
return log_debug_errno(r, "Failed to request properties of unit %s: %m", unit);
r = hashmap_put(d->items, item->bus_path, item);
if (r < 0)
return r;
d->state = BUS_WAIT_RUNNING;
item->parent = d;
TAKE_PTR(item);
return 0;
}
int bus_wait_for_units_run(BusWaitForUnits *d) {
int r;
assert(d);
while (d->state == BUS_WAIT_RUNNING) {
r = sd_bus_process(d->bus, NULL);
if (r < 0)
return r;
if (r > 0)
continue;
r = sd_bus_wait(d->bus, UINT64_MAX);
if (r < 0)
return r;
}
return d->state;
}
BusWaitForUnitsState bus_wait_for_units_state(BusWaitForUnits *d) {
assert(d);
return d->state;
}
| 12,617 | 28.550351 | 124 |
c
|
null |
systemd-main/src/shared/calendarspec.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/* A structure for specifying (possibly repetitive) points in calendar
* time, a la cron */
#include <stdbool.h>
#include "time-util.h"
typedef struct CalendarComponent {
int start;
int stop;
int repeat;
struct CalendarComponent *next;
} CalendarComponent;
typedef struct CalendarSpec {
int weekdays_bits;
bool end_of_month:1;
bool utc:1;
signed int dst:2;
char *timezone;
CalendarComponent *year;
CalendarComponent *month;
CalendarComponent *day;
CalendarComponent *hour;
CalendarComponent *minute;
CalendarComponent *microsecond;
} CalendarSpec;
CalendarSpec* calendar_spec_free(CalendarSpec *c);
bool calendar_spec_valid(CalendarSpec *spec);
int calendar_spec_to_string(const CalendarSpec *spec, char **ret);
int calendar_spec_from_string(const char *p, CalendarSpec **ret);
int calendar_spec_next_usec(const CalendarSpec *spec, usec_t usec, usec_t *next);
DEFINE_TRIVIAL_CLEANUP_FUNC(CalendarSpec*, calendar_spec_free);
| 1,120 | 23.911111 | 81 |
h
|
null |
systemd-main/src/shared/clean-ipc.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <mqueue.h>
#include <stdbool.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <unistd.h>
#include "clean-ipc.h"
#include "dirent-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "log.h"
#include "macro.h"
#include "string-util.h"
#include "strv.h"
#include "user-util.h"
static bool match_uid_gid(uid_t subject_uid, gid_t subject_gid, uid_t delete_uid, gid_t delete_gid) {
if (uid_is_valid(delete_uid) && subject_uid == delete_uid)
return true;
if (gid_is_valid(delete_gid) && subject_gid == delete_gid)
return true;
return false;
}
static int clean_sysvipc_shm(uid_t delete_uid, gid_t delete_gid, bool rm) {
_cleanup_fclose_ FILE *f = NULL;
bool first = true;
int ret = 0, r;
f = fopen("/proc/sysvipc/shm", "re");
if (!f) {
if (errno == ENOENT)
return 0;
return log_warning_errno(errno, "Failed to open /proc/sysvipc/shm: %m");
}
for (;;) {
_cleanup_free_ char *line = NULL;
unsigned n_attached;
pid_t cpid, lpid;
uid_t uid, cuid;
gid_t gid, cgid;
int shmid;
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0)
return log_warning_errno(errno, "Failed to read /proc/sysvipc/shm: %m");
if (r == 0)
break;
if (first) {
first = false;
continue;
}
if (sscanf(line, "%*i %i %*o %*u " PID_FMT " " PID_FMT " %u " UID_FMT " " GID_FMT " " UID_FMT " " GID_FMT,
&shmid, &cpid, &lpid, &n_attached, &uid, &gid, &cuid, &cgid) != 8)
continue;
if (n_attached > 0)
continue;
if (!match_uid_gid(uid, gid, delete_uid, delete_gid))
continue;
if (!rm)
return 1;
if (shmctl(shmid, IPC_RMID, NULL) < 0) {
/* Ignore entries that are already deleted */
if (IN_SET(errno, EIDRM, EINVAL))
continue;
ret = log_warning_errno(errno,
"Failed to remove SysV shared memory segment %i: %m",
shmid);
} else {
log_debug("Removed SysV shared memory segment %i.", shmid);
if (ret == 0)
ret = 1;
}
}
return ret;
}
static int clean_sysvipc_sem(uid_t delete_uid, gid_t delete_gid, bool rm) {
_cleanup_fclose_ FILE *f = NULL;
bool first = true;
int ret = 0, r;
f = fopen("/proc/sysvipc/sem", "re");
if (!f) {
if (errno == ENOENT)
return 0;
return log_warning_errno(errno, "Failed to open /proc/sysvipc/sem: %m");
}
for (;;) {
_cleanup_free_ char *line = NULL;
uid_t uid, cuid;
gid_t gid, cgid;
int semid;
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0)
return log_warning_errno(r, "Failed to read /proc/sysvipc/sem: %m");
if (r == 0)
break;
if (first) {
first = false;
continue;
}
if (sscanf(line, "%*i %i %*o %*u " UID_FMT " " GID_FMT " " UID_FMT " " GID_FMT,
&semid, &uid, &gid, &cuid, &cgid) != 5)
continue;
if (!match_uid_gid(uid, gid, delete_uid, delete_gid))
continue;
if (!rm)
return 1;
if (semctl(semid, 0, IPC_RMID) < 0) {
/* Ignore entries that are already deleted */
if (IN_SET(errno, EIDRM, EINVAL))
continue;
ret = log_warning_errno(errno,
"Failed to remove SysV semaphores object %i: %m",
semid);
} else {
log_debug("Removed SysV semaphore %i.", semid);
if (ret == 0)
ret = 1;
}
}
return ret;
}
static int clean_sysvipc_msg(uid_t delete_uid, gid_t delete_gid, bool rm) {
_cleanup_fclose_ FILE *f = NULL;
bool first = true;
int ret = 0, r;
f = fopen("/proc/sysvipc/msg", "re");
if (!f) {
if (errno == ENOENT)
return 0;
return log_warning_errno(errno, "Failed to open /proc/sysvipc/msg: %m");
}
for (;;) {
_cleanup_free_ char *line = NULL;
uid_t uid, cuid;
gid_t gid, cgid;
pid_t cpid, lpid;
int msgid;
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0)
return log_warning_errno(r, "Failed to read /proc/sysvipc/msg: %m");
if (r == 0)
break;
if (first) {
first = false;
continue;
}
if (sscanf(line, "%*i %i %*o %*u %*u " PID_FMT " " PID_FMT " " UID_FMT " " GID_FMT " " UID_FMT " " GID_FMT,
&msgid, &cpid, &lpid, &uid, &gid, &cuid, &cgid) != 7)
continue;
if (!match_uid_gid(uid, gid, delete_uid, delete_gid))
continue;
if (!rm)
return 1;
if (msgctl(msgid, IPC_RMID, NULL) < 0) {
/* Ignore entries that are already deleted */
if (IN_SET(errno, EIDRM, EINVAL))
continue;
ret = log_warning_errno(errno,
"Failed to remove SysV message queue %i: %m",
msgid);
} else {
log_debug("Removed SysV message queue %i.", msgid);
if (ret == 0)
ret = 1;
}
}
return ret;
}
static int clean_posix_shm_internal(const char *dirname, DIR *dir, uid_t uid, gid_t gid, bool rm) {
int ret = 0, r;
assert(dir);
FOREACH_DIRENT_ALL(de, dir, goto fail) {
struct stat st;
if (dot_or_dot_dot(de->d_name))
continue;
if (fstatat(dirfd(dir), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
if (errno == ENOENT)
continue;
ret = log_warning_errno(errno, "Failed to stat() POSIX shared memory segment %s/%s: %m",
dirname, de->d_name);
continue;
}
if (S_ISDIR(st.st_mode)) {
_cleanup_closedir_ DIR *kid = NULL;
kid = xopendirat(dirfd(dir), de->d_name, O_NOFOLLOW|O_NOATIME);
if (!kid) {
if (errno != ENOENT)
ret = log_warning_errno(errno, "Failed to enter shared memory directory %s/%s: %m",
dirname, de->d_name);
} else {
r = clean_posix_shm_internal(de->d_name, kid, uid, gid, rm);
if (r < 0)
ret = r;
}
if (!match_uid_gid(st.st_uid, st.st_gid, uid, gid))
continue;
if (!rm)
return 1;
if (unlinkat(dirfd(dir), de->d_name, AT_REMOVEDIR) < 0) {
if (errno == ENOENT)
continue;
ret = log_warning_errno(errno, "Failed to remove POSIX shared memory directory %s/%s: %m",
dirname, de->d_name);
} else {
log_debug("Removed POSIX shared memory directory %s", de->d_name);
if (ret == 0)
ret = 1;
}
} else {
if (!match_uid_gid(st.st_uid, st.st_gid, uid, gid))
continue;
if (!rm)
return 1;
if (unlinkat(dirfd(dir), de->d_name, 0) < 0) {
if (errno == ENOENT)
continue;
ret = log_warning_errno(errno, "Failed to remove POSIX shared memory segment %s: %m", de->d_name);
} else {
log_debug("Removed POSIX shared memory segment %s", de->d_name);
if (ret == 0)
ret = 1;
}
}
}
return ret;
fail:
return log_warning_errno(errno, "Failed to read /dev/shm: %m");
}
static int clean_posix_shm(uid_t uid, gid_t gid, bool rm) {
_cleanup_closedir_ DIR *dir = NULL;
dir = opendir("/dev/shm");
if (!dir) {
if (errno == ENOENT)
return 0;
return log_warning_errno(errno, "Failed to open /dev/shm: %m");
}
return clean_posix_shm_internal("/dev/shm", dir, uid, gid, rm);
}
static int clean_posix_mq(uid_t uid, gid_t gid, bool rm) {
_cleanup_closedir_ DIR *dir = NULL;
int ret = 0;
dir = opendir("/dev/mqueue");
if (!dir) {
if (errno == ENOENT)
return 0;
return log_warning_errno(errno, "Failed to open /dev/mqueue: %m");
}
FOREACH_DIRENT_ALL(de, dir, goto fail) {
struct stat st;
char fn[1+strlen(de->d_name)+1];
if (dot_or_dot_dot(de->d_name))
continue;
if (fstatat(dirfd(dir), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
if (errno == ENOENT)
continue;
ret = log_warning_errno(errno,
"Failed to stat() MQ segment %s: %m",
de->d_name);
continue;
}
if (!match_uid_gid(st.st_uid, st.st_gid, uid, gid))
continue;
if (!rm)
return 1;
fn[0] = '/';
strcpy(fn+1, de->d_name);
if (mq_unlink(fn) < 0) {
if (errno == ENOENT)
continue;
ret = log_warning_errno(errno,
"Failed to unlink POSIX message queue %s: %m",
fn);
} else {
log_debug("Removed POSIX message queue %s", fn);
if (ret == 0)
ret = 1;
}
}
return ret;
fail:
return log_warning_errno(errno, "Failed to read /dev/mqueue: %m");
}
int clean_ipc_internal(uid_t uid, gid_t gid, bool rm) {
int ret = 0, r;
/* If 'rm' is true, clean all IPC objects owned by either the specified UID or the specified GID. Return the
* last error encountered or == 0 if no matching IPC objects have been found or > 0 if matching IPC objects
* have been found and have been removed.
*
* If 'rm' is false, just search for IPC objects owned by either the specified UID or the specified GID. In
* this case we return < 0 on error, > 0 if we found a matching object, == 0 if we didn't.
*
* As special rule: if UID/GID is specified as root we'll silently not clean up things, and always claim that
* there are IPC objects for it. */
if (uid == 0) {
if (!rm)
return 1;
uid = UID_INVALID;
}
if (gid == 0) {
if (!rm)
return 1;
gid = GID_INVALID;
}
/* Anything to do? */
if (!uid_is_valid(uid) && !gid_is_valid(gid))
return 0;
r = clean_sysvipc_shm(uid, gid, rm);
if (r != 0) {
if (!rm)
return r;
if (ret == 0)
ret = r;
}
r = clean_sysvipc_sem(uid, gid, rm);
if (r != 0) {
if (!rm)
return r;
if (ret == 0)
ret = r;
}
r = clean_sysvipc_msg(uid, gid, rm);
if (r != 0) {
if (!rm)
return r;
if (ret == 0)
ret = r;
}
r = clean_posix_shm(uid, gid, rm);
if (r != 0) {
if (!rm)
return r;
if (ret == 0)
ret = r;
}
r = clean_posix_mq(uid, gid, rm);
if (r != 0) {
if (!rm)
return r;
if (ret == 0)
ret = r;
}
return ret;
}
int clean_ipc_by_uid(uid_t uid) {
return clean_ipc_internal(uid, GID_INVALID, true);
}
int clean_ipc_by_gid(gid_t gid) {
return clean_ipc_internal(UID_INVALID, gid, true);
}
| 14,798 | 31.668874 | 130 |
c
|
null |
systemd-main/src/shared/clean-ipc.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
#include "user-util.h"
int clean_ipc_internal(uid_t uid, gid_t gid, bool rm);
/* Remove all IPC objects owned by the specified UID or GID */
int clean_ipc_by_uid(uid_t uid);
int clean_ipc_by_gid(gid_t gid);
/* Check if any IPC object owned by the specified UID or GID exists, returns > 0 if so, == 0 if not */
static inline int search_ipc(uid_t uid, gid_t gid) {
return clean_ipc_internal(uid, gid, false);
}
| 507 | 27.222222 | 102 |
h
|
null |
systemd-main/src/shared/clock-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdbool.h>
#include <time.h>
#include <linux/rtc.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include "alloc-util.h"
#include "clock-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "macro.h"
#include "string-util.h"
int clock_get_hwclock(struct tm *tm) {
_cleanup_close_ int fd = -EBADF;
assert(tm);
fd = open("/dev/rtc", O_RDONLY|O_CLOEXEC);
if (fd < 0)
return -errno;
/* This leaves the timezone fields of struct tm
* uninitialized! */
if (ioctl(fd, RTC_RD_TIME, tm) < 0)
return -errno;
/* We don't know daylight saving, so we reset this in order not
* to confuse mktime(). */
tm->tm_isdst = -1;
return 0;
}
int clock_set_hwclock(const struct tm *tm) {
_cleanup_close_ int fd = -EBADF;
assert(tm);
fd = open("/dev/rtc", O_RDONLY|O_CLOEXEC);
if (fd < 0)
return -errno;
return RET_NERRNO(ioctl(fd, RTC_SET_TIME, tm));
}
int clock_is_localtime(const char* adjtime_path) {
_cleanup_fclose_ FILE *f = NULL;
int r;
if (!adjtime_path)
adjtime_path = "/etc/adjtime";
/*
* The third line of adjtime is "UTC" or "LOCAL" or nothing.
* # /etc/adjtime
* 0.0 0 0
* 0
* UTC
*/
f = fopen(adjtime_path, "re");
if (f) {
_cleanup_free_ char *line = NULL;
unsigned i;
for (i = 0; i < 2; i++) { /* skip the first two lines */
r = read_line(f, LONG_LINE_MAX, NULL);
if (r < 0)
return r;
if (r == 0)
return false; /* less than three lines → default to UTC */
}
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0)
return r;
if (r == 0)
return false; /* less than three lines → default to UTC */
return streq(line, "LOCAL");
} else if (errno != ENOENT)
return -errno;
/* adjtime not present → default to UTC */
return false;
}
int clock_set_timezone(int *ret_minutesdelta) {
struct timespec ts;
struct tm tm;
int minutesdelta;
struct timezone tz;
assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
assert_se(localtime_r(&ts.tv_sec, &tm));
minutesdelta = tm.tm_gmtoff / 60;
tz = (struct timezone) {
.tz_minuteswest = -minutesdelta,
.tz_dsttime = 0, /* DST_NONE */
};
/* If the RTC does not run in UTC but in local time, the very first call to settimeofday() will set
* the kernel's timezone and will warp the system clock, so that it runs in UTC instead of the local
* time we have read from the RTC. */
if (settimeofday(NULL, &tz) < 0)
return -errno;
if (ret_minutesdelta)
*ret_minutesdelta = minutesdelta;
return 0;
}
int clock_reset_timewarp(void) {
static const struct timezone tz = {
.tz_minuteswest = 0,
.tz_dsttime = 0, /* DST_NONE */
};
/* The very first call to settimeofday() does time warp magic. Do a dummy call here, so the time
* warping is sealed and all later calls behave as expected. */
return RET_NERRNO(settimeofday(NULL, &tz));
}
#define EPOCH_FILE "/usr/lib/clock-epoch"
int clock_apply_epoch(ClockChangeDirection *ret_attempted_change) {
usec_t epoch_usec, now_usec;
struct stat st;
/* NB: we update *ret_attempted_change in *all* cases, both
* on success and failure, to indicate what we intended to do! */
assert(ret_attempted_change);
if (stat(EPOCH_FILE, &st) < 0) {
if (errno != ENOENT)
log_warning_errno(errno, "Cannot stat " EPOCH_FILE ": %m");
epoch_usec = (usec_t) TIME_EPOCH * USEC_PER_SEC;
} else
epoch_usec = timespec_load(&st.st_mtim);
now_usec = now(CLOCK_REALTIME);
if (now_usec < epoch_usec)
*ret_attempted_change = CLOCK_CHANGE_FORWARD;
else if (CLOCK_VALID_RANGE_USEC_MAX > 0 && now_usec > usec_add(epoch_usec, CLOCK_VALID_RANGE_USEC_MAX))
*ret_attempted_change = CLOCK_CHANGE_BACKWARD;
else {
*ret_attempted_change = CLOCK_CHANGE_NOOP;
return 0;
}
if (clock_settime(CLOCK_REALTIME, TIMESPEC_STORE(epoch_usec)) < 0)
return -errno;
return 1;
}
| 4,951 | 28.47619 | 111 |
c
|
null |
systemd-main/src/shared/clock-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <time.h>
typedef enum ClockChangeDirection {
CLOCK_CHANGE_NOOP,
CLOCK_CHANGE_FORWARD,
CLOCK_CHANGE_BACKWARD,
_CLOCK_CHANGE_MAX,
_CLOCK_CHANGE_INVALID = -EINVAL,
} ClockChangeDirection;
int clock_is_localtime(const char* adjtime_path);
int clock_set_timezone(int *ret_minutesdelta);
int clock_reset_timewarp(void);
int clock_get_hwclock(struct tm *tm);
int clock_set_hwclock(const struct tm *tm);
int clock_apply_epoch(ClockChangeDirection *ret_attempted_change);
| 596 | 27.428571 | 66 |
h
|
null |
systemd-main/src/shared/common-signal.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "common-signal.h"
#include "fd-util.h"
#include "fileio.h"
#include "memstream-util.h"
#include "process-util.h"
#include "signal-util.h"
int sigrtmin18_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
struct sigrtmin18_info *info = userdata;
_cleanup_free_ char *comm = NULL;
assert(s);
assert(si);
(void) get_process_comm(si->ssi_pid, &comm);
if (si->ssi_code != SI_QUEUE) {
log_notice("Received control signal %s from process " PID_FMT " (%s) without command value, ignoring.",
signal_to_string(si->ssi_signo),
(pid_t) si->ssi_pid,
strna(comm));
return 0;
}
log_debug("Received control signal %s from process " PID_FMT " (%s) with command 0x%08x.",
signal_to_string(si->ssi_signo),
(pid_t) si->ssi_pid,
strna(comm),
(unsigned) si->ssi_int);
switch (si->ssi_int) {
case _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE..._COMMON_SIGNAL_COMMAND_LOG_LEVEL_END:
log_set_max_level(si->ssi_int - _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE);
break;
case COMMON_SIGNAL_COMMAND_CONSOLE:
log_set_target_and_open(LOG_TARGET_CONSOLE);
break;
case COMMON_SIGNAL_COMMAND_JOURNAL:
log_set_target_and_open(LOG_TARGET_JOURNAL);
break;
case COMMON_SIGNAL_COMMAND_KMSG:
log_set_target_and_open(LOG_TARGET_KMSG);
break;
case COMMON_SIGNAL_COMMAND_NULL:
log_set_target_and_open(LOG_TARGET_NULL);
break;
case COMMON_SIGNAL_COMMAND_MEMORY_PRESSURE:
if (info && info->memory_pressure_handler)
return info->memory_pressure_handler(s, info->memory_pressure_userdata);
sd_event_trim_memory();
break;
case COMMON_SIGNAL_COMMAND_MALLOC_INFO: {
_cleanup_(memstream_done) MemStream m = {};
FILE *f;
f = memstream_init(&m);
if (!f) {
log_oom();
break;
}
if (malloc_info(0, f) < 0) {
log_error_errno(errno, "Failed to invoke malloc_info(): %m");
break;
}
(void) memstream_dump(LOG_INFO, &m);
break;
}
default:
log_notice("Received control signal %s with unknown command 0x%08x, ignoring.",
signal_to_string(si->ssi_signo), (unsigned) si->ssi_int);
break;
}
return 0;
}
| 2,906 | 32.802326 | 119 |
c
|
null |
systemd-main/src/shared/common-signal.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <syslog.h>
#include <sd-event.h>
/* All our long-running services should implement a SIGRTMIN+18 handler that can be used to trigger certain
* actions that affect service runtime. The specific action is indicated via the "value integer" you can pass
* along realtime signals. This is mostly intended for debugging purposes and is entirely asynchronous in
* nature. Specifically, these are the commands:
*
* Currently available operations:
*
* • Change maximum log level
* • Change log target
* • Invoke memory trimming, like under memory pressure
* • Write glibc malloc() allocation info to logs
*
* How to use this? Via a command like the following:
*
* /usr/bin/kill -s RTMIN+18 -q 768 1
*
* (This will tell PID 1 to trim its memory use.)
*
* or:
*
* systemctl kill --kill-value=0x300 -s RTMIN+18 systemd-journald
*
* (This will tell journald to trim its memory use.)
*/
enum {
_COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE = 0x100,
COMMON_SIGNAL_COMMAND_LOG_EMERG = _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE + LOG_EMERG,
COMMON_SIGNAL_COMMAND_LOG_ALERT = _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE + LOG_ALERT,
COMMON_SIGNAL_COMMAND_LOG_CRIT = _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE + LOG_CRIT,
COMMON_SIGNAL_COMMAND_LOG_ERR = _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE + LOG_ERR,
COMMON_SIGNAL_COMMAND_LOG_WARNING = _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE + LOG_WARNING,
COMMON_SIGNAL_COMMAND_LOG_NOTICE = _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE + LOG_NOTICE,
COMMON_SIGNAL_COMMAND_LOG_INFO = _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE + LOG_INFO,
COMMON_SIGNAL_COMMAND_LOG_DEBUG = _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE + LOG_DEBUG,
_COMMON_SIGNAL_COMMAND_LOG_LEVEL_END = COMMON_SIGNAL_COMMAND_LOG_DEBUG,
COMMON_SIGNAL_COMMAND_CONSOLE = 0x200,
COMMON_SIGNAL_COMMAND_JOURNAL,
COMMON_SIGNAL_COMMAND_KMSG,
COMMON_SIGNAL_COMMAND_NULL,
COMMON_SIGNAL_COMMAND_MEMORY_PRESSURE = 0x300,
COMMON_SIGNAL_COMMAND_MALLOC_INFO,
};
struct sigrtmin18_info {
sd_event_handler_t memory_pressure_handler;
void *memory_pressure_userdata;
};
int sigrtmin18_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata);
| 2,442 | 40.40678 | 109 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.