dynamic loading of network stack no longer needed

This commit is contained in:
Joseph Henry
2017-04-06 19:16:01 -07:00
parent 997f12a592
commit 08cca3c7aa
463 changed files with 136513 additions and 0 deletions

2
src/README.md Normal file
View File

@@ -0,0 +1,2 @@
src
======

343
src/RPC.c Normal file
View File

@@ -0,0 +1,343 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifdef USE_GNU_SOURCE
#define _GNU_SOURCE
#endif
#if defined(__linux__)
#include <sys/syscall.h>
#endif
#include <stdio.h>
#include <unistd.h>
#include <sys/un.h>
#include <pthread.h>
#include <errno.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <stdint.h>
#include <strings.h>
#include "ZeroTierSDK.h"
#include "RPC.h"
// externs common between SDK_Intercept and SDK_Socket from SDK.h
int (*realsocket)(SOCKET_SIG);
int (*realconnect)(CONNECT_SIG);
#ifdef __cplusplus
extern "C" {
#endif
#define SERVICE_CONNECT_ATTEMPTS 30
ssize_t sock_fd_write(int sock, int fd);
ssize_t sock_fd_read(int sock, void *buf, ssize_t bufsize, int *fd);
static int rpc_count;
static pthread_mutex_t lock;
void rpc_mutex_init() {
if(pthread_mutex_init(&lock, NULL) != 0) {
}
}
void rpc_mutex_destroy() {
pthread_mutex_destroy(&lock);
}
/*
* Reads a new file descriptor from the service
*/
int get_new_fd(int sock)
{
char buf[BUF_SZ];
int newfd;
ssize_t size = sock_fd_read(sock, buf, sizeof(buf), &newfd);
if(size > 0)
return newfd;
return -1;
}
/*
* Reads a return value from the service and sets errno (if applicable)
*/
int get_retval(int rpc_sock)
{
if(rpc_sock >= 0) {
int retval;
int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
char retbuf[BUF_SZ];
memset(&retbuf, 0, sz);
long n_read = read(rpc_sock, &retbuf, sz);
if(n_read > 0) {
memcpy(&retval, &retbuf[1], sizeof(retval));
memcpy(&errno, &retbuf[1+sizeof(retval)], sizeof(errno));
return retval;
}
}
return -1;
}
int load_symbols_rpc()
{
#if defined(__IOS__) || defined(__UNITY_3D__)
realsocket = dlsym(RTLD_NEXT, "socket");
realconnect = dlsym(RTLD_NOW, "connect");
if(!realconnect || !realsocket)
return -1;
#endif
return 1;
}
int rpc_join(char * sockname)
{
if(sockname == NULL) {
DEBUG_ERROR("warning, rpc netpath is NULL");
}
if(!load_symbols_rpc())
return -1;
struct sockaddr_un addr;
int conn_err = -1, attempts = 0;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, sockname, sizeof(addr.sun_path)-1);
int sock;
#if defined(SDK_INTERCEPT)
if((sock = realsocket(AF_UNIX, SOCK_STREAM, 0)) < 0){
#else
if((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){
#endif
DEBUG_ERROR("error creating RPC socket");
return -1;
}
while((conn_err != 0) /* && (attempts < SERVICE_CONNECT_ATTEMPTS) */){
#if defined(SDK_INTERCEPT)
if((conn_err = realconnect(sock, (struct sockaddr*)&addr, sizeof(addr))) != 0) {
#else
if((conn_err = connect(sock, (struct sockaddr*)&addr, sizeof(addr))) != 0) {
#endif
DEBUG_ERROR("error connecting to RPC socket (%s). Re-attempting...", sockname);
usleep(100000);
}
else
return sock;
attempts++;
}
return -1;
}
/*
* Send a command to the service
*/
int rpc_send_command(char *path, int cmd, int forfd, void *data, int len)
{
pthread_mutex_lock(&lock);
char c, padding[] = {PADDING};
char cmdbuf[BUF_SZ], CANARY[CANARY_SZ+PADDING_SZ], metabuf[BUF_SZ];
memcpy(CANARY+CANARY_SZ, padding, sizeof(padding));
uint64_t canary_num;
// ephemeral RPC socket used only for this command
int rpc_sock = rpc_join(path);
// Generate token
int fdrand = open("/dev/urandom", O_RDONLY);
if(read(fdrand, &CANARY, CANARY_SZ) < 0) {
DEBUG_ERROR("unable to read from /dev/urandom for RPC canary data");
return -1;
}
close(fdrand);
memcpy(&canary_num, CANARY, CANARY_SZ);
cmdbuf[CMD_ID_IDX] = cmd;
memcpy(&cmdbuf[CANARY_IDX], &canary_num, CANARY_SZ);
memcpy(&cmdbuf[STRUCT_IDX], data, len);
rpc_count++;
memset(metabuf, 0, BUF_SZ);
#if defined(__linux__)
#if !defined(__ANDROID__)
pid_t pid = 5; //syscall(SYS_getpid);
pid_t tid = 4;//syscall(SYS_gettid);
#else
// Dummy values
pid_t pid = 5;
pid_t tid = gettid();
#endif
#endif
char timestring[20];
time_t timestamp;
timestamp = time(NULL);
strftime(timestring, sizeof(timestring), "%H:%M:%S", localtime(&timestamp));
#if defined(__linux__)
memcpy(&metabuf[IDX_PID], &pid, sizeof(pid_t) ); /* pid */
memcpy(&metabuf[IDX_TID], &tid, sizeof(pid_t) ); /* tid */
#endif
memcpy(&metabuf[IDX_TIME], &timestring, 20 ); /* timestamp */
/* Combine command flag+payload with RPC metadata */
memcpy(metabuf, RPC_PHRASE, RPC_PHRASE_SZ); // Write signal phrase
memcpy(&metabuf[IDX_PAYLOAD], cmdbuf, len + 1 + CANARY_SZ);
// Write RPC
long n_write = write(rpc_sock, &metabuf, BUF_SZ);
if(n_write < 0) {
DEBUG_ERROR("error writing command to service (CMD = %d)", cmdbuf[CMD_ID_IDX]);
errno = 0;
}
// Write token to corresponding data stream
if(read(rpc_sock, &c, 1) < 0) {
DEBUG_ERROR("unable to read RPC ACK byte from service.");
close(rpc_sock);
return -1;
}
if(c == 'z' && n_write > 0 && forfd > -1){
if(send(forfd, &CANARY, CANARY_SZ+PADDING_SZ, 0) < 0) {
perror("send: \n");
DEBUG_ERROR("unable to write canary to stream (fd=%d)", forfd);
close(rpc_sock);
return -1;
}
}
// Process response from service
int ret = ERR_OK;
if(n_write > 0) {
if(cmdbuf[CMD_ID_IDX]==RPC_SOCKET) {
pthread_mutex_unlock(&lock);
return rpc_sock; // Used as new socket
}
if(cmdbuf[CMD_ID_IDX]==RPC_CONNECT
|| cmdbuf[CMD_ID_IDX]==RPC_BIND
|| cmdbuf[CMD_ID_IDX]==RPC_LISTEN) {
ret = get_retval(rpc_sock);
}
if(cmdbuf[CMD_ID_IDX]==RPC_GETSOCKNAME || cmdbuf[CMD_ID_IDX]==RPC_GETPEERNAME) {
pthread_mutex_unlock(&lock);
return rpc_sock; // Don't close rpc here, we'll use it to read getsockopt_st
}
}
else
ret = -1;
close(rpc_sock); // We're done with this RPC socket, close it (if type-R)
pthread_mutex_unlock(&lock);
return ret;
}
/*
* Send file descriptor
*/
ssize_t sock_fd_write(int sock, int fd)
{
ssize_t size;
struct msghdr msg;
struct iovec iov;
char buf = '\0';
int buflen = 1;
union {
struct cmsghdr cmsghdr;
char control[CMSG_SPACE(sizeof (int))];
} cmsgu;
struct cmsghdr *cmsg;
iov.iov_base = &buf;
iov.iov_len = buflen;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
if (fd != -1) {
msg.msg_control = cmsgu.control;
msg.msg_controllen = sizeof(cmsgu.control);
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_len = CMSG_LEN(sizeof (int));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
*((int *) CMSG_DATA(cmsg)) = fd;
} else {
msg.msg_control = NULL;
msg.msg_controllen = 0;
}
size = sendmsg(sock, &msg, 0);
if (size < 0)
perror ("sendmsg");
return size;
}
/*
* Read a file descriptor
*/
ssize_t sock_fd_read(int sock, void *buf, ssize_t bufsize, int *fd)
{
ssize_t size;
if (fd) {
struct msghdr msg;
struct iovec iov;
union {
struct cmsghdr cmsghdr;
char control[CMSG_SPACE(sizeof (int))];
} cmsgu;
struct cmsghdr *cmsg;
iov.iov_base = buf;
iov.iov_len = bufsize;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsgu.control;
msg.msg_controllen = sizeof(cmsgu.control);
size = recvmsg (sock, &msg, 0);
if (size < 0)
return -1;
cmsg = CMSG_FIRSTHDR(&msg);
if (cmsg && cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
if (cmsg->cmsg_level != SOL_SOCKET) {
DEBUG_ERROR("invalid cmsg_level %d",cmsg->cmsg_level);
return -1;
}
if (cmsg->cmsg_type != SCM_RIGHTS) {
DEBUG_ERROR("invalid cmsg_type %d",cmsg->cmsg_type);
return -1;
}
*fd = *((int *) CMSG_DATA(cmsg));
} else {
*fd = -1;}
} else {
size = read (sock, buf, bufsize);
if (size < 0) {
DEBUG_ERROR("sock_fd_read(): read: Error");
return -1;
}
}
return size;
}
#ifdef __cplusplus
}
#endif

144
src/RPC.h Normal file
View File

@@ -0,0 +1,144 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef __RPCLIB_H_
#define __RPCLIB_H_
#include <sys/socket.h>
#define CANARY_SZ sizeof(uint64_t)
#define PADDING_SZ 12
#define PADDING 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
#define RPC_PHRASE "zerotier\0"
#define RPC_PHRASE_SZ 9
#define RPC_TIMESTAMP_SZ 20
// 1st RPC section (metdata)
#define IDX_SIGNAL_PHRASE 0
#define IDX_PID IDX_SIGNAL_PHRASE + RPC_PHRASE_SZ
#define IDX_TID sizeof(pid_t) + IDX_PID
#define IDX_TIME IDX_TID + sizeof(int)
#define IDX_PAYLOAD IDX_TIME + RPC_TIMESTAMP_SZ
// 2nd RPC section (payload and canary)
#define CMD_ID_IDX 0
#define CANARY_IDX 1
#define STRUCT_IDX CANARY_IDX+CANARY_SZ
#define BUF_SZ 512
#define ERR_OK 0
/* RPC codes */
#define RPC_UNDEFINED 0
#define RPC_CONNECT 1
#define RPC_CONNECT_SOCKARG 2
#define RPC_CLOSE 3
#define RPC_READ 4
#define RPC_WRITE 5
#define RPC_BIND 6
#define RPC_ACCEPT 7
#define RPC_LISTEN 8
#define RPC_SOCKET 9
#define RPC_SHUTDOWN 10
#define RPC_GETSOCKNAME 11
#define RPC_GETPEERNAME 12
#define RPC_RETVAL 13
#define RPC_IS_CONNECTED 14
#ifdef __cplusplus
extern "C" {
#endif
int get_retval(int);
int rpc_join( char * sockname);
int rpc_send_command(char *path, int cmd, int forfd, void *data, int len);
int get_new_fd(int sock);
ssize_t sock_fd_write(int sock, int fd);
ssize_t sock_fd_read(int sock, void *buf, ssize_t bufsize, int *fd);
void rpc_mutex_destroy();
void rpc_mutex_init();
/* Structures used for sending commands via RPC mechanism */
struct bind_st {
int fd;
struct sockaddr_storage addr;
socklen_t addrlen;
int tid;
};
struct connect_st {
int fd;
struct sockaddr_storage addr;
socklen_t addrlen;
int tid;
};
struct close_st {
int fd;
};
struct listen_st {
int fd;
int backlog;
int tid;
};
struct socket_st {
int socket_family;
int socket_type;
int protocol;
int tid;
};
struct accept_st {
int fd;
struct sockaddr_storage addr;
socklen_t addrlen;
int tid;
};
struct shutdown_st {
int socket;
int how;
};
struct getsockname_st {
int fd;
struct sockaddr_storage addr;
socklen_t addrlen;
};
#ifdef __cplusplus
}
#endif
#endif

435
src/SDKService.cpp Normal file
View File

@@ -0,0 +1,435 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#if defined(__ANDROID__) || defined(__JNI_LIB__)
#include <jni.h>
#endif
#include <dlfcn.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <pthread.h>
#include "OneService.hpp"
#include "Utils.hpp"
#include "OSUtils.hpp"
#include "InetAddress.hpp"
#include "ZeroTierOne.h"
#include "SocketTap.hpp"
#include "ZeroTierSDK.h"
#ifdef __cplusplus
extern "C" {
#endif
static ZeroTier::OneService *zt1Service;
std::string service_path;
std::string localHomeDir; // Local shortened path
std::string givenHomeDir; // What the user/application provides as a suggestion
std::string homeDir; // The resultant platform-specific dir we *must* use internally
std::string netDir; // Where network .conf files are to be written
/****************************************************************************/
/* SDK Socket API */
/****************************************************************************/
void zts_start(const char *path)
{
DEBUG_INFO("path=%s", path);
if(path)
homeDir = path;
zts_start_core_service(NULL);
}
// Stop the service, proxy server, stack, etc
void zts_stop() {
DEBUG_INFO();
zts_stop_service();
}
char *zts_core_version() {
return (char*)"1.2.2";
}
// ------------------------------------------------------------------------------
// --------------------------------- Base zts_* API -----------------------------
// ------------------------------------------------------------------------------
// Prototypes
void *zts_start_core_service(void *thread_id);
void zts_init_rpc(const char * path, const char * nwid);
// Basic ZT service controls
void zts_join_network(const char * nwid) {
DEBUG_ERROR();
std::string confFile = zt1Service->givenHomePath() + "/networks.d/" + nwid + ".conf";
if(!ZeroTier::OSUtils::mkdir(netDir)) {
DEBUG_ERROR("unable to create: %s", netDir.c_str());
}
if(!ZeroTier::OSUtils::writeFile(confFile.c_str(), "")) {
DEBUG_ERROR("unable to write network conf file: %s", confFile.c_str());
}
zt1Service->join(nwid);
// Provide the API with the RPC information
zts_init_rpc(homeDir.c_str(), nwid);
}
// Just create the dir and conf file required, don't instruct the core to do anything
void zts_join_network_soft(const char * filepath, const char * nwid) {
std::string net_dir = std::string(filepath) + "/networks.d/";
std::string confFile = net_dir + std::string(nwid) + ".conf";
if(!ZeroTier::OSUtils::mkdir(net_dir)) {
DEBUG_ERROR("unable to create: %s", net_dir.c_str());
}
if(!ZeroTier::OSUtils::fileExists(confFile.c_str(),false)) {
if(!ZeroTier::OSUtils::writeFile(confFile.c_str(), "")) {
DEBUG_ERROR("unable to write network conf file: %s", confFile.c_str());
}
}
}
// Prevent service from joining network upon startup
void zts_leave_network_soft(const char * filepath, const char * nwid) {
std::string net_dir = std::string(filepath) + "/networks.d/";
ZeroTier::OSUtils::rm((net_dir + nwid + ".conf").c_str());
}
// Instruct the service to leave the network
void zts_leave_network(const char * nwid) {
if(zt1Service)
zt1Service->leave(nwid);
}
// Check whether the service is running
int zts_service_is_running() {
return !zt1Service ? false : zt1Service->isRunning();
}
// Stop the service
void zts_stop_service() {
if(zt1Service)
zt1Service->terminate();
}
// FIXME: Re-implemented to make it play nicer with the C-linkage required for Xcode integrations
// Now only returns first assigned address per network. Shouldn't normally be a problem.
// Get IPV4 Address for this device on given network
int zts_has_address(const char *nwid)
{
char ipv4_addr[64], ipv6_addr[64];
memset(ipv4_addr, 0, 64);
memset(ipv6_addr, 0, 64);
zts_get_ipv4_address(nwid, ipv4_addr);
zts_get_ipv6_address(nwid, ipv6_addr);
if(!strcmp(ipv4_addr, "-1.-1.-1.-1/-1") && !strcmp(ipv4_addr, "-1.-1.-1.-1/-1")) {
return false;
}
return true;
}
void zts_get_ipv4_address(const char *nwid, char *addrstr)
{
uint64_t nwid_int = strtoull(nwid, NULL, 16);
ZeroTier::SocketTap *tap = zt1Service->getTap(nwid_int);
if(tap && tap->_ips.size()){
for(int i=0; i<tap->_ips.size(); i++) {
if(tap->_ips[i].isV4()) {
std::string addr = tap->_ips[i].toString();
// DEBUG_EXTRA("addr=%s, addrlen=%d", addr.c_str(), addr.length());
memcpy(addrstr, addr.c_str(), addr.length()); // first address found that matches protocol version 4
return;
}
}
}
else {
memcpy(addrstr, "-1.-1.-1.-1/-1", 14);
}
}
// Get IPV6 Address for this device on given network
void zts_get_ipv6_address(const char *nwid, char *addrstr)
{
uint64_t nwid_int = strtoull(nwid, NULL, 16);
ZeroTier::SocketTap *tap = zt1Service->getTap(nwid_int);
if(tap && tap->_ips.size()){
for(int i=0; i<tap->_ips.size(); i++) {
if(tap->_ips[i].isV6()) {
std::string addr = tap->_ips[i].toString();
// DEBUG_EXTRA("addr=%s, addrlen=%d", addr.c_str(), addr.length());
memcpy(addrstr, addr.c_str(), addr.length()); // first address found that matches protocol version 4
return;
}
}
}
else {
memcpy(addrstr, "-1.-1.-1.-1/-1", 14);
}
}
// Get device ID (from running service)
int zts_get_device_id(char *devID) {
if(zt1Service) {
char id[10];
sprintf(id, "%lx",zt1Service->getNode()->address());
memcpy(devID, id, 10);
return 0;
}
else
return -1;
}
// Get device ID (from file)
int zts_get_device_id_from_file(const char *filepath, char *devID) {
std::string fname("identity.public");
std::string fpath(filepath);
if(ZeroTier::OSUtils::fileExists((fpath + ZT_PATH_SEPARATOR_S + fname).c_str(),false)) {
std::string oldid;
ZeroTier::OSUtils::readFile((fpath + ZT_PATH_SEPARATOR_S + fname).c_str(),oldid);
memcpy(devID, oldid.c_str(), 10); // first 10 bytes of file
return 0;
}
return -1;
}
// Get the IP address of a peer if a direct path is available
int zts_get_peer_address(char *peer, const char *devID) {
if(zt1Service) {
ZT_PeerList *pl = zt1Service->getNode()->peers();
// uint64_t addr;
for(int i=0; i<pl->peerCount; i++) {
// ZT_Peer *p = &(pl->peers[i]);
// DEBUG_INFO("peer[%d] = %lx", i, p->address);
}
return pl->peerCount;
}
else
return -1;
}
// Return the number of peers on this network
unsigned long zts_get_peer_count() {
if(zt1Service)
return zt1Service->getNode()->peers()->peerCount;
else
return 0;
}
// Return the home path for this instance of ZeroTier
char *zts_get_homepath() {
return (char*)givenHomeDir.c_str();
}
// Returns a 6PLANE IPv6 address given a network ID and zerotier ID
void zts_get_6plane_addr(char *addr, const char *nwid, const char *devID)
{
ZeroTier::InetAddress _6planeAddr = ZeroTier::InetAddress::makeIpv66plane(ZeroTier::Utils::hexStrToU64(nwid),ZeroTier::Utils::hexStrToU64(devID));
memcpy(addr, _6planeAddr.toIpString().c_str(), 40);
}
// Returns a RFC 4193 IPv6 address given a network ID and zerotier ID
void zts_get_rfc4193_addr(char *addr, const char *nwid, const char *devID)
{
ZeroTier::InetAddress _6planeAddr = ZeroTier::InetAddress::makeIpv6rfc4193(ZeroTier::Utils::hexStrToU64(nwid),ZeroTier::Utils::hexStrToU64(devID));
memcpy(addr, _6planeAddr.toIpString().c_str(), 40);
}
// ------------------------------------------------------------------------------
// ------------------------------ EXPORTED JNI METHODS --------------------------
// ------------------------------------------------------------------------------
// JNI naming convention: Java_PACKAGENAME_CLASSNAME_METHODNAME
#if defined(__ANDROID__) || defined(__JNI_LIB__)
// Returns whether the ZeroTier service is running
JNIEXPORT jboolean JNICALL Java_zerotier_ZeroTier_zt_1service_1is_1running(JNIEnv *env, jobject thisObj) {
if(zt1Service)
return zts_service_is_running();
return false;
}
// Returns path for ZT config/data files
JNIEXPORT jstring JNICALL Java_zerotier_ZeroTier_zt_1get_1homepath(JNIEnv *env, jobject thisObj) {
return (*env).NewStringUTF(zts_get_homepath());
}
// Join a network
JNIEXPORT void JNICALL Java_zerotier_ZeroTier_zt_1join_1network(JNIEnv *env, jobject thisObj, jstring nwid) {
const char *nwidstr;
if(nwid) {
nwidstr = env->GetStringUTFChars(nwid, NULL);
zts_join_network(nwidstr);
}
}
// Leave a network
JNIEXPORT void JNICALL Java_zerotier_ZeroTier_zt_1leave_1network(JNIEnv *env, jobject thisObj, jstring nwid) {
const char *nwidstr;
if(nwid) {
nwidstr = env->GetStringUTFChars(nwid, NULL);
zts_leave_network(nwidstr);
}
}
// FIXME: Re-implemented to make it play nicer with the C-linkage required for Xcode integrations
// Now only returns first assigned address per network. Shouldn't normally be a problem
JNIEXPORT jobject JNICALL Java_zerotier_ZeroTier_zt_1get_1ipv4_1address(JNIEnv *env, jobject thisObj, jstring nwid) {
const char *nwid_str = env->GetStringUTFChars(nwid, NULL);
char address_string[32];
memset(address_string, 0, 32);
zts_get_ipv4_address(nwid_str, address_string);
jclass clazz = (*env).FindClass("java/util/ArrayList");
jobject addresses = (*env).NewObject(clazz, (*env).GetMethodID(clazz, "<init>", "()V"));
jstring _str = (*env).NewStringUTF(address_string);
env->CallBooleanMethod(addresses, env->GetMethodID(clazz, "add", "(Ljava/lang/Object;)Z"), _str);
return addresses;
}
JNIEXPORT jobject JNICALL Java_zerotier_ZeroTier_zt_1get_1ipv6_1address(JNIEnv *env, jobject thisObj, jstring nwid) {
const char *nwid_str = env->GetStringUTFChars(nwid, NULL);
char address_string[32];
memset(address_string, 0, 32);
zts_get_ipv6_address(nwid_str, address_string);
jclass clazz = (*env).FindClass("java/util/ArrayList");
jobject addresses = (*env).NewObject(clazz, (*env).GetMethodID(clazz, "<init>", "()V"));
jstring _str = (*env).NewStringUTF(address_string);
env->CallBooleanMethod(addresses, env->GetMethodID(clazz, "add", "(Ljava/lang/Object;)Z"), _str);
return addresses;
}
// Returns the device is in integer form
JNIEXPORT jint Java_zerotier_ZeroTier_zt_1get_1device_1id() {
return zts_get_device_id(NULL); // TODO
}
// Returns whether the path to an endpoint is currently relayed by a root server
JNIEXPORT jboolean JNICALL Java_zerotier_ZeroTier_zt_1is_1relayed() {
return 0;
// TODO
// zts_is_relayed();
}
#endif
// ------------------------------------------------------------------------------
// --------------------------- zts_start_core_service ---------------------------
// ------------------------------------------------------------------------------
// Starts a ZeroTier service in the background
void *zts_start_core_service(void *thread_id) {
#if defined(SDK_BUNDLED)
if(thread_id)
homeDir = std::string((char*)thread_id);
#endif
#if defined(__IOS__)
char current_dir[MAX_DIR_SZ];
// Go to the app's data directory so we can shorten the sun_path we bind to
getcwd(current_dir, MAX_DIR_SZ);
std::string targetDir = homeDir; // + "/../../";
chdir(targetDir.c_str());
homeDir = localHomeDir;
#endif
#if defined(__APPLE__)
#include "TargetConditionals.h"
#if TARGET_IPHONE_SIMULATOR
// homeDir = "dont/run/this/in/the/simulator/it/wont/work";
#elif TARGET_OS_IPHONE
localHomeDir = "ZeroTier/One";
std::string del = givenHomeDir.length() && givenHomeDir[givenHomeDir.length()-1]!='/' ? "/" : "";
homeDir = givenHomeDir + del + localHomeDir;
#endif
#endif
#if defined(__APPLE__) && !defined(__IOS__)
localHomeDir = homeDir; // Used for RPC and *can* differ from homeDir on some platforms
#endif
DEBUG_INFO("homeDir=%s", homeDir.c_str());
// Where network .conf files will be stored
netDir = homeDir + "/networks.d";
zt1Service = (ZeroTier::OneService *)0;
// Construct path for network config and supporting service files
if (homeDir.length()) {
std::vector<std::string> hpsp(ZeroTier::OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
std::string ptmp;
if (homeDir[0] == ZT_PATH_SEPARATOR)
ptmp.push_back(ZT_PATH_SEPARATOR);
for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
if (ptmp.length() > 0)
ptmp.push_back(ZT_PATH_SEPARATOR);
ptmp.append(*pi);
if ((*pi != ".")&&(*pi != "..")) {
if (!ZeroTier::OSUtils::mkdir(ptmp)) {
DEBUG_ERROR("home path does not exist, and could not create");
perror("error\n");
}
}
}
}
else {
DEBUG_ERROR("homeDir is empty, could not construct path");
return NULL;
}
DEBUG_INFO("starting service...");
// Generate random port for new service instance
unsigned int randp = 0;
ZeroTier::Utils::getSecureRandom(&randp,sizeof(randp));
int servicePort = 9000 + (randp % 1000);
for(;;) {
zt1Service = ZeroTier::OneService::newInstance(homeDir.c_str(),servicePort);
switch(zt1Service->run()) {
case ZeroTier::OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
case ZeroTier::OneService::ONE_NORMAL_TERMINATION:
break;
case ZeroTier::OneService::ONE_UNRECOVERABLE_ERROR:
DEBUG_ERROR("fatal error: %s",zt1Service->fatalErrorMessage().c_str());
break;
case ZeroTier::OneService::ONE_IDENTITY_COLLISION: {
delete zt1Service;
zt1Service = (ZeroTier::OneService *)0;
std::string oldid;
ZeroTier::OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
if (oldid.length()) {
ZeroTier::OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
ZeroTier::OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
ZeroTier::OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
}
}
continue; // restart!
}
break; // terminate loop -- normally we don't keep restarting
}
delete zt1Service;
zt1Service = (ZeroTier::OneService *)0;
return NULL;
}
#ifdef __cplusplus
}
#endif

152
src/Socket.c Normal file
View File

@@ -0,0 +1,152 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
// For defining the Android direct-call API
#if defined(__ANDROID__) || defined(__JNI_LIB__)
#include <jni.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__linux__)
#define SOCK_MAX (SOCK_PACKET + 1)
#endif
#define SOCK_TYPE_MASK 0xf
#include "ZeroTierSDK.h"
#include "RPC.h"
char *api_netpath;
/****************************************************************************/
/* zts_init_rpc() */
/****************************************************************************/
int service_initialized = 0;
// Assembles (and/or) sets the RPC path for communication with the ZeroTier service
void zts_init_rpc(const char *path, const char *nwid)
{
// If no path, construct one or get it fron system env vars
if(!api_netpath) {
rpc_mutex_init();
// Provided by user
#if defined(SDK_BUNDLED)
// Get the path/nwid from the user application
// netpath = [path + "/nc_" + nwid]
char *fullpath = (char *)malloc(strlen(path)+strlen(nwid)+1+4);
if(fullpath) {
zts_join_network_soft(path, nwid);
strcpy(fullpath, path);
strcat(fullpath, "/nc_");
strcat(fullpath, nwid);
api_netpath = fullpath;
}
// Provided by Env
#else
// Get path/nwid from environment variables
if (!api_netpath) {
api_netpath = getenv("ZT_NC_NETWORK");
DEBUG_INFO("$ZT_NC_NETWORK=%s", api_netpath);
}
#endif
}
// start the SDK service if this is bundled
#if defined(SDK_BUNDLED)
if(!service_initialized) {
DEBUG_ATTN("api_netpath = %s", api_netpath);
pthread_t service_thread;
pthread_create(&service_thread, NULL, zts_start_core_service, (void *)(path));
service_initialized = 1;
DEBUG_ATTN("waiting for service to assign address to network stack");
// wait for zt service to assign the network stack an address
sleep(1);
while(!zts_has_address(nwid)) { usleep(1000); }
}
#endif
}
void get_api_netpath() { zts_init_rpc("",""); }
/****************************************************************************/
/* socket() */
/****************************************************************************/
// int socket_family, int socket_type, int protocol
#if defined(SDK_LANG_JAVA)
JNIEXPORT jint JNICALL Java_zerotier_ZeroTier_zt_1socket(JNIEnv *env, jobject thisObj, jint family, jint type, jint protocol) {
return zts_socket(family, type, protocol);
}
#endif
#ifdef DYNAMIC_LIB
int zt_socket(SOCKET_SIG)
#else
int zts_socket(SOCKET_SIG)
#endif
{
get_api_netpath();
DEBUG_INFO("");
// Check that type makes sense
#if defined(__linux__) && !defined(__ANDROID__)
int flags = socket_type & ~SOCK_TYPE_MASK;
if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
errno = EINVAL;
return -1;
}
#endif
socket_type &= SOCK_TYPE_MASK;
// Check protocol is in range
#if defined(__linux__)
if (socket_family < 0 || socket_family >= NPROTO){
errno = EAFNOSUPPORT;
return -1;
}
if (socket_type < 0 || socket_type >= SOCK_MAX) {
errno = EINVAL;
return -1;
}
#endif
// Assemble and send RPC
struct socket_st rpc_st;
rpc_st.socket_family = socket_family;
rpc_st.socket_type = socket_type;
rpc_st.protocol = protocol;
// -1 is passed since we we're generating the new socket in this call
return rpc_send_command(api_netpath, RPC_SOCKET, -1, &rpc_st, sizeof(struct socket_st));
}
#ifdef __cplusplus
}
#endif

510
src/SocketTap.cpp Normal file
View File

@@ -0,0 +1,510 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include <algorithm>
#include <utility>
#include <dlfcn.h>
#include <sys/poll.h>
#include <stdint.h>
#include <utility>
#include <string>
#include <sys/resource.h>
#include <sys/syscall.h>
#include "SocketTap.hpp"
#include "ZeroTierSDK.h"
#include "RPC.h"
#include "picoTCP.hpp"
#include "Utils.hpp"
#include "OSUtils.hpp"
#include "Constants.hpp"
#include "Phy.hpp"
namespace ZeroTier {
// Ignore these
void SocketTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *local_address, const struct sockaddr *from,void *data,unsigned long len) {}
void SocketTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
void SocketTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
void SocketTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
void SocketTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
void SocketTap::phyOnTcpWritable(PhySocket *sock,void **uptr, bool stack_invoked) {}
int SocketTap::sendReturnValue(int fd, int retval, int _errno)
{
//DEBUG_INFO("fd=%d, retval=%d, errno=%d", fd, retval, _errno);
int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
char retmsg[sz];
memset(&retmsg, 0, sizeof(retmsg));
retmsg[0]=RPC_RETVAL;
memcpy(&retmsg[1], &retval, sizeof(retval));
memcpy(&retmsg[1]+sizeof(retval), &_errno, sizeof(_errno));
return write(fd, &retmsg, sz);
}
// Unpacks the buffer from an RPC command
void SocketTap::unloadRPC(void *data, pid_t &pid, pid_t &tid,
char (timestamp[RPC_TIMESTAMP_SZ]), char (CANARY[sizeof(uint64_t)]), char &cmd, void* &payload)
{
unsigned char *buf = (unsigned char*)data;
memcpy(&pid, &buf[IDX_PID], sizeof(pid_t));
memcpy(&tid, &buf[IDX_TID], sizeof(pid_t));
memcpy(timestamp, &buf[IDX_TIME], RPC_TIMESTAMP_SZ);
memcpy(&cmd, &buf[IDX_PAYLOAD], sizeof(char));
memcpy(CANARY, &buf[IDX_PAYLOAD+1], CANARY_SZ);
}
/*------------------------------------------------------------------------------
-------------------------------- Tap Service ----------------------------------
------------------------------------------------------------------------------*/
SocketTap::SocketTap(
const char *homePath,
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *friendlyName,
void (*handler)(void *,void*,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
void *arg) :
_homePath(homePath),
_mac(mac),
_mtu(mtu),
_nwid(nwid),
_handler(handler),
_arg(arg),
_phy(this,false,true),
_unixListenSocket((PhySocket *)0),
_enabled(true),
_run(true)
{
char sockPath[4096];
Utils::snprintf(sockPath,sizeof(sockPath),"%s%snc_%.16llx",homePath,ZT_PATH_SEPARATOR_S,_nwid,ZT_PATH_SEPARATOR_S,(unsigned long long)nwid);
_dev = sockPath; // in SDK mode, set device to be just the network ID
_unixListenSocket = _phy.unixListen(sockPath,(void *)this);
chmod(sockPath, 0777); // To make the RPC socket available to all users
if (!_unixListenSocket)
DEBUG_ERROR("unable to bind to: path=%s", sockPath);
else
DEBUG_INFO("tap initialized on: path=%s", sockPath);
picostack = new picoTCP();
pico_stack_init();
_thread = Thread::start(this);
}
SocketTap::~SocketTap()
{
_run = false;
_phy.whack();
_phy.whack(); // FIXME: Remove?
Thread::join(_thread);
_phy.close(_unixListenSocket,false);
}
void SocketTap::setEnabled(bool en)
{
_enabled = en;
}
bool SocketTap::enabled() const
{
return _enabled;
}
bool SocketTap::addIp(const InetAddress &ip)
{
// Initialize network stack's interface, assign addresses
picotap = this;
picostack->pico_init_interface(this, ip);
return true;
}
bool SocketTap::removeIp(const InetAddress &ip)
{
Mutex::Lock _l(_ips_m);
std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
if (i == _ips.end())
return false;
_ips.erase(i);
if (ip.isV4()) {
// TODO: De-register from network stacks
}
return true;
}
std::vector<InetAddress> SocketTap::ips() const
{
Mutex::Lock _l(_ips_m);
return _ips;
}
// Receive data from ZT tap service (virtual wire) and present it to network stack
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |--------------->| | RX
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |
// -----------------------------------------
void SocketTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
{
// DEBUG_EXTRA("RX packet: len=%d, etherType=%d", len, etherType);
// RX packet
picostack->pico_rx(this, from,to,etherType,data,len);
}
std::string SocketTap::deviceName() const
{
return _dev;
}
void SocketTap::setFriendlyName(const char *friendlyName) {
}
void SocketTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
{
std::vector<MulticastGroup> newGroups;
Mutex::Lock _l(_multicastGroups_m);
// TODO: get multicast subscriptions from network stack
std::vector<InetAddress> allIps(ips());
for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
std::sort(newGroups.begin(),newGroups.end());
std::unique(newGroups.begin(),newGroups.end());
for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
added.push_back(*m);
}
for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
removed.push_back(*m);
}
_multicastGroups.swap(newGroups);
}
void SocketTap::threadMain()
throw()
{
// Enter main thread loop for network stack
picostack->pico_loop(this);
}
Connection *SocketTap::getConnection(PhySocket *sock)
{
for(size_t i=0;i<_Connections.size();++i) {
if(_Connections[i]->sock == sock)
return _Connections[i];
}
return NULL;
}
Connection *SocketTap::getConnection(struct pico_socket *sock)
{
for(size_t i=0;i<_Connections.size();++i) {
if(_Connections[i]->picosock == sock)
return _Connections[i];
}
return NULL;
}
void SocketTap::closeConnection(PhySocket *sock)
{
Mutex::Lock _l(_close_m);
// Here we assume _tcpconns_m is already locked by caller
if(!sock) {
DEBUG_EXTRA("invalid PhySocket");
return;
}
picostack->pico_handleClose(sock);
Connection *conn = getConnection(sock);
if(!conn)
return;
for(size_t i=0;i<_Connections.size();++i) {
if(_Connections[i] == conn){
_Connections.erase(_Connections.begin() + i);
delete conn;
break;
}
}
if(!sock)
return;
close(_phy.getDescriptor(sock));
_phy.close(sock, false);
}
void SocketTap::phyOnUnixClose(PhySocket *sock,void **uptr) {
//Mutex::Lock _l(_tcpconns_m);
//closeConnection(sock);
}
// Receive data from ZT tap service and present it to network stack
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |--------------->| | RX
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |
// -----------------------------------------
void SocketTap::handleRead(PhySocket *sock,void **uptr,bool stack_invoked)
{
picostack->pico_handleRead(sock, uptr, stack_invoked);
}
void SocketTap::phyOnUnixWritable(PhySocket *sock,void **uptr,bool stack_invoked)
{
handleRead(sock,uptr,stack_invoked);
}
void SocketTap::phyOnUnixData(PhySocket *sock, void **uptr, void *data, ssize_t len)
{
//DEBUG_INFO("physock=%p, len=%d", sock, (int)len);
uint64_t CANARY_num;
pid_t pid, tid;
ssize_t wlen = len;
char tmpbuf[SDK_MTU];
char cmd, timestamp[20], CANARY[CANARY_SZ], padding[] = {PADDING};
void *payload;
unsigned char *buf = (unsigned char*)data;
std::pair<PhySocket*, void*> sockdata;
PhySocket *rpcSock;
bool foundJob = false, detected_rpc = false;
Connection *conn;
// RPC
char phrase[RPC_PHRASE_SZ];
memset(phrase, 0, RPC_PHRASE_SZ);
if(len == BUF_SZ) {
memcpy(phrase, buf, RPC_PHRASE_SZ);
if(strcmp(phrase, RPC_PHRASE) == 0)
detected_rpc = true;
}
if(detected_rpc) {
unloadRPC(data, pid, tid, timestamp, CANARY, cmd, payload);
memcpy(&CANARY_num, CANARY, CANARY_SZ);
// DEBUG_EXTRA(" RPC: physock=%p, (pid=%d, tid=%d, timestamp=%s, cmd=%d)", sock, pid, tid, timestamp, cmd);
if(cmd == RPC_SOCKET) {
// DEBUG_INFO("RPC_SOCKET, physock=%p", sock);
// Create new stack socket and associate it with this sock
struct socket_st socket_rpc;
memcpy(&socket_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct socket_st));
Connection * new_conn;
if((new_conn = handleSocket(sock, uptr, &socket_rpc))) {
new_conn->pid = pid; // Merely kept to look up application path/names later, not strictly necessary
}
} else {
memcpy(&tmpbuf,data,len);
jobmap[CANARY_num] = std::pair<PhySocket*, void*>(sock, tmpbuf);
}
write(_phy.getDescriptor(sock), "z", 1); // RPC ACK byte to maintain order
}
// STREAM
else {
int data_start = -1, data_end = -1, canary_pos = -1, padding_pos = -1;
// Look for padding
std::string padding_pattern(padding, padding+PADDING_SZ);
std::string buffer(buf, buf + len);
padding_pos = buffer.find(padding_pattern);
canary_pos = padding_pos-CANARY_SZ;
// Grab token, next we'll use it to look up an RPC job
if(canary_pos > -1) {
memcpy(&CANARY_num, buf+canary_pos, CANARY_SZ);
if(CANARY_num != 0) {
// Find job
sockdata = jobmap[CANARY_num];
if(!sockdata.first) {
return;
} else
foundJob = true;
}
}
conn = getConnection(sock);
if(!conn)
return;
if(padding_pos == -1) { // [DATA]
memcpy(&conn->txbuf[conn->txsz], buf, wlen);
} else { // Padding found, implies a canary is present
// [CANARY]
if(len == CANARY_SZ+PADDING_SZ && canary_pos == 0) {
wlen = 0; // Nothing to write
} else {
// [CANARY] + [DATA]
if(len > CANARY_SZ+PADDING_SZ && canary_pos == 0) {
wlen = len - CANARY_SZ+PADDING_SZ;
data_start = padding_pos+PADDING_SZ;
memcpy((&conn->txbuf)+conn->txsz, buf+data_start, wlen);
}
// [DATA] + [CANARY]
if(len > CANARY_SZ+PADDING_SZ && canary_pos > 0 && canary_pos == len - CANARY_SZ+PADDING_SZ) {
wlen = len - CANARY_SZ+PADDING_SZ;
data_start = 0;
memcpy((&conn->txbuf)+conn->txsz, buf+data_start, wlen);
}
// [DATA] + [CANARY] + [DATA]
if(len > CANARY_SZ+PADDING_SZ && canary_pos > 0 && len > (canary_pos + CANARY_SZ+PADDING_SZ)) {
wlen = len - CANARY_SZ+PADDING_SZ;
data_start = 0;
data_end = padding_pos-CANARY_SZ;
memcpy((&conn->txbuf)+conn->txsz, buf+data_start, (data_end-data_start)+1);
memcpy((&conn->txbuf)+conn->txsz, buf+(padding_pos+PADDING_SZ), len-(canary_pos+CANARY_SZ+PADDING_SZ));
}
}
}
// Write data from stream
if(wlen) {
conn->txsz += wlen;
handleWrite(conn);
}
}
// Process RPC if we have a corresponding jobmap entry
if(foundJob) {
rpcSock = sockdata.first;
buf = (unsigned char*)sockdata.second;
unloadRPC(buf, pid, tid, timestamp, CANARY, cmd, payload);
//DEBUG_ERROR(" RPC: physock=%p, (pid=%d, tid=%d, timestamp=%s, cmd=%d)", sock, pid, tid, timestamp, cmd);
switch(cmd) {
case RPC_BIND:
//DEBUG_INFO("RPC_BIND, physock=%p", sock);
struct bind_st bind_rpc;
memcpy(&bind_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct bind_st));
handleBind(sock, rpcSock, uptr, &bind_rpc);
break;
case RPC_LISTEN:
//DEBUG_INFO("RPC_LISTEN, physock=%p", sock);
struct listen_st listen_rpc;
memcpy(&listen_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct listen_st));
handleListen(sock, rpcSock, uptr, &listen_rpc);
break;
case RPC_GETSOCKNAME:
//DEBUG_INFO("RPC_GETSOCKNAME, physock=%p", sock);
struct getsockname_st getsockname_rpc;
memcpy(&getsockname_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct getsockname_st));
handleGetsockname(sock, rpcSock, uptr, &getsockname_rpc);
break;
case RPC_GETPEERNAME:
//DEBUG_INFO("RPC_GETPEERNAME, physock=%p", sock);
struct getsockname_st getpeername_rpc;
memcpy(&getpeername_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct getsockname_st));
handleGetpeername(sock, rpcSock, uptr, &getpeername_rpc);
break;
case RPC_CONNECT:
//DEBUG_INFO("RPC_CONNECT, physock=%p", sock);
struct connect_st connect_rpc;
memcpy(&connect_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct connect_st));
handleConnect(sock, rpcSock, conn, &connect_rpc);
jobmap.erase(CANARY_num);
return; // Keep open RPC, we'll use it once in nc_connected to send retval
default:
return;
break;
}
Mutex::Lock _l(_tcpconns_m);
closeConnection(sockdata.first); // close RPC after sending retval, no longer needed
jobmap.erase(CANARY_num);
}
}
/*------------------------------------------------------------------------------
----------------------------- RPC Handler functions ----------------------------
------------------------------------------------------------------------------*/
void SocketTap::handleGetsockname(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct getsockname_st *getsockname_rpc)
{
Mutex::Lock _l(_tcpconns_m);
Connection *conn = getConnection(sock);
if(conn->local_addr == NULL){
DEBUG_EXTRA("no address info available. is it bound?");
struct sockaddr_storage storage;
memset(&storage, 0, sizeof(struct sockaddr_storage));
write(_phy.getDescriptor(rpcSock), NULL, sizeof(struct sockaddr_storage));
return;
}
write(_phy.getDescriptor(rpcSock), conn->local_addr, sizeof(struct sockaddr_storage));
}
void SocketTap::handleGetpeername(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct getsockname_st *getsockname_rpc)
{
Mutex::Lock _l(_tcpconns_m);
Connection *conn = getConnection(sock);
if(conn->peer_addr == NULL){
DEBUG_EXTRA("no peer address info available. is it connected?");
struct sockaddr_storage storage;
memset(&storage, 0, sizeof(struct sockaddr_storage));
write(_phy.getDescriptor(rpcSock), NULL, sizeof(struct sockaddr_storage));
return;
}
write(_phy.getDescriptor(rpcSock), conn->peer_addr, sizeof(struct sockaddr_storage));
}
Connection * SocketTap::handleSocket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
{
return picostack->pico_handleSocket(sock, uptr, socket_rpc);
}
// Connect a stack's PCB/socket/Connection object to a remote host
void SocketTap::handleConnect(PhySocket *sock, PhySocket *rpcSock, Connection *conn, struct connect_st* connect_rpc)
{
Mutex::Lock _l(_tcpconns_m);
picostack->pico_handleConnect(sock, rpcSock, conn, connect_rpc);
}
void SocketTap::handleBind(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct bind_st *bind_rpc)
{
Mutex::Lock _l(_tcpconns_m);
if(!_ips.size()) {
// We haven't been given an address yet. Binding at this stage is premature
DEBUG_ERROR("cannot bind yet. ZT address hasn't been provided");
sendReturnValue(_phy.getDescriptor(rpcSock), -1, ENOMEM);
return;
}
picostack->pico_handleBind(sock,rpcSock,uptr,bind_rpc);
}
void SocketTap::handleListen(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct listen_st *listen_rpc)
{
Mutex::Lock _l(_tcpconns_m);
picostack->pico_handleListen(sock, rpcSock, uptr, listen_rpc);
}
// Write to the network stack (and thus out onto the network)
void SocketTap::handleWrite(Connection *conn)
{
picostack->pico_handleWrite(conn);
}
} // namespace ZeroTier

244
src/SocketTap.hpp Normal file
View File

@@ -0,0 +1,244 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_SocketTap_HPP
#define ZT_SocketTap_HPP
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <utility>
#include <stdexcept>
#include <stdint.h>
#include "Constants.hpp"
#include "MulticastGroup.hpp"
#include "Mutex.hpp"
#include "InetAddress.hpp"
#include "Thread.hpp"
#include "Phy.hpp"
#include "ZeroTierSDK.h"
#include "RPC.h"
#include "picoTCP.hpp"
#include "pico_protocol.h"
#include "pico_stack.h"
#include "pico_ipv4.h"
#include "pico_icmp4.h"
#include "pico_dev_tap.h"
#include "pico_protocol.h"
#include "pico_socket.h"
#include "pico_device.h"
#include "pico_ipv6.h"
// ZT RPC structs
struct socket_st;
struct listen_st;
struct bind_st;
struct connect_st;
struct getsockname_st;
struct accept_st;
struct pico_socket;
namespace ZeroTier {
class SocketTap;
extern SocketTap *picotap;
/*
* TCP connection
*/
struct Connection
{
bool listening, probation, disabled;
int pid, txsz, rxsz, type;
PhySocket *rpcSock, *sock;
struct tcp_pcb *TCP_pcb;
struct udp_pcb *UDP_pcb;
struct sockaddr_storage *local_addr; // Address we've bound to locally
struct sockaddr_storage *peer_addr; // Address of connection call to remote host
unsigned short port;
unsigned char txbuf[DEFAULT_TCP_TX_BUF_SZ];
unsigned char rxbuf[DEFAULT_TCP_RX_BUF_SZ];
// pico
struct pico_socket *picosock;
};
/*
* A helper for passing a reference to _phy to LWIP callbacks as a "state"
*/
struct Larg
{
SocketTap *tap;
Connection *conn;
Larg(SocketTap *_tap, Connection *conn) : tap(_tap), conn(conn) {}
};
/*
* Network Containers instance -- emulates an Ethernet tap device as far as OneService knows
*/
class SocketTap
{
friend class Phy<SocketTap *>;
public:
SocketTap(
const char *homePath,
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *friendlyName,
void (*handler)(void *, void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
void *arg);
~SocketTap();
void setEnabled(bool en);
bool enabled() const;
bool addIp(const InetAddress &ip);
bool removeIp(const InetAddress &ip);
std::vector<InetAddress> ips() const;
std::vector<InetAddress> _ips;
void put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len);
std::string deviceName() const;
void setFriendlyName(const char *friendlyName);
void scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed);
int sendReturnValue(int fd, int retval, int _errno);
void unloadRPC(void *data, pid_t &pid, pid_t &tid, char (timestamp[RPC_TIMESTAMP_SZ]), char (CANARY[sizeof(uint64_t)]), char &cmd, void* &payload);
void threadMain()
throw();
std::string _homePath;
MAC _mac;
unsigned int _mtu;
uint64_t _nwid;
void (*_handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int);
void *_arg;
Phy<SocketTap *> _phy;
PhySocket *_unixListenSocket;
volatile bool _enabled;
volatile bool _run;
// picoTCP
unsigned char pico_frame_rxbuf[MAX_PICO_FRAME_RX_BUF_SZ];
int pico_frame_rxbuf_tot;
Mutex _pico_frame_rxbuf_m;
void handleBind(PhySocket *sock, PhySocket *rpcsock, void **uptr, struct bind_st *bind_rpc);
void handleListen(PhySocket *sock, PhySocket *rpcsock, void **uptr, struct listen_st *listen_rpc);
Connection * handleSocket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc);
void handleConnect(PhySocket *sock, PhySocket *rpcsock, Connection *conn, struct connect_st* connect_rpc);
// void handleIsConnected();
/*
* Return the address that the socket is bound to
*/
void handleGetsockname(PhySocket *sock, PhySocket *rpcsock, void **uptr, struct getsockname_st *getsockname_rpc);
/*
* Return the address of the peer connected to this socket
*/
void handleGetpeername(PhySocket *sock, PhySocket *rpcsock, void **uptr, struct getsockname_st *getsockname_rpc);
/*
* Writes data from the application's socket to the LWIP connection
*/
void handleWrite(Connection *conn);
// Unused -- no UDP or TCP from this thread/Phy<>
void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *local_address, const struct sockaddr *from,void *data,unsigned long len);
void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success);
void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from);
void phyOnTcpClose(PhySocket *sock,void **uptr);
void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len);
void phyOnTcpWritable(PhySocket *sock,void **uptr, bool stack_invoked);
void handleRead(PhySocket *sock,void **uptr,bool stack_invoked);
/*
* Signals us to close the TcpConnection associated with this PhySocket
*/
void phyOnUnixClose(PhySocket *sock,void **uptr);
/*
* Notifies us that there is data to be read from an application's socket
*/
void phyOnUnixData(PhySocket *sock,void **uptr,void *data,ssize_t len);
/*
* Notifies us that we can write to an application's socket
*/
void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked);
/*
* Returns a pointer to a TcpConnection associated with a given PhySocket
*/
Connection *getConnection(PhySocket *sock);
/*
* Returns a pointer to a TcpConnection associated with a given pico_socket
*/
Connection *getConnection(struct pico_socket *socket);
/*
* Closes a TcpConnection, associated LWIP PCB strcuture,
* PhySocket, and underlying file descriptor
*/
void closeConnection(PhySocket *sock);
picoTCP *picostack;
std::vector<Connection*> _Connections;
std::map<uint64_t, std::pair<PhySocket*, void*> > jobmap;
pid_t rpcCounter;
Thread _thread;
std::string _dev; // path to Unix domain socket
std::vector<MulticastGroup> _multicastGroups;
Mutex _multicastGroups_m;
Mutex _ips_m, _tcpconns_m, _rx_buf_m, _close_m;
};
} // namespace ZeroTier
#endif

809
src/picoTCP.cpp Normal file
View File

@@ -0,0 +1,809 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include "pico_eth.h"
#include "pico_stack.h"
#include "pico_ipv4.h"
#include "pico_icmp4.h"
#include "pico_dev_tap.h"
#include "pico_protocol.h"
#include "pico_socket.h"
#include "pico_device.h"
#include "pico_ipv6.h"
#include "ZeroTierSDK.h"
#include "SocketTap.hpp"
#include "picoTCP.hpp"
#include "Utils.hpp"
#include "OSUtils.hpp"
#include "Mutex.hpp"
#include "Constants.hpp"
#include "Phy.hpp"
// stack locks
ZeroTier::Mutex _lock;
ZeroTier::Mutex _lock_mem;
struct pico_socket;
struct pico_device;
extern "C" int pico_stack_init(void);
extern "C" void pico_stack_tick(void);
int pico_ipv4_to_string(PICO_IPV4_TO_STRING_SIG);
extern "C" int pico_ipv4_link_add(PICO_IPV4_LINK_ADD_SIG);
extern "C" int pico_device_init(PICO_DEVICE_INIT_SIG);
int pico_stack_recv(PICO_STACK_RECV_SIG);
int pico_icmp4_ping(PICO_ICMP4_PING_SIG);
extern "C" int pico_string_to_ipv4(PICO_STRING_TO_IPV4_SIG);
extern "C" int pico_string_to_ipv6(PICO_STRING_TO_IPV6_SIG);
int pico_socket_setoption(PICO_SOCKET_SETOPTION_SIG);
uint32_t pico_timer_add(PICO_TIMER_ADD_SIG);
int pico_socket_send(PICO_SOCKET_SEND_SIG);
int pico_socket_sendto(PICO_SOCKET_SENDTO_SIG);
int pico_socket_recv(PICO_SOCKET_RECV_SIG);
extern "C" int pico_socket_recvfrom(PICO_SOCKET_RECVFROM_SIG);
extern "C" struct pico_socket * pico_socket_open(PICO_SOCKET_OPEN_SIG);
int pico_socket_bind(PICO_SOCKET_BIND_SIG);
int pico_socket_connect(PICO_SOCKET_CONNECT_SIG);
extern "C" int pico_socket_listen(PICO_SOCKET_LISTEN_SIG);
int pico_socket_read(PICO_SOCKET_READ_SIG);
extern "C" int pico_socket_write(PICO_SOCKET_WRITE_SIG);
extern "C" int pico_socket_close(PICO_SOCKET_CLOSE_SIG);
int pico_socket_shutdown(PICO_SOCKET_SHUTDOWN_SIG);
struct pico_socket * pico_socket_accept(PICO_SOCKET_ACCEPT_SIG);
extern "C" struct pico_ipv6_link * pico_ipv6_link_add(PICO_IPV6_LINK_ADD_SIG);
namespace ZeroTier {
// Reference to the tap interface
// This is needed due to the fact that there's a lot going on in the tap interface
// that needs to be updated on each of the network stack's callbacks and not every
// network stack provides a mechanism for storing a reference to the tap.
//
// In future releases this will be replaced with a new structure of static pointers that
// will make it easier to maintain multiple active tap interfaces
struct pico_device picodev;
SocketTap * picotap;
int pico_eth_send(struct pico_device *dev, void *buf, int len);
int pico_eth_poll(struct pico_device *dev, int loop_score);
// Initialize network stack's interfaces and assign addresses
void picoTCP::pico_init_interface(SocketTap *tap, const InetAddress &ip)
{
if (std::find(tap->_ips.begin(),tap->_ips.end(),ip) == tap->_ips.end()) {
tap->_ips.push_back(ip);
std::sort(tap->_ips.begin(),tap->_ips.end());
#if defined(SDK_IPV4)
if(ip.isV4())
{
struct pico_ip4 ipaddr, netmask;
ipaddr.addr = *((uint32_t *)ip.rawIpData());
netmask.addr = *((uint32_t *)ip.netmask().rawIpData());
uint8_t mac[PICO_SIZE_ETH];
tap->_mac.copyTo(mac, PICO_SIZE_ETH);
DEBUG_ATTN("mac = %s", tap->_mac.toString().c_str());
picodev.send = pico_eth_send; // tx
picodev.poll = pico_eth_poll; // rx
picodev.mtu = tap->_mtu;
if( 0 != pico_device_init(&(picodev), "p0", mac)) {
DEBUG_ERROR("device init failed");
return;
}
pico_ipv4_link_add(&(picodev), ipaddr, netmask);
// DEBUG_INFO("device initialized as ipv4_addr = %s", ipv4_str);
// pico_icmp4_ping("10.8.8.1", 20, 1000, 10000, 64, cb_ping);
}
#elif defined(SDK_IPV6)
if(ip.isV6())
{
struct pico_ip6 ipaddr, netmask;
char ipv6_str[INET6_ADDRSTRLEN], nm_str[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, ip.rawIpData(), ipv6_str, INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, ip.netmask().rawIpData(), nm_str, INET6_ADDRSTRLEN);
pico_string_to_ipv6(ipv6_str, ipaddr.addr);
pico_string_to_ipv6(nm_str, netmask.addr);
pico_ipv6_link_add(&(picodev), ipaddr, netmask);
picodev.send = pico_eth_send; // tx
picodev.poll = pico_eth_poll; // rx
uint8_t mac[PICO_SIZE_ETH];
tap->_mac.copyTo(mac, PICO_SIZE_ETH);
DEBUG_ATTN("mac = %s", tap->_mac.toString().c_str());
if( 0 != pico_device_init(&(picodev), "p0", mac)) {
DEBUG_ERROR("device init failed");
return;
}
DEBUG_ATTN("device initialized as ipv6_addr = %s", ipv6_str);
}
#endif
}
}
// Main stack loop
void picoTCP::pico_loop(SocketTap *tap)
{
while(tap->_run)
{
tap->_phy.poll(ZT_PHY_POLL_INTERVAL); // in ms
pico_stack_tick();
}
}
// RX packets from [ZT->STACK] onto RXBUF
// Also notify the tap service that data can be read:
// [RXBUF -> (ZTSOCK->APP)]
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |<-----------------| | RX
// -----------------------------------------
// After this step, buffer will be emptied periodically by pico_handleRead()
void picoTCP::pico_cb_tcp_read(ZeroTier::SocketTap *tap, struct pico_socket *s)
{
Connection *conn = tap->getConnection(s);
if(conn) {
int r;
uint16_t port = 0;
union {
struct pico_ip4 ip4;
struct pico_ip6 ip6;
} peer;
do {
int avail = DEFAULT_TCP_RX_BUF_SZ - conn->rxsz;
if(avail) {
r = pico_socket_recvfrom(s, conn->rxbuf + (conn->rxsz), SDK_MTU, (void *)&peer.ip4.addr, &port);
// DEBUG_ATTN("received packet (%d byte) from %08X:%u", r, long_be2(peer.ip4.addr), short_be(port));
tap->_phy.setNotifyWritable(conn->sock, true);
if (r > 0)
conn->rxsz += r;
}
else
DEBUG_ERROR("not enough space left on I/O RX buffer for pico_socket(%p)", s);
}
while(r > 0);
return;
}
DEBUG_ERROR("invalid connection");
}
// RX packets from the stack onto internal buffer
// Also notifies the tap service that data can be read
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |<-----------------| | RX
// -----------------------------------------
// After this step, buffer will be emptied periodically by pico_handleRead()
// Read payload is encapsulated as such:
//
// [addr|payload_len|payload]
//
void picoTCP::pico_cb_udp_read(SocketTap *tap, struct pico_socket *s)
{
Connection *conn = tap->getConnection(s);
if(conn) {
uint16_t port = 0;
union {
struct pico_ip4 ip4;
struct pico_ip6 ip6;
} peer;
char tmpbuf[SDK_MTU];
unsigned char *addr_pos, *sz_pos, *payload_pos;
struct sockaddr_in addr_in;
addr_in.sin_addr.s_addr = peer.ip4.addr;
addr_in.sin_port = port;
// RX
int r = pico_socket_recvfrom(s, tmpbuf, SDK_MTU, (void *)&peer.ip4.addr, &port);
//DEBUG_FLOW(" [ RXBUF <- STACK] Receiving (%d) from stack, copying to receving buffer", r);
// Mutex::Lock _l2(tap->_rx_buf_m);
// struct sockaddr_in6 addr_in6;
// addr_in6.sin6_addr.s6_addr;
// addr_in6.sin6_port = Utils::ntoh(s->remote_port);
// DEBUG_ATTN("remote_port=%d, local_port=%d", s->remote_port, Utils::ntoh(s->local_port));
tap->_rx_buf_m.lock();
if(conn->rxsz == DEFAULT_UDP_RX_BUF_SZ) { // if UDP buffer full
//DEBUG_FLOW(" [ RXBUF <- STACK] UDP RX buffer full. Discarding oldest payload segment");
memmove(conn->rxbuf, conn->rxbuf + SDK_MTU, DEFAULT_UDP_RX_BUF_SZ - SDK_MTU);
addr_pos = conn->rxbuf + (DEFAULT_UDP_RX_BUF_SZ - SDK_MTU); // TODO:
sz_pos = addr_pos + sizeof(struct sockaddr_storage);
conn->rxsz -= SDK_MTU;
}
else {
addr_pos = conn->rxbuf + conn->rxsz; // where we'll prepend the size of the address
sz_pos = addr_pos + sizeof(struct sockaddr_storage);
}
payload_pos = addr_pos + sizeof(struct sockaddr_storage) + sizeof(r);
memcpy(addr_pos, &addr_in, sizeof(struct sockaddr_storage));
memcpy(payload_pos, tmpbuf, r); // write payload to app's socket
// Adjust buffer size
if(r) {
conn->rxsz += SDK_MTU;
memcpy(sz_pos, &r, sizeof(r));
}
if (r < 0) {
DEBUG_ERROR("unable to read from picosock=%p", s);
}
tap->_rx_buf_m.unlock();
// TODO: Revisit logic
if(r)
tap->phyOnUnixWritable(conn->sock, NULL, true);
//DEBUG_EXTRA(" Copied onto rxbuf (%d) from stack socket", r);
return;
}
}
// TX packets from internal buffer to network
void picoTCP::pico_cb_tcp_write(SocketTap *tap, struct pico_socket *s)
{
Connection *conn = tap->getConnection(s);
if(!conn)
DEBUG_ERROR("invalid connection");
if(!conn->txsz)
return;
// Only called from a locked context, no need to lock anything
if(conn->txsz > 0) {
int r, max_write_len = conn->txsz < SDK_MTU ? conn->txsz : SDK_MTU;
if((r = pico_socket_write(s, &conn->txbuf, max_write_len)) < 0) {
DEBUG_ERROR("unable to write to picosock=%p", s);
return;
}
int sz = (conn->txsz)-r;
if(sz)
memmove(&conn->txbuf, (conn->txbuf+r), sz);
conn->txsz -= r;
#if DEBUG_LEVEL >= MSG_TRANSFER
int max = conn->type == SOCK_STREAM ? DEFAULT_TCP_TX_BUF_SZ : DEFAULT_UDP_TX_BUF_SZ;
DEBUG_TRANS("[TCP TX] ---> :: {TX: %.3f%%, RX: %.3f%%, physock=%p} :: %d bytes",
(float)conn->txsz / (float)max, (float)conn->rxsz / max, conn->sock, r);
#endif
return;
}
}
// Main callback for TCP connections
void picoTCP::pico_cb_socket_activity(uint16_t ev, struct pico_socket *s)
{
int err;
Mutex::Lock _l(picotap->_tcpconns_m);
Connection *conn = picotap->getConnection(s);
if(!conn) {
DEBUG_ERROR("invalid connection");
}
// Accept connection (analogous to lwip_nc_accept)
if (ev & PICO_SOCK_EV_CONN) {
DEBUG_INFO("connection established with server, picosock=%p",(conn->picosock));
uint32_t peer;
uint16_t port;
struct pico_socket *client = pico_socket_accept(s, &peer, &port);
if(!client) {
DEBUG_EXTRA("unable to accept conn. (event might not be incoming, not necessarily an error), picosock=%p", (conn->picosock));
}
ZT_PHY_SOCKFD_TYPE fds[2];
if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
if(errno < 0) {
// FIXME: Return a value to the client
//tap->sendReturnValue(conn, -1, errno);
DEBUG_ERROR("unable to create socketpair");
return;
}
}
Connection *newTcpConn = new Connection();
picotap->_Connections.push_back(newTcpConn);
newTcpConn->type = SOCK_STREAM;
newTcpConn->sock = picotap->_phy.wrapSocket(fds[0], newTcpConn);
newTcpConn->picosock = client;
int fd = picotap->_phy.getDescriptor(conn->sock);
if(sock_fd_write(fd, fds[1]) < 0) {
DEBUG_ERROR("error sending new fd to client application");
}
DEBUG_EXTRA("conn=%p, physock=%p, listen_picosock=%p, new_picosock=%p, fd=%d", newTcpConn, newTcpConn->sock, s, client, fds[1]);
}
if (ev & PICO_SOCK_EV_FIN) {
DEBUG_INFO("socket closed. exit normally. picosock=%p\n\n", s);
//pico_timer_add(2000, compare_results, NULL);
}
if (ev & PICO_SOCK_EV_ERR) {
DEBUG_INFO("socket error received" /*, strerror(pico_err)*/);
}
if (ev & PICO_SOCK_EV_CLOSE) {
err = pico_socket_close(s);
DEBUG_INFO("socket closure = %d, picosock=%p", err, s);
if(err==0) {
picotap->closeConnection(conn->sock);
}
return;
}
// Read from picoTCP socket
if (ev & PICO_SOCK_EV_RD) {
if(conn->type==SOCK_STREAM)
pico_cb_tcp_read(picotap, s);
if(conn->type==SOCK_DGRAM)
pico_cb_udp_read(picotap, s);
}
// Write to picoTCP socket
if (ev & PICO_SOCK_EV_WR) {
pico_cb_tcp_write(picotap, s);
}
}
// Called when an incoming ping is received
/*
static void pico_cb_ping(struct pico_icmp4_stats *s)
{
DEBUG_INFO();
char host[30];
pico_ipv4_to_string(host, s->dst.addr);
if (s->err == 0) {
printf("%lu bytes from %s: icmp_req=%lu ttl=%lu time=%lu ms\n", s->size,
host, s->seq, s->ttl, (long unsigned int)s->time);
} else {
printf("PING %lu to %s: Error %d\n", s->seq, host, s->err);
}
}
*/
// Called from the stack, sends data to the tap device (in our case, the ZeroTier service)
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |<-------------------------| | TX
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |
// -----------------------------------------
int pico_eth_send(struct pico_device *dev, void *buf, int len)
{
struct pico_eth_hdr *ethhdr;
ethhdr = (struct pico_eth_hdr *)buf;
MAC src_mac;
MAC dest_mac;
src_mac.setTo(ethhdr->saddr, 6);
dest_mac.setTo(ethhdr->daddr, 6);
picotap->_handler(picotap->_arg,NULL,picotap->_nwid,src_mac,dest_mac,
Utils::ntoh((uint16_t)ethhdr->proto),0, ((char*)buf) + sizeof(struct pico_eth_hdr),len - sizeof(struct pico_eth_hdr));
return len;
}
// Receives data from the tap device and encapsulates it into a ZeroTier ethernet frame and places it in a locked memory buffer
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |--------------->| | RX
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |
// -----------------------------------------
// It will then periodically be transfered into the network stack via pico_eth_poll()
void picoTCP::pico_rx(SocketTap *tap, const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
{
// Since picoTCP only allows the reception of frames from within the polling function, we
// must enqueue each frame into a memory structure shared by both threads. This structure will
Mutex::Lock _l(tap->_pico_frame_rxbuf_m);
// assemble new eth header
struct pico_eth_hdr ethhdr;
from.copyTo(ethhdr.saddr, 6);
to.copyTo(ethhdr.daddr, 6);
ethhdr.proto = Utils::hton((uint16_t)etherType);
int newlen = len + sizeof(int) + sizeof(struct pico_eth_hdr);
int mylen;
while(newlen > (MAX_PICO_FRAME_RX_BUF_SZ-tap->pico_frame_rxbuf_tot) && ethhdr.proto == 56710)
{
mylen = 0;
//DEBUG_FLOW(" [ ZTWIRE -> FBUF ] not enough space left on RX frame buffer, dropping oldest packet in buffer");
/*
memcpy(&mylen, picotap->pico_frame_rxbuf, sizeof(len));
memmove(tap->pico_frame_rxbuf, tap->pico_frame_rxbuf + mylen, MAX_PICO_FRAME_RX_BUF_SZ-mylen); // shift buffer
picotap->pico_frame_rxbuf_tot-=mylen;
*/
memset(tap->pico_frame_rxbuf,0,MAX_PICO_FRAME_RX_BUF_SZ);
picotap->pico_frame_rxbuf_tot=0;
}
memcpy(tap->pico_frame_rxbuf + tap->pico_frame_rxbuf_tot, &newlen, sizeof(newlen)); // size of frame + meta
memcpy(tap->pico_frame_rxbuf + tap->pico_frame_rxbuf_tot + sizeof(newlen), &ethhdr, sizeof(ethhdr)); // new eth header
memcpy(tap->pico_frame_rxbuf + tap->pico_frame_rxbuf_tot + sizeof(newlen) + sizeof(ethhdr), data, len); // frame data
tap->pico_frame_rxbuf_tot += newlen;
DEBUG_FLOW(" [ ZTWIRE -> FBUF ] Move FRAME(sz=%d) into FBUF(sz=%d), data_len=%d", newlen, picotap->pico_frame_rxbuf_tot, len);
}
// Called periodically by the stack, this removes data from the locked memory buffer (FBUF) and feeds it into the stack.
// A maximum of 'loop_score' frames can be processed in each call
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |----------------->| | RX
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |
// -----------------------------------------
int pico_eth_poll(struct pico_device *dev, int loop_score)
{
// OPTIMIZATION: The copy logic and/or buffer structure should be reworked for better performance after the BETA
// SocketTap *tap = (SocketTap*)netif->state;
Mutex::Lock _l(picotap->_pico_frame_rxbuf_m);
unsigned char frame[SDK_MTU];
int len;
while (picotap->pico_frame_rxbuf_tot > 0 && loop_score > 0) {
//DEBUG_FLOW(" [ FBUF -> STACK] Frame buffer SZ=%d", picotap->pico_frame_rxbuf_tot);
memset(frame, 0, sizeof(frame));
len = 0;
memcpy(&len, picotap->pico_frame_rxbuf, sizeof(len)); // get frame len
if(len >= 0) {
//DEBUG_FLOW(" [ FBUF -> STACK] Moving FRAME of size (%d) from FBUF(sz=%d) into stack",len, picotap->pico_frame_rxbuf_tot-len);
memcpy(frame, picotap->pico_frame_rxbuf + sizeof(len), len-(sizeof(len)) ); // get frame data
memmove(picotap->pico_frame_rxbuf, picotap->pico_frame_rxbuf + len, MAX_PICO_FRAME_RX_BUF_SZ-len); // shift buffer
pico_stack_recv(dev, (uint8_t*)frame, (len-sizeof(len)));
picotap->pico_frame_rxbuf_tot-=len;
}
else {
DEBUG_ERROR("Skipping frame of size (%d)",len);
exit(0);
}
loop_score--;
}
return loop_score;
}
// Creates a new pico_socket and Connection object to represent a new connection to be.
Connection *picoTCP::pico_handleSocket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
{
struct pico_socket * psock;
int protocol, protocol_version;
#if defined(SDK_IPV4)
protocol_version = PICO_PROTO_IPV4;
#elif defined(SDK_IPV6)
protocol_version = PICO_PROTO_IPV6;
#endif
if(socket_rpc->socket_type == SOCK_DGRAM) {
protocol = PICO_PROTO_UDP;
psock = pico_socket_open(protocol_version, protocol, &pico_cb_socket_activity);
}
if(socket_rpc->socket_type == SOCK_STREAM) {
protocol = PICO_PROTO_TCP;
psock = pico_socket_open(protocol_version, protocol, &pico_cb_socket_activity);
}
if(psock) {
DEBUG_ATTN("physock=%p, picosock=%p", sock, psock);
Connection * newConn = new Connection();
*uptr = newConn;
newConn->type = socket_rpc->socket_type;
newConn->sock = sock;
/*
int res = 0;
int sendbuff = UNIX_SOCK_BUF_SIZE;
socklen_t optlen = sizeof(sendbuff);
res = setsockopt(picotap->_phy.getDescriptor(sock), SOL_SOCKET, SO_RCVBUF, &sendbuff, sizeof(sendbuff));
if(res == -1)
//DEBUG_ERROR("Error while setting RX buffer limits");
res = setsockopt(picotap->_phy.getDescriptor(sock), SOL_SOCKET, SO_SNDBUF, &sendbuff, sizeof(sendbuff));
if(res == -1)
//DEBUG_ERROR("Error while setting TX buffer limits");
// Get buffer size
// optlen = sizeof(sendbuff);
// res = getsockopt(picotap->_phy.getDescriptor(sock), SOL_SOCKET, SO_SNDBUF, &sendbuff, &optlen);
// DEBUG_INFO("buflen=%d", sendbuff);
*/
newConn->local_addr = NULL;
newConn->picosock = psock;
picotap->_Connections.push_back(newConn);
memset(newConn->rxbuf, 0, DEFAULT_UDP_RX_BUF_SZ);
return newConn;
}
else
DEBUG_ERROR("failed to create pico_socket");
return NULL;
}
// Writes data from the I/O buffer to the network stack
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |----------------->| | TX
// -----------------------------------------
void picoTCP::pico_handleWrite(Connection *conn)
{
if(!conn || !conn->picosock) {
DEBUG_ERROR(" invalid connection");
return;
}
int max, r, max_write_len = conn->txsz < SDK_MTU ? conn->txsz : SDK_MTU;
if((r = pico_socket_write(conn->picosock, &conn->txbuf, max_write_len)) < 0) {
DEBUG_ERROR("unable to write to picosock=%p, r=%d", (conn->picosock), r);
return;
}
// TODO: Errors
/*
if(pico_err == PICO_ERR_EINVAL)
DEBUG_ERROR("PICO_ERR_EINVAL - invalid argument");
if(pico_err == PICO_ERR_EIO)
DEBUG_ERROR("PICO_ERR_EIO - input/output error");
if(pico_err == PICO_ERR_ENOTCONN)
DEBUG_ERROR("PICO_ERR_ENOTCONN - the socket is not connected");
if(pico_err == PICO_ERR_ESHUTDOWN)
DEBUG_ERROR("PICO_ERR_ESHUTDOWN - cannot send after transport endpoint shutdown");
if(pico_err == PICO_ERR_EADDRNOTAVAIL)
DEBUG_ERROR("PICO_ERR_EADDRNOTAVAIL - address not available");
if(pico_err == PICO_ERR_EHOSTUNREACH)
DEBUG_ERROR("PICO_ERR_EHOSTUNREACH - host is unreachable");
if(pico_err == PICO_ERR_ENOMEM)
DEBUG_ERROR("PICO_ERR_ENOMEM - not enough space");
if(pico_err == PICO_ERR_EAGAIN)
DEBUG_ERROR("PICO_ERR_EAGAIN - resource temporarily unavailable");
*/
// adjust buffer
int sz = (conn->txsz)-r;
if(sz)
memmove(&conn->txbuf, (conn->txbuf+r), sz);
conn->txsz -= r;
if(conn->type == SOCK_STREAM) {
max = DEFAULT_TCP_TX_BUF_SZ;
DEBUG_TRANS("[TCP TX] ---> :: {TX: %.3f%%, RX: %.3f%%, physock=%p} :: %d bytes",
(float)conn->txsz / (float)max, (float)conn->rxsz / max, conn->sock, r);
}
if(conn->type == SOCK_DGRAM) {
max = DEFAULT_UDP_TX_BUF_SZ;
DEBUG_TRANS("[UDP TX] ---> :: {TX: %.3f%%, RX: %.3f%%, physock=%p} :: %d bytes",
(float)conn->txsz / (float)max, (float)conn->rxsz / max, conn->sock, r);
}
}
// Instructs the stack to connect to a remote host
void picoTCP::pico_handleConnect(PhySocket *sock, PhySocket *rpcSock, Connection *conn, struct connect_st* connect_rpc)
{
if(conn->picosock) {
struct sockaddr_in *addr = (struct sockaddr_in *) &connect_rpc->addr;
int ret;
// TODO: Rewrite this
#if defined(SDK_IPV4)
struct pico_ip4 zaddr;
struct sockaddr_in *in4 = (struct sockaddr_in*)&connect_rpc->addr;
char ipv4_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(in4->sin_addr), ipv4_str, INET_ADDRSTRLEN);
pico_string_to_ipv4(ipv4_str, &(zaddr.addr));
//DEBUG_ATTN("addr=%s:%d", ipv4_str, Utils::ntoh(addr->sin_port));
ret = pico_socket_connect(conn->picosock, &zaddr, addr->sin_port);
#elif defined(SDK_IPV6) // "fd56:5799:d8f6:1238:8c99:9322:30ce:418a"
struct pico_ip6 zaddr;
struct sockaddr_in6 *in6 = (struct sockaddr_in6*)&connect_rpc->addr;
char ipv6_str[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(in6->sin6_addr), ipv6_str, INET6_ADDRSTRLEN);
pico_string_to_ipv6(ipv6_str, zaddr.addr);
//DEBUG_ATTN("addr=%s:%d", ipv6_str, Utils::ntoh(addr->sin_port));
ret = pico_socket_connect(conn->picosock, &zaddr, addr->sin_port);
#endif
memcpy(&(conn->peer_addr), &connect_rpc->addr, sizeof(struct sockaddr_storage));
if(ret == PICO_ERR_EPROTONOSUPPORT)
DEBUG_ERROR("PICO_ERR_EPROTONOSUPPORT");
if(ret == PICO_ERR_EINVAL)
DEBUG_ERROR("PICO_ERR_EINVAL");
if(ret == PICO_ERR_EHOSTUNREACH)
DEBUG_ERROR("PICO_ERR_EHOSTUNREACH");
picotap->sendReturnValue(picotap->_phy.getDescriptor(rpcSock), 0, ERR_OK);
}
}
// Instructs the stack to bind to a given address
void picoTCP::pico_handleBind(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct bind_st *bind_rpc)
{
Connection *conn = picotap->getConnection(sock);
if(!sock) {
DEBUG_ERROR("invalid connection");
return;
}
struct sockaddr_in *addr = (struct sockaddr_in *) &bind_rpc->addr;
int ret;
// TODO: Rewrite this
#if defined(SDK_IPV4)
struct pico_ip4 zaddr;
struct sockaddr_in *in4 = (struct sockaddr_in*)&bind_rpc->addr;
char ipv4_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(in4->sin_addr), ipv4_str, INET_ADDRSTRLEN);
pico_string_to_ipv4(ipv4_str, &(zaddr.addr));
DEBUG_ATTN("addr=%s:%d, physock=%p, picosock=%p", ipv4_str, Utils::ntoh(addr->sin_port), sock, (conn->picosock));
ret = pico_socket_bind(conn->picosock, &zaddr, (uint16_t*)&(addr->sin_port));
#elif defined(SDK_IPV6)
struct pico_ip6 zaddr;
struct sockaddr_in6 *in6 = (struct sockaddr_in6*)&bind_rpc->addr;
char ipv6_str[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(in6->sin6_addr), ipv6_str, INET6_ADDRSTRLEN);
pico_string_to_ipv6(ipv6_str, zaddr.addr);
DEBUG_ATTN("addr=%s:%d, physock=%p, picosock=%p", ipv6_str, Utils::ntoh(addr->sin_port), sock, (conn->picosock));
ret = pico_socket_bind(conn->picosock, &zaddr, (uint16_t*)&(addr->sin_port));
#endif
if(ret < 0) {
DEBUG_ERROR("unable to bind pico_socket(%p), err=%d", (conn->picosock), ret);
if(ret == PICO_ERR_EINVAL) {
DEBUG_ERROR("PICO_ERR_EINVAL - invalid argument");
picotap->sendReturnValue(picotap->_phy.getDescriptor(rpcSock), -1, EINVAL);
}
if(ret == PICO_ERR_ENOMEM) {
DEBUG_ERROR("PICO_ERR_ENOMEM - not enough space");
picotap->sendReturnValue(picotap->_phy.getDescriptor(rpcSock), -1, ENOMEM);
}
if(ret == PICO_ERR_ENXIO) {
DEBUG_ERROR("PICO_ERR_ENXIO - no such device or address");
picotap->sendReturnValue(picotap->_phy.getDescriptor(rpcSock), -1, ENXIO);
}
}
picotap->sendReturnValue(picotap->_phy.getDescriptor(rpcSock), ERR_OK, ERR_OK); // success
}
// Puts a pico_socket into a listening state to receive incoming connection requests
void picoTCP::pico_handleListen(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct listen_st *listen_rpc)
{
Connection *conn = picotap->getConnection(sock);
DEBUG_ATTN("physock=%p, conn=%p, picosock=%p", sock, conn, conn->picosock);
if(!sock || !conn) {
DEBUG_ERROR("invalid connection");
return;
}
int ret, backlog = 100;
if((ret = pico_socket_listen(conn->picosock, backlog)) < 0)
{
if(ret == PICO_ERR_EINVAL) {
DEBUG_ERROR("PICO_ERR_EINVAL - invalid argument");
picotap->sendReturnValue(picotap->_phy.getDescriptor(rpcSock), -1, EINVAL);
}
if(ret == PICO_ERR_EISCONN) {
DEBUG_ERROR("PICO_ERR_EISCONN - socket is connected");
picotap->sendReturnValue(picotap->_phy.getDescriptor(rpcSock), -1, EISCONN);
}
}
picotap->sendReturnValue(picotap->_phy.getDescriptor(rpcSock), ERR_OK, ERR_OK); // success
}
// Feeds data into the local app socket from the I/O buffer associated with the "connection"
// [ (APP<-ZTSOCK) <- RXBUF ]
// -----------------------------------------
// | TAP <-> MEM BUFFER <-> STACK <-> APP |
// | |
// | APP <-> I/O BUFFER <-> STACK <-> TAP |
// | |<---------------| | RX
// -----------------------------------------
void picoTCP::pico_handleRead(PhySocket *sock,void **uptr,bool lwip_invoked)
{
if(!lwip_invoked) {
// The stack thread writes to RXBUF as well
picotap->_tcpconns_m.lock();
picotap->_rx_buf_m.lock();
}
int tot = 0, n = -1, write_attempts = 0;
Connection *conn = picotap->getConnection(sock);
if(conn && conn->rxsz) {
//
if(conn->type==SOCK_DGRAM) {
// Try to write SDK_MTU-sized chunk to app socket
while(tot < SDK_MTU) {
write_attempts++;
n = picotap->_phy.streamSend(conn->sock, (conn->rxbuf)+tot, SDK_MTU);
tot += n;
DEBUG_FLOW(" [ ZTSOCK <- RXBUF] wrote = %d, errno=%d", n, errno);
// If socket is unavailable, attempt to write N times before giving up
if(errno==35) {
if(write_attempts == 1024) {
n = SDK_MTU; // say we wrote it, even though we didn't (drop packet)
tot = SDK_MTU;
}
}
}
int payload_sz, addr_sz_offset = sizeof(struct sockaddr_storage);
memcpy(&payload_sz, conn->rxbuf + addr_sz_offset, sizeof(int));
struct sockaddr_storage addr;
memcpy(&addr, conn->rxbuf, addr_sz_offset);
// adjust buffer
//DEBUG_FLOW(" [ ZTSOCK <- RXBUF] Copying data from receiving buffer to ZT-controlled app socket (n=%d, payload_sz=%d)", n, payload_sz);
if(conn->rxsz-n > 0) { // If more remains on buffer
memcpy(conn->rxbuf, conn->rxbuf+SDK_MTU, conn->rxsz - SDK_MTU);
//DEBUG_FLOW(" [ ZTSOCK <- RXBUF] Data(%d) still on buffer, moving it up by one MTU", conn->rxsz-n);
////memset(conn->rxbuf, 0, DEFAULT_UDP_RX_BUF_SZ);
////conn->rxsz=SDK_MTU;
}
conn->rxsz -= SDK_MTU;
}
//
if(conn->type==SOCK_STREAM) {
n = picotap->_phy.streamSend(conn->sock, conn->rxbuf, conn->rxsz);
if(conn->rxsz-n > 0) // If more remains on buffer
memcpy(conn->rxbuf, conn->rxbuf+n, conn->rxsz - n);
conn->rxsz -= n;
}
// Notify ZT I/O loop that it has new buffer contents
if(n) {
if(conn->type==SOCK_STREAM) {
#if DEBUG_LEVEL >= MSG_TRANSFER
float max = conn->type == SOCK_STREAM ? (float)DEFAULT_TCP_RX_BUF_SZ : (float)DEFAULT_UDP_RX_BUF_SZ;
DEBUG_TRANS("[TCP RX] <--- :: {TX: %.3f%%, RX: %.3f%%, physock=%p} :: %d bytes",
(float)conn->txsz / max, (float)conn->rxsz / max, conn->sock, n);
#endif
}
if(conn->rxsz == 0) {
picotap->_phy.setNotifyWritable(sock, false);
}
else {
picotap->_phy.setNotifyWritable(sock, true);
}
}
else {
picotap->_phy.setNotifyWritable(sock, false);
}
}
if(!lwip_invoked) {
picotap->_tcpconns_m.unlock();
picotap->_rx_buf_m.unlock();
}
DEBUG_FLOW(" [ ZTSOCK <- RXBUF] Emitted (%d) from RXBUF(%d) to socket", tot, conn->rxsz);
}
// Closes a pico_socket
void picoTCP::pico_handleClose(PhySocket *sock)
{
/*
int ret;
if(conn && conn->picosock) {
if((ret = pico_socket_close(conn->picosock)) < 0) {
DEBUG_ERROR("error closing pico_socket(%p)", (void*)(conn->picosock));
// sendReturnValue()
}
return;
}
DEBUG_ERROR("invalid connection or pico_socket");
*/
}
}

105
src/picoTCP.hpp Normal file
View File

@@ -0,0 +1,105 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_PICOTCP_HPP
#define ZT_PICOTCP_HPP
#include "pico_eth.h"
#include "pico_stack.h"
#include "pico_ipv4.h"
#include "pico_icmp4.h"
#include "pico_dev_tap.h"
#include "pico_protocol.h"
#include "pico_socket.h"
#include "pico_device.h"
#include "pico_ipv6.h"
#include "SocketTap.hpp"
/****************************************************************************/
/* PicoTCP API Signatures */
/****************************************************************************/
#define PICO_IPV4_TO_STRING_SIG char *ipbuf, const uint32_t ip
#define PICO_TAP_CREATE_SIG char *name
#define PICO_IPV4_LINK_ADD_SIG struct pico_device *dev, struct pico_ip4 address, struct pico_ip4 netmask
#define PICO_DEVICE_INIT_SIG struct pico_device *dev, const char *name, uint8_t *mac
#define PICO_STACK_RECV_SIG struct pico_device *dev, uint8_t *buffer, uint32_t len
#define PICO_ICMP4_PING_SIG char *dst, int count, int interval, int timeout, int size, void (*cb)(struct pico_icmp4_stats *)
#define PICO_TIMER_ADD_SIG pico_time expire, void (*timer)(pico_time, void *), void *arg
#define PICO_STRING_TO_IPV4_SIG const char *ipstr, uint32_t *ip
#define PICO_STRING_TO_IPV6_SIG const char *ipstr, uint8_t *ip
#define PICO_SOCKET_SETOPTION_SIG struct pico_socket *s, int option, void *value
#define PICO_SOCKET_SEND_SIG struct pico_socket *s, const void *buf, int len
#define PICO_SOCKET_SENDTO_SIG struct pico_socket *s, const void *buf, int len, void *dst, uint16_t remote_port
#define PICO_SOCKET_RECV_SIG struct pico_socket *s, void *buf, int len
#define PICO_SOCKET_RECVFROM_SIG struct pico_socket *s, void *buf, int len, void *orig, uint16_t *remote_port
#define PICO_SOCKET_OPEN_SIG uint16_t net, uint16_t proto, void (*wakeup)(uint16_t ev, struct pico_socket *s)
#define PICO_SOCKET_BIND_SIG struct pico_socket *s, void *local_addr, uint16_t *port
#define PICO_SOCKET_CONNECT_SIG struct pico_socket *s, const void *srv_addr, uint16_t remote_port
#define PICO_SOCKET_LISTEN_SIG struct pico_socket *s, const int backlog
#define PICO_SOCKET_READ_SIG struct pico_socket *s, void *buf, int len
#define PICO_SOCKET_WRITE_SIG struct pico_socket *s, const void *buf, int len
#define PICO_SOCKET_CLOSE_SIG struct pico_socket *s
#define PICO_SOCKET_SHUTDOWN_SIG struct pico_socket *s, int mode
#define PICO_SOCKET_ACCEPT_SIG struct pico_socket *s, void *orig, uint16_t *port
#define PICO_IPV6_LINK_ADD_SIG struct pico_device *dev, struct pico_ip6 address, struct pico_ip6 netmask
namespace ZeroTier
{
class SocketTap;
struct Connection;
class picoTCP
{
public:
void pico_init_interface(ZeroTier::SocketTap *tap, const ZeroTier::InetAddress &ip);
void pico_loop(SocketTap *tap);
//int pico_eth_send(struct pico_device *dev, void *buf, int len);
//int pico_eth_poll(struct pico_device *dev, int loop_score);
static void pico_cb_tcp_read(SocketTap *tap, struct pico_socket *s);
static void pico_cb_udp_read(SocketTap *tap, struct pico_socket *s);
static void pico_cb_tcp_write(SocketTap *tap, struct pico_socket *s);
static void pico_cb_socket_activity(uint16_t ev, struct pico_socket *s);
void pico_rx(SocketTap *tap, const ZeroTier::MAC &from,const ZeroTier::MAC &to,unsigned int etherType,const void *data,unsigned int len);
Connection *pico_handleSocket(ZeroTier::PhySocket *sock, void **uptr, struct socket_st* socket_rpc);
void pico_handleWrite(Connection *conn);
void pico_handleConnect(ZeroTier::PhySocket *sock, ZeroTier::PhySocket *rpcSock, Connection *conn, struct connect_st* connect_rpc);
void pico_handleBind(ZeroTier::PhySocket *sock, ZeroTier::PhySocket *rpcSock, void **uptr, struct bind_st *bind_rpc);
void pico_handleListen(ZeroTier::PhySocket *sock, ZeroTier::PhySocket *rpcSock, void **uptr, struct listen_st *listen_rpc);
void pico_handleRead(ZeroTier::PhySocket *sock,void **uptr,bool lwip_invoked);
void pico_handleClose(ZeroTier::PhySocket *sock);
};
}
#endif