src/shared/: split AF_UNIX/AF_VSOCK address parsing into src/basic/

We'll use it from libsystemd0 later, but AF_INET/6 requires some
netlink calls and thus the additional library dependency
This commit is contained in:
Luca Boccassi
2023-01-05 18:43:47 +01:00
parent ea575e176a
commit 747b5d963e
3 changed files with 131 additions and 103 deletions
+68
View File
@@ -1472,3 +1472,71 @@ int connect_unix_path(int fd, int dir_fd, const char *path) {
return RET_NERRNO(connect(fd, &sa.sa, salen));
}
int socket_address_parse_unix(SocketAddress *ret_address, const char *s) {
struct sockaddr_un un;
int r;
assert(ret_address);
assert(s);
if (!IN_SET(*s, '/', '@'))
return -EPROTO;
r = sockaddr_un_set_path(&un, s);
if (r < 0)
return r;
*ret_address = (SocketAddress) {
.sockaddr.un = un,
.size = r,
};
return 0;
}
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s) {
/* AF_VSOCK socket in vsock:cid:port notation */
_cleanup_free_ char *n = NULL;
char *e, *cid_start;
unsigned port, cid;
int r;
assert(ret_address);
assert(s);
cid_start = startswith(s, "vsock:");
if (!cid_start)
return -EPROTO;
e = strchr(cid_start, ':');
if (!e)
return -EINVAL;
r = safe_atou(e+1, &port);
if (r < 0)
return r;
n = strndup(cid_start, e - cid_start);
if (!n)
return -ENOMEM;
if (isempty(n))
cid = VMADDR_CID_ANY;
else {
r = safe_atou(n, &cid);
if (r < 0)
return r;
}
*ret_address = (SocketAddress) {
.sockaddr.vm = {
.svm_cid = cid,
.svm_family = AF_VSOCK,
.svm_port = port,
},
.size = sizeof(struct sockaddr_vm),
};
return 0;
}
+6
View File
@@ -336,3 +336,9 @@ int socket_get_mtu(int fd, int af, size_t *ret);
#define UCRED_INVALID { .pid = 0, .uid = UID_INVALID, .gid = GID_INVALID }
int connect_unix_path(int fd, int dir_fd, const char *path);
/* Parses AF_UNIX and AF_VSOCK addresses. AF_INET[6] require some netlink calls, so it cannot be in
* src/basic/ and is done from 'socket_local_address from src/shared/. Return -EPROTO in case of
* protocol mismatch. */
int socket_address_parse_unix(SocketAddress *ret_address, const char *s);
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s);