Added untested DNS client code

This commit is contained in:
Joseph Henry
2017-10-09 00:07:31 -07:00
parent 0319f8a894
commit 7301c8c405
7 changed files with 172 additions and 54 deletions

View File

@@ -31,6 +31,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <string> #include <string>
#include <fcntl.h> #include <fcntl.h>
#include <regex.h>
#include <vector> #include <vector>
#include <algorithm> #include <algorithm>
@@ -45,12 +46,13 @@ namespace ZeroTier {
typedef void PhySocket; typedef void PhySocket;
ZTProxy::ZTProxy(int proxy_listen_port, std::string nwid, std::string path, std::string internal_addr, ZTProxy::ZTProxy(int proxy_listen_port, std::string nwid, std::string path, std::string internal_addr,
int internal_port) int internal_port, std::string dns_nameserver)
: :
_enabled(true), _enabled(true),
_run(true), _run(true),
_proxy_listen_port(proxy_listen_port), _proxy_listen_port(proxy_listen_port),
_internal_port(internal_port), _internal_port(internal_port),
_dns_nameserver(dns_nameserver),
_nwid(nwid), _nwid(nwid),
_internal_addr(internal_addr), _internal_addr(internal_addr),
_phy(this,false,true) _phy(this,false,true)
@@ -97,6 +99,14 @@ namespace ZeroTier {
void ZTProxy::threadMain() void ZTProxy::threadMain()
throw() throw()
{ {
// Add DNS nameserver
if (_dns_nameserver.length() > 0) {
DEBUG_INFO("setting DNS nameserver (%s)", _dns_nameserver.c_str());
struct sockaddr_in dns_address;
dns_address.sin_addr.s_addr = inet_addr(_dns_nameserver.c_str());
zts_add_dns_nameserver((struct sockaddr*)&dns_address);
}
TcpConnection *conn = NULL; TcpConnection *conn = NULL;
uint32_t msecs = 1; uint32_t msecs = 1;
struct timeval tv; struct timeval tv;
@@ -185,63 +195,89 @@ namespace ZeroTier {
} }
} }
bool isValidIPAddress(const char *ip)
{
struct sockaddr_in sa;
return inet_pton(AF_INET, ip, &(sa.sin_addr)) == 1;
}
void ZTProxy::phyOnTcpData(PhySocket *sock, void **uptr, void *data, unsigned long len) void ZTProxy::phyOnTcpData(PhySocket *sock, void **uptr, void *data, unsigned long len)
{ {
int wr = 0, zfd = -1, err = 0; int wr = 0, zfd = -1, err = 0;
DEBUG_EXTRA("sock=%p, len=%lu", sock, len); DEBUG_EXTRA("sock=%p, len=%lu", sock, len);
std::string host = _internal_addr; std::string host = _internal_addr;
// Get the TcpConnection object
TcpConnection *conn = cmap[sock]; TcpConnection *conn = cmap[sock];
if (conn == NULL) { if (conn == NULL) {
DEBUG_ERROR("invalid conn"); DEBUG_ERROR("invalid conn");
exit(0); exit(0);
} }
if (conn->zfd < 0) { // no connection yet if (conn->zfd < 0) { // no connection yet
DEBUG_INFO("no connection yet, will establish...");
if (host == "") {
DEBUG_ERROR("invalid hostname or address (empty)");
return;
}
DEBUG_INFO("establishing proxy connection..."); DEBUG_INFO("establishing proxy connection...");
if (host != "")
{ uint16_t dest_port, ipv;
uint16_t dest_port, ipv; dest_port = _internal_port;
dest_port = _internal_port; host = _internal_addr;
host = _internal_addr;
ipv = host.find(":") != std::string::npos ? 6 : 4; if (isValidIPAddress(host.c_str()) == false) {
// try to resolve this if it isn't an IP address
struct hostent *h = zts_gethostbyname(host.c_str());
if (h == NULL) {
DEBUG_ERROR("unable to resolve hostname (%s) (errno=%d)", host.c_str(), errno);
return;
}
// TODO
// host = h->h_addr_list[0];
}
if (ipv == 4) { // determine address type
// Connect to proxied host via libzt ipv = host.find(":") != std::string::npos ? 6 : 4;
DEBUG_INFO("attempting to proxy [0.0.0.0:%d -> %s:%d]", _proxy_listen_port, host.c_str(), dest_port);
struct sockaddr_in in4; // connect to remote host
memset(&in4,0,sizeof(in4)); if (ipv == 4) {
in4.sin_family = AF_INET; DEBUG_INFO("attempting to proxy [0.0.0.0:%d -> %s:%d]", _proxy_listen_port, host.c_str(), dest_port);
in4.sin_addr.s_addr = inet_addr(host.c_str()); struct sockaddr_in in4;
in4.sin_port = Utils::hton(dest_port); memset(&in4,0,sizeof(in4));
zfd = zts_socket(AF_INET, SOCK_STREAM, 0); in4.sin_family = AF_INET;
err = zts_connect(zfd, (const struct sockaddr *)&in4, sizeof(in4)); in4.sin_addr.s_addr = inet_addr(host.c_str());
in4.sin_port = Utils::hton(dest_port);
if ((zfd = zts_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
DEBUG_ERROR("unable to create socket (errno=%d)", errno);
return;
} }
if (ipv == 6) { if ((err = zts_connect(zfd, (const struct sockaddr *)&in4, sizeof(in4))) < 0) {
// Connect to proxied host via libzt DEBUG_ERROR("unable to connect to remote host (errno=%d)", errno);
//DEBUG_INFO("attempting to proxy [0.0.0.0:%d -> %s:%d]", _proxy_listen_port, host.c_str(), dest_port);
struct sockaddr_in6 in6;
memset(&in6,0,sizeof(in6));
in6.sin6_family = AF_INET;
struct hostent *server;
server = gethostbyname2((char*)host.c_str(),AF_INET6);
memmove((char *) &in6.sin6_addr.s6_addr, (char *) server->h_addr, server->h_length);
in6.sin6_port = Utils::hton(dest_port);
zfd = zts_socket(AF_INET, SOCK_STREAM, 0);
err = zts_connect(zfd, (const struct sockaddr *)&in6, sizeof(in6));
}
if (zfd < 0 || err < 0) {
// now release TX buffer contents we previously saved, since we can't connect
DEBUG_ERROR("error while connecting to remote host (zfd=%d, err=%d)", zfd, err);
conn->tx_m.lock();
conn->TXbuf->reset();
conn->tx_m.unlock();
return; return;
} }
else {
DEBUG_INFO("successfully connected to remote host");
}
} }
if (ipv == 6) {
//DEBUG_INFO("attempting to proxy [0.0.0.0:%d -> %s:%d]", _proxy_listen_port, host.c_str(), dest_port);
struct sockaddr_in6 in6;
memset(&in6,0,sizeof(in6));
in6.sin6_family = AF_INET;
struct hostent *server;
server = gethostbyname2((char*)host.c_str(),AF_INET6);
memmove((char *) &in6.sin6_addr.s6_addr, (char *) server->h_addr, server->h_length);
in6.sin6_port = Utils::hton(dest_port);
zfd = zts_socket(AF_INET, SOCK_STREAM, 0);
err = zts_connect(zfd, (const struct sockaddr *)&in6, sizeof(in6));
}
if (zfd < 0 || err < 0) {
// now release TX buffer contents we previously saved, since we can't connect
DEBUG_ERROR("error while connecting to remote host (zfd=%d, err=%d)", zfd, err);
conn->tx_m.lock();
conn->TXbuf->reset();
conn->tx_m.unlock();
return;
}
else {
DEBUG_INFO("successfully connected to remote host");
}
conn_m.lock(); conn_m.lock();
// on success, add connection entry to map, set physock for later // on success, add connection entry to map, set physock for later
clist.push_back(conn); clist.push_back(conn);
@@ -251,6 +287,9 @@ namespace ZeroTier {
zmap[zfd] = conn; zmap[zfd] = conn;
conn_m.unlock(); conn_m.unlock();
} }
else {
DEBUG_INFO("connection already established, reusing...");
}
// Write data coming from client TCP connection to its TX buffer, later emptied into libzt by threadMain I/O loop // Write data coming from client TCP connection to its TX buffer, later emptied into libzt by threadMain I/O loop
conn->tx_m.lock(); conn->tx_m.lock();
if ((wr = conn->TXbuf->write((const unsigned char *)data, len)) < 0) { if ((wr = conn->TXbuf->write((const unsigned char *)data, len)) < 0) {
@@ -278,6 +317,9 @@ namespace ZeroTier {
TcpConnection *conn = cmap[sock]; TcpConnection *conn = cmap[sock];
if (conn) { if (conn) {
conn->client_sock=NULL; conn->client_sock=NULL;
if (conn->zfd >= 0) {
zts_close(conn->zfd);
}
cmap.erase(sock); cmap.erase(sock);
for (int i=0; i<clist.size(); i++) { for (int i=0; i<clist.size(); i++) {
if (conn == clist[i]) { if (conn == clist[i]) {
@@ -319,9 +361,9 @@ namespace ZeroTier {
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
if (argc != 6) { if (argc < 6 || argc > 7) {
printf("\nZeroTier TCP Proxy Service\n"); printf("\nZeroTier TCP Proxy Service\n");
printf("ztproxy [config_file_path] [local_listen_port] [nwid] [zt_host_addr] [zt_resource_port]\n"); printf("ztproxy [config_file_path] [local_listen_port] [nwid] [zt_host_addr] [zt_resource_port] [optional_dns_nameserver]\n");
exit(0); exit(0);
} }
std::string path = argv[1]; std::string path = argv[1];
@@ -329,8 +371,9 @@ int main(int argc, char **argv)
std::string nwid = argv[3]; std::string nwid = argv[3];
std::string internal_addr = argv[4]; std::string internal_addr = argv[4];
int internal_port = atoi(argv[5]); int internal_port = atoi(argv[5]);
std::string dns_nameserver= argv[6];
ZeroTier::ZTProxy *proxy = new ZeroTier::ZTProxy(proxy_listen_port, nwid, path, internal_addr, internal_port); ZeroTier::ZTProxy *proxy = new ZeroTier::ZTProxy(proxy_listen_port, nwid, path, internal_addr, internal_port, dns_nameserver);
if (proxy) { if (proxy) {
printf("\nZTProxy started. Listening on %d\n", proxy_listen_port); printf("\nZTProxy started. Listening on %d\n", proxy_listen_port);

View File

@@ -75,7 +75,7 @@ namespace ZeroTier {
friend class Phy<ZTProxy *>; friend class Phy<ZTProxy *>;
public: public:
ZTProxy(int proxy_listen_port, std::string nwid, std::string path, std::string internal_addr, int internal_port); ZTProxy(int proxy_listen_port, std::string nwid, std::string path, std::string internal_addr, int internal_port, std::string _dns_nameserver);
~ZTProxy(); ~ZTProxy();
// Send incoming data to intended host // Send incoming data to intended host
@@ -111,6 +111,7 @@ namespace ZeroTier {
int _internal_port; int _internal_port;
std::string _nwid; std::string _nwid;
std::string _internal_addr; std::string _internal_addr;
std::string _dns_nameserver;
Thread _thread; Thread _thread;
Phy<ZTProxy*> _phy; Phy<ZTProxy*> _phy;

View File

@@ -413,6 +413,15 @@ int zts_gethostname(char *name, size_t len);
*/ */
int zts_sethostname(const char *name, size_t len); int zts_sethostname(const char *name, size_t len);
/**
* @brief Return a pointer to an object with the following structure describing an internet host referenced by name
*
* @usage Call this after zts_start() has succeeded
* @param name
* @return Returns pointer to hostent structure otherwise NULL if failure
*/
struct hostent *zts_gethostbyname(const char *name);
/** /**
* @brief Close a socket * @brief Close a socket
* *

View File

@@ -46,6 +46,22 @@
*/ */
void lwip_driver_init(); void lwip_driver_init();
/**
* @brief Initialize and start the DNS client
*
* @usage Called after lwip_driver_init()
* @return
*/
void lwip_dns_init();
/**
* @brief Starts DHCP timers
*
* @usage lwip_driver_init()
* @return
*/
void lwip_start_dhcp(struct netif *interface);
void general_lwip_init_interface(void *tapref, struct netif *interface, const char *name, const ZeroTier::MAC &mac, void general_lwip_init_interface(void *tapref, struct netif *interface, const char *name, const ZeroTier::MAC &mac,
const ZeroTier::InetAddress &addr, const ZeroTier::InetAddress &nm, const ZeroTier::InetAddress &gw); const ZeroTier::InetAddress &addr, const ZeroTier::InetAddress &nm, const ZeroTier::InetAddress &gw);

View File

@@ -167,6 +167,7 @@
#undef TCP_MSS #undef TCP_MSS
#define TCP_MSS 1460 #define TCP_MSS 1460
#define LWIP_NETIF_API 1
/* /*
The TCP window size can be adjusted by changing the define TCP_WND. However, The TCP window size can be adjusted by changing the define TCP_WND. However,
do keep in mind that this should be at least twice the size of TCP_MSS (thus do keep in mind that this should be at least twice the size of TCP_MSS (thus
@@ -356,26 +357,26 @@ happening sooner than they should.
* MEMP_NUM_NETCONN: the number of struct netconns. * MEMP_NUM_NETCONN: the number of struct netconns.
* (only needed if you use the sequential API, like api_lib.c) * (only needed if you use the sequential API, like api_lib.c)
*/ */
#define MEMP_NUM_NETCONN 4 #define MEMP_NUM_NETCONN 32
/** /**
* MEMP_NUM_TCPIP_MSG_API: the number of struct tcpip_msg, which are used * MEMP_NUM_TCPIP_MSG_API: the number of struct tcpip_msg, which are used
* for callback/timeout API communication. * for callback/timeout API communication.
* (only needed if you use tcpip.c) * (only needed if you use tcpip.c)
*/ */
#define MEMP_NUM_TCPIP_MSG_API 8 #define MEMP_NUM_TCPIP_MSG_API 64
/** /**
* MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used * MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used
* for incoming packets. * for incoming packets.
* (only needed if you use tcpip.c) * (only needed if you use tcpip.c)
*/ */
#define MEMP_NUM_TCPIP_MSG_INPKT 8 #define MEMP_NUM_TCPIP_MSG_INPKT 32
/** /**
* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. * PBUF_POOL_SIZE: the number of buffers in the pbuf pool.
*/ */
#define PBUF_POOL_SIZE 8000 /* was 32 */ #define PBUF_POOL_SIZE 4092 /* was 32 */
/*------------------------------------------------------------------------------ /*------------------------------------------------------------------------------
@@ -433,7 +434,7 @@ happening sooner than they should.
* PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive
* packets even if the maximum amount of fragments is enqueued for reassembly! * packets even if the maximum amount of fragments is enqueued for reassembly!
*/ */
#define IP_REASS_MAX_PBUFS 4 #define IP_REASS_MAX_PBUFS 32
/** /**
* IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP
@@ -476,7 +477,7 @@ happening sooner than they should.
/** /**
* LWIP_DHCP==1: Enable DHCP module. * LWIP_DHCP==1: Enable DHCP module.
*/ */
#define LWIP_DHCP 0 #define LWIP_DHCP 1
/*------------------------------------------------------------------------------ /*------------------------------------------------------------------------------
@@ -518,7 +519,7 @@ happening sooner than they should.
* LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS
* transport. * transport.
*/ */
#define LWIP_DNS 0 #define LWIP_DNS 1
/*------------------------------------------------------------------------------ /*------------------------------------------------------------------------------

View File

@@ -36,6 +36,8 @@
#include "lwip/sockets.h" #include "lwip/sockets.h"
#include "lwip/sys.h" #include "lwip/sys.h"
#include "lwip/ip_addr.h" #include "lwip/ip_addr.h"
#include "lwip/netdb.h"
#include "dns.h"
#endif #endif
#if defined(NO_STACK) #if defined(NO_STACK)
#include <sys/socket.h> #include <sys/socket.h>
@@ -265,6 +267,36 @@ int zts_sethostname(const char *name, size_t len)
return err; return err;
} }
struct hostent *zts_gethostbyname(const char *name)
{
#if defined(STACK_LWIP)
// TODO:
char buf[256];
int buflen = 256;
int h_err = 0;
struct hostent hret;
struct hostent **result = NULL;
int err = 0;
/*
if ((err = lwip_gethostbyname_r(name, &hret, buf, buflen, result, &h_err)) != 0) {
DEBUG_ERROR("err = %d", err);
DEBUG_ERROR("h_err = %d", h_err);
errno = h_err;
return NULL; // failure
}
return *result;
*/
return lwip_gethostbyname(name);
#endif
#if defined(STCK_PICO)
#endif
#if defined(NO_STACK)
return NULL;
#endif
}
int zts_close(int fd) int zts_close(int fd)
{ {
int err = -1; int err = -1;
@@ -475,6 +507,12 @@ int zts_add_dns_nameserver(struct sockaddr *addr)
DEBUG_EXTRA(); DEBUG_EXTRA();
int err = -1; int err = -1;
#if defined(STACK_LWIP) #if defined(STACK_LWIP)
struct sockaddr_in *in4 = (struct sockaddr_in*)&addr;
static ip_addr_t ipaddr;
ipaddr.addr = in4->sin_addr.s_addr;
// TODO: manage DNS server indices
dns_setserver(0, &ipaddr);
err = 0;
#endif #endif
#if defined(STCK_PICO) #if defined(STCK_PICO)
#endif #endif

View File

@@ -51,6 +51,9 @@
#include "lwip/timeouts.h" #include "lwip/timeouts.h"
#include "lwip/stats.h" #include "lwip/stats.h"
#include "dns.h"
#include "netifapi.h"
#include "lwIP.hpp" #include "lwIP.hpp"
netif lwipdev, lwipdev6, n1; netif lwipdev, lwipdev6, n1;
@@ -87,7 +90,6 @@ static void tcpip_init_done(void *arg)
DEBUG_EXTRA("lwIP stack driver initialized"); DEBUG_EXTRA("lwIP stack driver initialized");
lwip_driver_initialized = true; lwip_driver_initialized = true;
driver_m.unlock(); driver_m.unlock();
DEBUG_EXTRA("released lock");
// sys_timeout(5000, tcp_timeout, NULL); // sys_timeout(5000, tcp_timeout, NULL);
sys_sem_signal(sem); sys_sem_signal(sem);
} }
@@ -109,9 +111,7 @@ static void main_network_stack_thread(void *arg)
// initialize the lwIP stack // initialize the lwIP stack
void lwip_driver_init() void lwip_driver_init()
{ {
DEBUG_EXTRA("getting lock..");
driver_m.lock(); // unlocked from callback indicating completion of driver init driver_m.lock(); // unlocked from callback indicating completion of driver init
DEBUG_EXTRA("got lock");
if (lwip_driver_initialized == true) { if (lwip_driver_initialized == true) {
return; return;
} }
@@ -201,6 +201,16 @@ void general_turn_on_interface(struct netif *interface)
//netif_set_link_down(&lwipdev); //netif_set_link_down(&lwipdev);
} }
void lwip_dns_init()
{
dns_init();
}
void lwip_start_dhcp(struct netif *interface)
{
netifapi_dhcp_start(interface);
}
void lwip_init_interface(void *tapref, const ZeroTier::MAC &mac, const ZeroTier::InetAddress &ip) void lwip_init_interface(void *tapref, const ZeroTier::MAC &mac, const ZeroTier::InetAddress &ip)
{ {
char ipbuf[INET6_ADDRSTRLEN], nmbuf[INET6_ADDRSTRLEN]; char ipbuf[INET6_ADDRSTRLEN], nmbuf[INET6_ADDRSTRLEN];