summary refs log blame commit diff
path: root/vsock.c
blob: 99945c376afa9653f0397d15bc425633b4a31fda (plain) (tree)
1
2
                                            
                                                               































                                                                                
               
 
                                                                              




                              
                  














                                                                  



                                               

 
                                                                 






                                                                      



                                      


                 
// 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;
}