1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
| | // SPDX-License-Identifier: GPL-2.0-or-later
// SPDX-FileCopyrightText: 2020-2021 Alyssa Ross <hi@alyssa.is>
#define _GNU_SOURCE
#include "vsock.h"
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/vm_sockets.h>
static void fill_sockaddr(struct sockaddr_vm *addr, uint32_t cid, uint32_t port)
{
addr->svm_family = AF_VSOCK;
addr->svm_cid = cid;
addr->svm_port = port;
}
int vsock_bind(int fd, uint32_t cid, uint32_t port)
{
struct sockaddr_vm addr = { 0 };
fill_sockaddr(&addr, cid, port);
if (bind(fd, (struct sockaddr *)&addr, sizeof addr) == -1)
return -1;
return 0;
}
int vsock_accept(int sockfd, uint32_t *cid, uint32_t *port)
{
struct sockaddr_vm addr = { 0 };
socklen_t addr_size = sizeof addr;
int fd;
if ((fd = accept(sockfd, (struct sockaddr *)&addr, &addr_size)) == -1)
return -1;
*cid = addr.svm_cid;
*port = addr.svm_port;
return fd;
}
int vsock_connect(int fd, uint32_t cid, uint32_t port)
{
struct sockaddr_vm addr = { 0 };
fill_sockaddr(&addr, cid, port);
return connect(fd, (struct sockaddr *)&addr, sizeof addr);
}
int vsock_open(uint32_t cid, uint32_t port)
{
int fd = socket(AF_VSOCK, SOCK_STREAM, 0);
if (fd == -1)
return -1;
if (vsock_connect(fd, cid, port) == -1)
return -1;
return fd;
}
int vsock_get_cid_and_port(int fd, uint32_t *cid, uint32_t *port)
{
struct sockaddr_vm addr;
socklen_t addrlen = sizeof addr;
if (getsockname(fd, (struct sockaddr *)&addr, &addrlen) == -1)
return -1;
if (cid)
*cid = addr.svm_cid;
if (port)
*port = addr.svm_port;
return 0;
}
|