This commit is contained in:
AlexandreRouma
2023-01-26 02:54:29 +01:00
parent ab5d7a73c1
commit 66bbc93535
10 changed files with 26 additions and 1954 deletions

View File

@ -1,5 +1,5 @@
#pragma once
#include "net.h"
#include <utils/net.h>
#include <dsp/stream.h>
#include <dsp/types.h>
#include <memory>

View File

@ -1,403 +0,0 @@
#include "net.h"
#include <string.h>
#include <codecvt>
#ifdef _WIN32
#define WOULD_BLOCK (WSAGetLastError() == WSAEWOULDBLOCK)
#else
#define WOULD_BLOCK (errno == EWOULDBLOCK)
#endif
namespace net {
bool _init = false;
// === Private functions ===
void init() {
if (_init) { return; }
#ifdef _WIN32
// Initialize WinSock2
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa)) {
throw std::runtime_error("Could not initialize WinSock2");
return;
}
#else
// Disable SIGPIPE to avoid closing when the remote host disconnects
signal(SIGPIPE, SIG_IGN);
#endif
_init = true;
}
bool queryHost(uint32_t* addr, std::string host) {
hostent* ent = gethostbyname(host.c_str());
if (!ent || !ent->h_addr_list[0]) { return false; }
*addr = *(uint32_t*)ent->h_addr_list[0];
return true;
}
void closeSocket(SockHandle_t sock) {
#ifdef _WIN32
shutdown(sock, SD_BOTH);
closesocket(sock);
#else
shutdown(sock, SHUT_RDWR);
close(sock);
#endif
}
void setNonblocking(SockHandle_t sock) {
#ifdef _WIN32
u_long enabled = 1;
ioctlsocket(sock, FIONBIO, &enabled);
#else
fcntl(sock, F_SETFL, O_NONBLOCK);
#endif
}
// === Address functions ===
Address::Address() {
memset(&addr, 0, sizeof(addr));
}
Address::Address(const std::string& host, int port) {
// Initialize WSA if needed
init();
// Lookup host
hostent* ent = gethostbyname(host.c_str());
if (!ent || !ent->h_addr_list[0]) {
throw std::runtime_error("Unknown host");
}
// Build address
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = *(uint32_t*)ent->h_addr_list[0];
addr.sin_port = htons(port);
}
Address::Address(IP_t ip, int port) {
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(ip);
addr.sin_port = htons(port);
}
std::string Address::getIPStr() {
char buf[128];
IP_t ip = getIP();
sprintf(buf, "%d.%d.%d.%d", (ip >> 24) & 0xFF, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF);
return buf;
}
IP_t Address::getIP() {
return htonl(addr.sin_addr.s_addr);
}
void Address::setIP(IP_t ip) {
addr.sin_addr.s_addr = htonl(ip);
}
int Address::getPort() {
return htons(addr.sin_port);
}
void Address::setPort(int port) {
addr.sin_port = htons(port);
}
// === Socket functions ===
Socket::Socket(SockHandle_t sock, const Address* raddr) {
this->sock = sock;
if (raddr) {
this->raddr = new Address(*raddr);
}
}
Socket::~Socket() {
close();
if (raddr) { delete raddr; }
}
void Socket::close() {
if (!open) { return; }
open = false;
closeSocket(sock);
}
bool Socket::isOpen() {
return open;
}
SocketType Socket::type() {
return raddr ? SOCKET_TYPE_UDP : SOCKET_TYPE_TCP;
}
int Socket::send(const uint8_t* data, size_t len, const Address* dest) {
return sendto(sock, (const char*)data, len, 0, (sockaddr*)(dest ? &dest->addr : (raddr ? &raddr->addr : NULL)), sizeof(sockaddr_in));
}
int Socket::sendstr(const std::string& str, const Address* dest) {
return send((const uint8_t*)str.c_str(), str.length(), dest);
}
int Socket::recv(uint8_t* data, size_t maxLen, bool forceLen, int timeout, Address* dest) {
// Create FD set
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
// Define timeout
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = timeout * 1000;
int read = 0;
bool blocking = (timeout != NONBLOCKING);
do {
// Wait for data or error if
if (blocking) {
int err = select(sock+1, &set, NULL, &set, (timeout > 0) ? &tv : NULL);
if (err <= 0) { return err; }
}
// Receive
int addrLen = sizeof(sockaddr_in);
int err = ::recvfrom(sock, (char*)&data[read], maxLen - read, 0,(sockaddr*)(dest ? &dest->addr : NULL), (socklen_t*)(dest ? &addrLen : NULL));
if (err <= 0 && !WOULD_BLOCK) {
close();
return err;
}
read += err;
}
while (blocking && forceLen && read < maxLen);
return read;
}
int Socket::recvline(std::string& str, int maxLen, int timeout, Address* dest) {
// Disallow nonblocking mode
if (timeout < 0) { return -1; }
str.clear();
int read = 0;
while (true) {
char c;
int err = recv((uint8_t*)&c, 1, false, timeout, dest);
if (err <= 0) { return err; }
if (c == '\n') { break; }
str += c;
read++;
if (maxLen && read >= maxLen) { break; }
}
return read;
}
// === Listener functions ===
Listener::Listener(SockHandle_t sock) {
this->sock = sock;
}
Listener::~Listener() {
stop();
}
void Listener::stop() {
closeSocket(sock);
open = false;
}
bool Listener::listening() {
return open;
}
std::shared_ptr<Socket> Listener::accept(Address* dest, int timeout) {
// Create FD set
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
// Define timeout
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = timeout * 1000;
// Wait for data or error
if (timeout != NONBLOCKING) {
int err = select(sock+1, &set, NULL, &set, (timeout > 0) ? &tv : NULL);
if (err <= 0) { return NULL; }
}
// Accept
int addrLen = sizeof(sockaddr_in);
SockHandle_t s = ::accept(sock, (sockaddr*)(dest ? &dest->addr : NULL), (socklen_t*)(dest ? &addrLen : NULL));
if ((int)s < 0) {
if (!WOULD_BLOCK) { stop(); }
return NULL;
}
// Enable nonblocking mode
setNonblocking(s);
return std::make_shared<Socket>(s);
}
// === Creation functions ===
std::map<std::string, InterfaceInfo> listInterfaces() {
// Init library if needed
init();
std::map<std::string, InterfaceInfo> ifaces;
#ifdef _WIN32
// Pre-allocate buffer
ULONG size = sizeof(IP_ADAPTER_ADDRESSES);
PIP_ADAPTER_ADDRESSES addresses = (PIP_ADAPTER_ADDRESSES)malloc(size);
// Reallocate to real size
if (GetAdaptersAddresses(AF_INET, 0, NULL, addresses, &size) == ERROR_BUFFER_OVERFLOW) {
addresses = (PIP_ADAPTER_ADDRESSES)realloc(addresses, size);
if (GetAdaptersAddresses(AF_INET, 0, NULL, addresses, &size)) {
throw std::exception("Could not list network interfaces");
}
}
// Save data
std::wstring_convert<std::codecvt_utf8<wchar_t>> utfConv;
for (auto iface = addresses; iface; iface = iface->Next) {
InterfaceInfo info;
auto ip = iface->FirstUnicastAddress;
if (!ip || ip->Address.lpSockaddr->sa_family != AF_INET) { continue; }
info.address = ntohl(*(uint32_t*)&ip->Address.lpSockaddr->sa_data[2]);
info.netmask = ~((1 << (32 - ip->OnLinkPrefixLength)) - 1);
info.broadcast = info.address | (~info.netmask);
ifaces[utfConv.to_bytes(iface->FriendlyName)] = info;
}
// Free tables
free(addresses);
#else
// Get iface list
struct ifaddrs* addresses = NULL;
getifaddrs(&addresses);
// Save data
for (auto iface = addresses; iface; iface = iface->ifa_next) {
if (iface->ifa_addr->sa_family != AF_INET) { continue; }
InterfaceInfo info;
info.address = ntohl(*(uint32_t*)&iface->ifa_addr->sa_data[2]);
info.netmask = ntohl(*(uint32_t*)&iface->ifa_netmask->sa_data[2]);
info.broadcast = info.address | (~info.netmask);
ifaces[iface->ifa_name] = info;
}
// Free iface list
freeifaddrs(addresses);
#endif
return ifaces;
}
std::shared_ptr<Listener> listen(const Address& addr) {
// Init library if needed
init();
// Create socket
SockHandle_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// TODO: Support non-blockign mode
#ifndef _WIN32
// Allow port reusing if the app was killed or crashed
// and the socket is stuck in TIME_WAIT state.
// This option has a different meaning on Windows,
// so we use it only for non-Windows systems
int enable = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {
closeSocket(s);
throw std::runtime_error("Could not configure socket");
return NULL;
}
#endif
// Bind socket to the port
if (bind(s, (sockaddr*)&addr.addr, sizeof(sockaddr_in))) {
closeSocket(s);
throw std::runtime_error("Could not bind socket");
return NULL;
}
// Enable listening
if (::listen(s, SOMAXCONN) != 0) {
throw std::runtime_error("Could start listening for connections");
return NULL;
}
// Enable nonblocking mode
setNonblocking(s);
// Return listener class
return std::make_shared<Listener>(s);
}
std::shared_ptr<Listener> listen(std::string host, int port) {
return listen(Address(host, port));
}
std::shared_ptr<Socket> connect(const Address& addr) {
// Init library if needed
init();
// Create socket
SockHandle_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// Connect to server
if (::connect(s, (sockaddr*)&addr.addr, sizeof(sockaddr_in))) {
closeSocket(s);
throw std::runtime_error("Could not connect");
return NULL;
}
// Enable nonblocking mode
setNonblocking(s);
// Return socket class
return std::make_shared<Socket>(s);
}
std::shared_ptr<Socket> connect(std::string host, int port) {
return connect(Address(host, port));
}
std::shared_ptr<Socket> openudp(const Address& raddr, const Address& laddr) {
// Init library if needed
init();
// Create socket
SockHandle_t s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// Bind socket to local port
if (bind(s, (sockaddr*)&laddr.addr, sizeof(sockaddr_in))) {
closeSocket(s);
throw std::runtime_error("Could not bind socket");
return NULL;
}
// Return socket class
return std::make_shared<Socket>(s, &raddr);
}
std::shared_ptr<Socket> openudp(std::string rhost, int rport, const Address& laddr) {
return openudp(Address(rhost, rport), laddr);
}
std::shared_ptr<Socket> openudp(const Address& raddr, std::string lhost, int lport) {
return openudp(raddr, Address(lhost, lport));
}
std::shared_ptr<Socket> openudp(std::string rhost, int rport, std::string lhost, int lport) {
return openudp(Address(rhost, rport), Address(lhost, lport));
}
}

View File

@ -1,281 +0,0 @@
#pragma once
#include <stdint.h>
#include <mutex>
#include <memory>
#include <map>
#ifdef _WIN32
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iphlpapi.h>
#else
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>
#include <poll.h>
#include <fcntl.h>
#include <ifaddrs.h>
#endif
namespace net {
#ifdef _WIN32
typedef SOCKET SockHandle_t;
typedef int socklen_t;
#else
typedef int SockHandle_t;
#endif
typedef uint32_t IP_t;
class Socket;
class Listener;
struct InterfaceInfo {
IP_t address;
IP_t netmask;
IP_t broadcast;
};
class Address {
friend Socket;
friend Listener;
public:
/**
* Default constructor. Corresponds to 0.0.0.0:0.
*/
Address();
/**
* Do not instantiate this class manually. Use the provided functions.
* @param host Hostname or IP.
* @param port TCP/UDP port.
*/
Address(const std::string& host, int port);
/**
* Do not instantiate this class manually. Use the provided functions.
* @param ip IP in host byte order.
* @param port TCP/UDP port.
*/
Address(IP_t ip, int port);
/**
* Get the IP address.
* @return IP address in standard string format.
*/
std::string getIPStr();
/**
* Get the IP address.
* @return IP address in host byte order.
*/
IP_t getIP();
/**
* Set the IP address.
* @param ip IP address in host byte order.
*/
void setIP(IP_t ip);
/**
* Get the TCP/UDP port.
* @return TCP/UDP port number.
*/
int getPort();
/**
* Set the TCP/UDP port.
* @param port TCP/UDP port number.
*/
void setPort(int port);
struct sockaddr_in addr;
};
enum {
NO_TIMEOUT = -1,
NONBLOCKING = 0
};
enum SocketType {
SOCKET_TYPE_TCP,
SOCKET_TYPE_UDP
};
class Socket {
public:
/**
* Do not instantiate this class manually. Use the provided functions.
*/
Socket(SockHandle_t sock, const Address* raddr = NULL);
~Socket();
/**
* Close socket. The socket can no longer be used after this.
*/
void close();
/**
* Check if the socket is open.
* @return True if open, false if closed.
*/
bool isOpen();
/**
* Get socket type. Either TCP or UDP.
* @return Socket type.
*/
SocketType type();
/**
* Send data on socket.
* @param data Data to be sent.
* @param len Number of bytes to be sent.
* @param dest Destination address. NULL to use the default remote address.
* @return Number of bytes sent.
*/
int send(const uint8_t* data, size_t len, const Address* dest = NULL);
/**
* Send string on socket. Terminating NULL byte is not sent, include one in the string if you need it.
* @param str String to be sent.
* @param dest Destination address. NULL to use the default remote address.
* @return Number of bytes sent.
*/
int sendstr(const std::string& str, const Address* dest = NULL);
/**
* Receive data from socket.
* @param data Buffer to read the data into.
* @param maxLen Maximum number of bytes to read.
* @param forceLen Read the maximum number of bytes even if it requires multiple receive operations.
* @param timeout Timeout in milliseconds. Use NO_TIMEOUT or NONBLOCKING here if needed.
* @param dest Destination address. If multiple packets, this will contain the address of the last one. NULL if not used.
* @return Number of bytes read. 0 means timed out or closed. -1 means would block or error.
*/
int recv(uint8_t* data, size_t maxLen, bool forceLen = false, int timeout = NO_TIMEOUT, Address* dest = NULL);
/**
* Receive line from socket.
* @param str String to read the data into.
* @param maxLen Maximum line length allowed, 0 for no limit.
* @param timeout Timeout in milliseconds. Use NO_TIMEOUT or NONBLOCKING here if needed.
* @param dest Destination address. If multiple packets, this will contain the address of the last one. NULL if not used.
* @return Length of the returned string. 0 means timed out or closed. -1 means would block or error.
*/
int recvline(std::string& str, int maxLen = 0, int timeout = NO_TIMEOUT, Address* dest = NULL);
private:
Address* raddr = NULL;
SockHandle_t sock;
bool open = true;
};
class Listener {
public:
/**
* Do not instantiate this class manually. Use the provided functions.
*/
Listener(SockHandle_t sock);
~Listener();
/**
* Stop listening. The listener can no longer be used after this.
*/
void stop();
/**
* CHeck if the listener is still listening.
* @return True if listening, false if not.
*/
bool listening();
/**
* Accept connection.
* @param timeout Timeout in milliseconds. Use NO_TIMEOUT or NONBLOCKING here if needed.
* @return Socket of the connection. NULL means timed out, would block or closed.
*/
std::shared_ptr<Socket> accept(Address* dest = NULL, int timeout = NO_TIMEOUT);
private:
SockHandle_t sock;
bool open = true;
};
/**
* Get a list of the network interface.
* @return List of network interfaces and their addresses.
*/
std::map<std::string, InterfaceInfo> listInterfaces();
/**
* Create TCP listener.
* @param addr Address to listen on.
* @return Listener instance on success, Throws runtime_error otherwise.
*/
std::shared_ptr<Listener> listen(const Address& addr);
/**
* Create TCP listener.
* @param host Hostname or IP to listen on ("0.0.0.0" for Any).
* @param port Port to listen on.
* @return Listener instance on success, Throws runtime_error otherwise.
*/
std::shared_ptr<Listener> listen(std::string host, int port);
/**
* Create TCP connection.
* @param addr Remote address.
* @return Socket instance on success, Throws runtime_error otherwise.
*/
std::shared_ptr<Socket> connect(const Address& addr);
/**
* Create TCP connection.
* @param host Remote hostname or IP address.
* @param port Remote port.
* @return Socket instance on success, Throws runtime_error otherwise.
*/
std::shared_ptr<Socket> connect(std::string host, int port);
/**
* Create UDP socket.
* @param raddr Remote address.
* @param laddr Local address to bind the socket to.
* @return Socket instance on success, Throws runtime_error otherwise.
*/
std::shared_ptr<Socket> openudp(const Address& raddr, const Address& laddr);
/**
* Create UDP socket.
* @param rhost Remote hostname or IP address.
* @param rport Remote port.
* @param laddr Local address to bind the socket to.
* @return Socket instance on success, Throws runtime_error otherwise.
*/
std::shared_ptr<Socket> openudp(std::string rhost, int rport, const Address& laddr);
/**
* Create UDP socket.
* @param raddr Remote address.
* @param lhost Local hostname or IP used to bind the socket (optional, "0.0.0.0" for Any).
* @param lpost Local port used to bind the socket to (optional, 0 to allocate automatically).
* @return Socket instance on success, Throws runtime_error otherwise.
*/
std::shared_ptr<Socket> openudp(const Address& raddr, std::string lhost = "0.0.0.0", int lport = 0);
/**
* Create UDP socket.
* @param rhost Remote hostname or IP address.
* @param rport Remote port.
* @param lhost Local hostname or IP used to bind the socket (optional, "0.0.0.0" for Any).
* @param lpost Local port used to bind the socket to (optional, 0 to allocate automatically).
* @return Socket instance on success, Throws runtime_error otherwise.
*/
std::shared_ptr<Socket> openudp(std::string rhost, int rport, std::string lhost = "0.0.0.0", int lport = 0);
}