Applied styling rules from .clang-format

This commit is contained in:
Joseph Henry
2021-04-17 23:46:21 -07:00
parent 8e7bcdb16a
commit a5121b1e3c
22 changed files with 3215 additions and 2231 deletions

View File

@@ -86,14 +86,15 @@
*
*/
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <stdlib.h>
#include "ZeroTierSockets.h"
struct Node
struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {}
}
bool online;
bool joinedAtLeastOneNetwork;
uint64_t id;
@@ -115,24 +116,33 @@ void on_zts_event(void *msgPtr)
myNode.online = true;
}
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) {
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n");
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, "
"firewall, etc. What ports are you blocking?\n");
myNode.online = false;
}
// Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) {
printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
printf(
"ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) {
printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", msg->network->nwid);
printf(
"ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a "
"few seconds...\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) {
printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n",
printf(
"ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. "
"Did you authorize the node yet?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) {
printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
@@ -142,13 +152,15 @@ void on_zts_event(void *msgPtr)
// Network stack events
if (msg->eventCode == ZTS_EVENT_NETIF_UP) {
printf("ZTS_EVENT_NETIF_UP --- network=%llx, mac=%llx, mtu=%d\n",
printf(
"ZTS_EVENT_NETIF_UP --- network=%llx, mac=%llx, mtu=%d\n",
msg->netif->nwid,
msg->netif->mac,
msg->netif->mtu);
}
if (msg->eventCode == ZTS_EVENT_NETIF_DOWN) {
printf("ZTS_EVENT_NETIF_DOWN --- network=%llx, mac=%llx\n",
printf(
"ZTS_EVENT_NETIF_DOWN --- network=%llx, mac=%llx\n",
msg->netif->nwid,
msg->netif->mac);
}
@@ -158,8 +170,7 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n",
msg->addr->nwid, ipstr);
printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr);
}
// Peer events
@@ -170,18 +181,22 @@ void on_zts_event(void *msgPtr)
return;
}
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) {
printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
printf(
"ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) {
printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for "
"node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) {
printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
msg->peer->address);
}
}
@@ -221,14 +236,17 @@ int main(int argc, char **argv)
}
int adhocStartPort = atoi(argv[2]); // Start of port range your application will use
int adhocEndPort = atoi(argv[3]); // End of port range your application will use
int ztServicePort = atoi(argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int ztServicePort = atoi(
argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
uint64_t adhoc_nwid = zts_generate_adhoc_nwid_from_range(adhocStartPort, adhocEndPort);
int err = ZTS_ERR_OK;
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take
// slightly longer to start the node
zts_allow_network_caching(1);
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take
// slightly longer to contact a remote peer
zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1);
@@ -238,7 +256,9 @@ int main(int argc, char **argv)
exit(1);
}
printf("Waiting for node to come online...\n");
while (!myNode.online) { zts_delay_ms(50); }
while (! myNode.online) {
zts_delay_ms(50);
}
printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(adhoc_nwid)) != ZTS_ERR_OK) {
@@ -246,12 +266,16 @@ int main(int argc, char **argv)
exit(1);
}
printf("Joining network %llx\n", adhoc_nwid);
while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); }
while (! myNode.joinedAtLeastOneNetwork) {
zts_delay_ms(50);
}
// Idle and just show callback events, stack statistics, etc
printf("Node will now idle...\n");
while (true) { zts_delay_ms(1000); }
while (true) {
zts_delay_ms(1000);
}
// Shut down service and stack threads

View File

@@ -1,12 +1,11 @@
#include "ZeroTierSockets.h"
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iomanip>
#include <iostream>
#include "ZeroTierSockets.h"
// For optional JSON parsing
#include "../ext/ZeroTierOne/ext/json/json.hpp"
@@ -67,7 +66,12 @@ int main(int argc, char **argv)
// Provide URL to Central API server and user API token generated at https://my.zerotier.com
printf("Initializing Central API client...\n");
if ((err = zts_central_init(central_url.c_str(), api_token.c_str(), rbuf, ZTS_CENTRAL_RESP_BUF_DEFAULT_SZ)) != ZTS_ERR_OK) {
if ((err = zts_central_init(
central_url.c_str(),
api_token.c_str(),
rbuf,
ZTS_CENTRAL_RESP_BUF_DEFAULT_SZ))
!= ZTS_ERR_OK) {
fprintf(stderr, "Error while initializing client's Central API parameters\n");
return 0;
}
@@ -81,7 +85,8 @@ int main(int argc, char **argv)
printf("Requesting Central API server status (/api/status):\n");
if ((err = zts_central_get_status(&http_res_code)) != ZTS_ERR_OK) {
fprintf(stderr, "Error (%d) making the request.\n", err);
} else {
}
else {
process_response(rbuf, http_res_code);
}
// Get network config
@@ -89,15 +94,18 @@ int main(int argc, char **argv)
printf("Requesting network config: /api/network/%llx\n", nwid);
if ((err = zts_central_get_network(&http_res_code, nwid)) != ZTS_ERR_OK) {
fprintf(stderr, "Error (%d) making the request.\n", err);
} else {
}
else {
process_response(rbuf, http_res_code);
}
// Authorize a node on a network
int64_t nodeid = 0x9934343434;
printf("Authorizing: /api/network/%llx/member/%llx\n", nwid, nodeid);
if ((err = zts_central_set_node_auth(&http_res_code, nwid, nodeid, ZTS_CENTRAL_NODE_AUTH_TRUE)) != ZTS_ERR_OK) {
if ((err = zts_central_set_node_auth(&http_res_code, nwid, nodeid, ZTS_CENTRAL_NODE_AUTH_TRUE))
!= ZTS_ERR_OK) {
fprintf(stderr, "Error (%d) making the request.\n", err);
} else {
}
else {
process_response(rbuf, http_res_code);
}

View File

@@ -2,16 +2,17 @@
* libzt API example
*/
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "ZeroTierSockets.h"
struct Node
struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {}
}
bool online;
bool joinedAtLeastOneNetwork;
uint64_t id;
@@ -33,7 +34,8 @@ void on_zts_event(void *msgPtr)
myNode.online = true;
}
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) {
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n");
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, "
"firewall, etc. What ports are you blocking?\n");
myNode.online = false;
}
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
@@ -42,23 +44,33 @@ void on_zts_event(void *msgPtr)
// Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) {
printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
printf(
"ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) {
printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", msg->network->nwid);
printf(
"ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a "
"few seconds...\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) {
printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n",
printf(
"ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. "
"Did you authorize the node yet?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) {
printf("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) {
printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
@@ -71,29 +83,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
// Peer events
if (msg->peer) {
@@ -103,18 +125,22 @@ void on_zts_event(void *msgPtr)
return;
}
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) {
printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
printf(
"ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) {
printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for "
"node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) {
printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
msg->peer->address);
}
}
@@ -212,7 +238,8 @@ int main(int argc, char **argv)
uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
std::string remoteAddr = argv[3]; // Remote application's virtual ZT address
int remotePort = atoi(argv[4]); // Port the application will try to connect to the server on
int ztServicePort = atoi(argv[5]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int ztServicePort = atoi(
argv[5]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
struct zts_sockaddr_in in4;
in4.sin_port = htons(remotePort);
@@ -227,9 +254,11 @@ int main(int argc, char **argv)
int err = ZTS_ERR_OK;
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take
// slightly longer to start the node
zts_allow_network_caching(1);
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take
// slightly longer to contact a remote peer
zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1);
@@ -239,7 +268,9 @@ int main(int argc, char **argv)
exit(1);
}
printf("Waiting for node to come online...\n");
while (!myNode.online) { zts_delay_ms(50); }
while (! myNode.online) {
zts_delay_ms(50);
}
printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(nwid)) != ZTS_ERR_OK) {
@@ -248,7 +279,9 @@ int main(int argc, char **argv)
}
printf("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n");
while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); }
while (! myNode.joinedAtLeastOneNetwork) {
zts_delay_ms(50);
}
// Socket-like API example
@@ -265,12 +298,18 @@ int main(int argc, char **argv)
for (;;) {
printf("Connecting to remote host...\n");
if ((err = zts_connect(fd, (const struct zts_sockaddr*)&in4, sizeof(in4))) < 0) {
printf("Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n",
fd, err, zts_errno);
printf(
"Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n",
fd,
err,
zts_errno);
zts_close(fd);
printf("Creating socket...\n");
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) {
printf("Error creating ZeroTier socket (fd=%d, zts_errno=%d). Exiting.\n", fd, zts_errno);
printf(
"Error creating ZeroTier socket (fd=%d, zts_errno=%d). Exiting.\n",
fd,
zts_errno);
exit(1);
}
zts_delay_ms(250);
@@ -282,13 +321,21 @@ int main(int argc, char **argv)
}
printf("Sending message string to server...\n");
if ((bytes = zts_write(fd, msgStr, strlen(msgStr))) < 0) {
printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno);
printf(
"Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
bytes,
zts_errno);
exit(1);
}
printf("Sent %d bytes: %s\n", bytes, msgStr);
printf("Reading message string from server...\n");
if ((bytes = zts_read(fd, recvBuf, sizeof(recvBuf))) < 0) {
printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno);
printf(
"Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
bytes,
zts_errno);
exit(1);
}
printf("Read %d bytes: %s\n", bytes, recvBuf);

View File

@@ -86,18 +86,19 @@
*
*/
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "ZeroTierSockets.h"
#ifdef __WINDOWS__
#include "winsock.h"
#endif
struct Node
struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {}
}
bool online;
bool joinedAtLeastOneNetwork;
uint64_t id;
@@ -108,7 +109,11 @@ void printNodeDetails(const char *msgStr, struct zts_node_details *d)
{
printf("\n%s\n", msgStr);
printf("\t- id : %llx\n", d->address);
printf("\t- version : %d.%d.%d\n", d->versionMajor, d->versionMinor, d->versionRev);
printf(
"\t- version : %d.%d.%d\n",
d->versionMajor,
d->versionMinor,
d->versionRev);
printf("\t- primaryPort : %d\n", d->primaryPort);
printf("\t- secondaryPort : %d\n", d->secondaryPort);
}
@@ -119,7 +124,11 @@ void printPeerDetails(const char *msgStr, struct zts_peer_details *d)
printf("\t- peer : %llx\n", d->address);
printf("\t- role : %llx\n", d->role);
printf("\t- latency : %d\n", d->latency);
printf("\t- version : %d.%d.%d\n", d->versionMajor, d->versionMinor, d->versionRev);
printf(
"\t- version : %d.%d.%d\n",
d->versionMajor,
d->versionMinor,
d->versionRev);
printf("\t- pathCount : %d\n", d->pathCount);
printf("\t- paths:\n");
@@ -160,7 +169,10 @@ void printNetworkDetails(const char *msgStr, struct zts_network_details *d)
printf("\t- multicastSubscriptionCount : %d\n", d->multicastSubscriptionCount);
for (int i = 0; i < d->multicastSubscriptionCount; i++) {
printf("\t - mac=%llx, adi=%x\n", d->multicastSubscriptions[i].mac, d->multicastSubscriptions[i].adi);
printf(
"\t - mac=%llx, adi=%x\n",
d->multicastSubscriptions[i].mac,
d->multicastSubscriptions[i].adi);
}
printf("\t- addresses:\n");
@@ -230,33 +242,44 @@ void on_zts_event(void *msgPtr)
myNode.online = true;
}
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) {
printf("\nZTS_EVENT_NODE_OFFLINE --- Check your Internet connection, router, firewall, etc. What ports are you blocking?\n");
printf("\nZTS_EVENT_NODE_OFFLINE --- Check your Internet connection, router, firewall, "
"etc. What ports are you blocking?\n");
myNode.online = false;
}
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
printf("\nZTS_EVENT_NODE_NORMAL_TERMINATION -- A call to zts_start() will restart ZeroTier.\n");
printf("\nZTS_EVENT_NODE_NORMAL_TERMINATION -- A call to zts_start() will restart "
"ZeroTier.\n");
myNode.online = false;
}
// Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) {
printf("\nZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
printf(
"\nZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) {
printf("\nZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n",
printf(
"\nZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a "
"few seconds...\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) {
printf("\nZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n",
printf(
"\nZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. "
"Did you authorize the node yet?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) {
printNetworkDetails("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received.", msg->network);
printNetworkDetails(
"ZTS_EVENT_NETWORK_READY_IP4 --- Network config received.",
msg->network);
myNode.joinedAtLeastOneNetwork = true;
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) {
printNetworkDetails("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received.", msg->network);
printNetworkDetails(
"ZTS_EVENT_NETWORK_READY_IP6 --- Network config received.",
msg->network);
myNode.joinedAtLeastOneNetwork = true;
}
if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) {
@@ -271,29 +294,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("\nZTS_EVENT_ADDR_ADDED_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"\nZTS_EVENT_ADDR_ADDED_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("\nZTS_EVENT_ADDR_ADDED_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"\nZTS_EVENT_ADDR_ADDED_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("\nZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"\nZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("\nZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"\nZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
// Peer events
@@ -310,7 +343,9 @@ void on_zts_event(void *msgPtr)
printPeerDetails("ZTS_EVENT_PEER_RELAY --- No direct path known.", msg->peer);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) {
printPeerDetails("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered.", msg->peer);
printPeerDetails(
"ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered.",
msg->peer);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) {
printPeerDetails("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died.", msg->peer);
@@ -338,7 +373,8 @@ void on_zts_event(void *msgPtr)
printf("\nZTS_EVENT_STACK_UP --- No action required.\n");
}
if (msg->eventCode == ZTS_EVENT_STACK_DOWN) {
printf("\nZTS_EVENT_STACK_DOWN --- No action required. An app restart is needed to use ZeroTier again.\n");
printf("\nZTS_EVENT_STACK_DOWN --- No action required. An app restart is needed to use "
"ZeroTier again.\n");
}
}
@@ -358,7 +394,8 @@ void display_stack_stats()
{
int err = 0;
// Count received pings
if ((err = zts_get_protocol_stats(ZTS_STATS_PROTOCOL_ICMP, &protoSpecificStats)) != ZTS_ERR_OK) {
if ((err = zts_get_protocol_stats(ZTS_STATS_PROTOCOL_ICMP, &protoSpecificStats))
!= ZTS_ERR_OK) {
printf("zts_get_proto_stats()=%d", err);
return;
}
@@ -380,15 +417,18 @@ int main(int argc, char **argv)
}
std::string configPath = std::string(argv[1]);
uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
int ztServicePort = atoi(argv[3]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int ztServicePort = atoi(
argv[3]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
// Bring up ZeroTier service and join network
int err = ZTS_ERR_OK;
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take
// slightly longer to start the node
zts_allow_network_caching(1);
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take
// slightly longer to contact a remote peer
zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1);
@@ -398,7 +438,9 @@ int main(int argc, char **argv)
exit(1);
}
printf("Waiting for node to come online...\n");
while (!myNode.online) { zts_delay_ms(50); }
while (! myNode.online) {
zts_delay_ms(50);
}
printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(nwid)) != ZTS_ERR_OK) {
@@ -407,7 +449,9 @@ int main(int argc, char **argv)
}
printf("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n");
while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); }
while (! myNode.joinedAtLeastOneNetwork) {
zts_delay_ms(50);
}
// Idle and just show callback events, stack statistics, etc
// Alternatively, this is where you could start making calls to the socket API

View File

@@ -86,14 +86,15 @@
*
*/
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <stdlib.h>
#include "ZeroTierSockets.h"
struct Node
struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {}
}
bool online;
bool joinedAtLeastOneNetwork;
uint64_t id;
@@ -114,18 +115,26 @@ void on_zts_event(void *msgPtr)
myNode.online = true;
}
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) {
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n");
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, "
"firewall, etc. What ports are you blocking?\n");
myNode.online = false;
}
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) {
printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", msg->network->nwid);
printf(
"ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a "
"few seconds...\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) {
printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n",
printf(
"ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. "
"Did you authorize the node yet?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) {
printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
@@ -136,15 +145,13 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP4 --- Join %llx and ping me at %s\n",
msg->addr->nwid, ipstr);
printf("ZTS_EVENT_ADDR_NEW_IP4 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n",
msg->addr->nwid, ipstr);
printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr);
}
// Peer events
if (msg->peer) {
@@ -154,18 +161,22 @@ void on_zts_event(void *msgPtr)
return;
}
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) {
printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
printf(
"ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) {
printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for "
"node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) {
printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
msg->peer->address);
}
}
@@ -178,13 +189,16 @@ int main(int argc, char **argv)
printf("earthtest <config_file_path> <ztServicePort>\n");
exit(0);
}
int ztServicePort = atoi(argv[2]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int ztServicePort = atoi(
argv[2]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int err = ZTS_ERR_OK;
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take
// slightly longer to start the node
zts_allow_network_caching(1);
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take
// slightly longer to contact a remote peer
zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1);
@@ -194,7 +208,9 @@ int main(int argc, char **argv)
exit(1);
}
printf("Waiting for node to come online...\n");
while (!myNode.online) { zts_delay_ms(50); }
while (! myNode.online) {
zts_delay_ms(50);
}
printf("This node's identity is stored in %s\n", argv[1]);
uint64_t nwid = 0x8056c2e21c000001;
@@ -204,12 +220,16 @@ int main(int argc, char **argv)
exit(1);
}
printf("Joining network %llx\n", nwid);
while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); }
while (! myNode.joinedAtLeastOneNetwork) {
zts_delay_ms(50);
}
// Idle and just show callback events, stack statistics, etc
printf("Node will now idle...\n");
while (true) { zts_delay_ms(1000); }
while (true) {
zts_delay_ms(1000);
}
// Shut down service and stack threads

View File

@@ -5,15 +5,16 @@
* local storage. In this mode you are responsible for saving keys.
*/
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ZeroTierSockets.h"
struct Node
struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {}
}
bool online;
bool joinedAtLeastOneNetwork;
uint64_t id;
@@ -34,11 +35,14 @@ void on_zts_event(void *msgPtr)
myNode.online = true;
}
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) {
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n");
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, "
"firewall, etc. What ports are you blocking?\n");
myNode.online = false;
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) {
printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
@@ -53,17 +57,17 @@ int main(int argc, char **argv)
printf("earthtest <config_file_path> <ztServicePort>\n");
exit(0);
}
int ztServicePort = atoi(argv[2]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int ztServicePort = atoi(
argv[2]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int err = ZTS_ERR_OK;
// BEGIN key handling
// Do not allow ZT to write anything to disk
zts_disable_local_storage(1);
// Buffer used to store identity keypair (if someone can read this, they can impersonate your node!)
// Buffer used to store identity keypair (if someone can read this, they can impersonate your
// node!)
char keypair[KEY_BUF_LEN];
memset(keypair, 0, KEY_BUF_LEN);
@@ -77,7 +81,8 @@ int main(int argc, char **argv)
printf("\n\nVerifying ident...\n");
if (zts_verify_identity(keypair)) {
printf("\tIdentity is valid\n");
} else {
}
else {
printf("\tIdentity is invalid\n");
}
@@ -85,7 +90,9 @@ int main(int argc, char **argv)
zts_start_with_identity(keypair, keypair_len, &on_zts_event, ztServicePort);
printf("\n\nWaiting for node to come online...\n");
while (!myNode.online) { zts_delay_ms(50); }
while (! myNode.online) {
zts_delay_ms(50);
}
printf("\n\nAs a test, copy node's identity keypair back into buffer...\n");
memset(keypair, 0, KEY_BUF_LEN);
@@ -93,10 +100,8 @@ int main(int argc, char **argv)
zts_get_node_identity(keypair, &keypair_len);
printf("keypair(len=%d) = [%s]\n", keypair_len, keypair);
// END key handling
uint64_t nwid = 0x8056c2e21c000001;
if ((err = zts_join(nwid)) != ZTS_ERR_OK) {
@@ -104,12 +109,16 @@ int main(int argc, char **argv)
exit(1);
}
printf("Joining network %llx\n", nwid);
while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); }
while (! myNode.joinedAtLeastOneNetwork) {
zts_delay_ms(50);
}
// Idle and just show callback events, stack statistics, etc
printf("Node will now idle...\n");
while (true) { zts_delay_ms(1000); }
while (true) {
zts_delay_ms(1000);
}
// Shut down service and stack threads

View File

@@ -84,16 +84,17 @@
*
*/
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "ZeroTierSockets.h"
struct Node
struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {}
}
bool online;
bool joinedAtLeastOneNetwork;
uint64_t id;
@@ -115,7 +116,8 @@ void on_zts_event(void *msgPtr)
myNode.online = true;
}
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) {
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n");
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, "
"firewall, etc. What ports are you blocking?\n");
myNode.online = false;
}
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
@@ -125,24 +127,33 @@ void on_zts_event(void *msgPtr)
// Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) {
printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
printf(
"ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) {
printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n",
printf(
"ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a "
"few seconds...\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) {
printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n",
printf(
"ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. "
"Did you authorize the node yet?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) {
printf("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) {
printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
@@ -155,29 +166,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
// Peer events
@@ -188,18 +209,22 @@ void on_zts_event(void *msgPtr)
return;
}
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) {
printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
printf(
"ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) {
printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for "
"node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) {
printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
msg->peer->address);
}
}
@@ -209,13 +234,15 @@ int main(int argc, char **argv)
{
if (argc != 6) {
printf("\nlibzt example non-blocking client\n");
printf("nonblockingclient <config_file_path> <nwid> <remoteAddr> <remotePort> <ztServicePort>\n");
printf("nonblockingclient <config_file_path> <nwid> <remoteAddr> <remotePort> "
"<ztServicePort>\n");
exit(0);
}
uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
std::string remoteAddr = argv[3]; // Remote application's virtual ZT address
int remotePort = atoi(argv[4]); // Port the application will try to connect to the server on
int ztServicePort = atoi(argv[5]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int ztServicePort = atoi(
argv[5]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
struct zts_sockaddr_in in4;
in4.sin_port = htons(remotePort);
@@ -230,9 +257,11 @@ int main(int argc, char **argv)
int err = ZTS_ERR_OK;
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take
// slightly longer to start the node
zts_allow_network_caching(1);
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take
// slightly longer to contact a remote peer
zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1);
@@ -242,7 +271,9 @@ int main(int argc, char **argv)
exit(1);
}
printf("Waiting for node to come online...\n");
while (!myNode.online) { zts_delay_ms(50); }
while (! myNode.online) {
zts_delay_ms(50);
}
printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(nwid)) != ZTS_ERR_OK) {
@@ -251,7 +282,9 @@ int main(int argc, char **argv)
}
printf("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n");
while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); }
while (! myNode.joinedAtLeastOneNetwork) {
zts_delay_ms(50);
}
// Socket-like API example
@@ -268,12 +301,18 @@ int main(int argc, char **argv)
for (;;) {
printf("Connecting to remote host...\n");
if ((err = zts_connect(fd, (const struct zts_sockaddr*)&in4, sizeof(in4))) < 0) {
printf("Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n",
fd, err, zts_errno);
printf(
"Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n",
fd,
err,
zts_errno);
zts_close(fd);
printf("Creating socket...\n");
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) {
printf("Error creating ZeroTier socket (fd=%d, zts_errno=%d). Exiting.\n", fd, zts_errno);
printf(
"Error creating ZeroTier socket (fd=%d, zts_errno=%d). Exiting.\n",
fd,
zts_errno);
exit(1);
}
zts_delay_ms(250);
@@ -288,7 +327,11 @@ int main(int argc, char **argv)
// The non-blocking aspect of this example is server-side
while (1) {
if ((bytes = zts_send(fd, msgStr, strlen(msgStr), 0)) < 0) {
printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno);
printf(
"Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
bytes,
zts_errno);
exit(1);
}
printf("zts_send()=%d\n", bytes);

View File

@@ -84,15 +84,16 @@
*
*/
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ZeroTierSockets.h"
struct Node
struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {}
}
bool online;
bool joinedAtLeastOneNetwork;
uint64_t id;
@@ -114,7 +115,8 @@ void on_zts_event(void *msgPtr)
myNode.online = true;
}
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) {
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n");
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, "
"firewall, etc. What ports are you blocking?\n");
myNode.online = false;
}
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
@@ -124,24 +126,33 @@ void on_zts_event(void *msgPtr)
// Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) {
printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
printf(
"ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) {
printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n",
printf(
"ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a "
"few seconds...\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) {
printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n",
printf(
"ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. "
"Did you authorize the node yet?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) {
printf("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) {
printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
@@ -154,29 +165,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
// Peer events
@@ -187,18 +208,22 @@ void on_zts_event(void *msgPtr)
return;
}
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) {
printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
printf(
"ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) {
printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for "
"node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) {
printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
msg->peer->address);
}
}
@@ -213,7 +238,8 @@ int main(int argc, char **argv)
}
uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
int serverBindPort = atoi(argv[3]); // Port the application should bind to
int ztServicePort = atoi(argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int ztServicePort = atoi(
argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
struct zts_sockaddr_in in4, acc_in4;
in4.sin_port = htons(serverBindPort);
@@ -229,9 +255,11 @@ int main(int argc, char **argv)
int fd, accfd;
int err = ZTS_ERR_OK;
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take
// slightly longer to start the node
zts_allow_network_caching(1);
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take
// slightly longer to contact a remote peer
zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1);
@@ -241,7 +269,9 @@ int main(int argc, char **argv)
exit(1);
}
printf("Waiting for node to come online...\n");
while (!myNode.online) { zts_delay_ms(50); }
while (! myNode.online) {
zts_delay_ms(50);
}
printf("This node ID is %llx\n", myNode.id);
printf("This node's identity is stored in %s\n", argv[1]);
@@ -251,29 +281,47 @@ int main(int argc, char **argv)
}
printf("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n");
while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); }
while (! myNode.joinedAtLeastOneNetwork) {
zts_delay_ms(50);
}
// Socket-like API example
printf("Creating socket...\n");
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) {
printf("Error creating ZeroTier socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",fd, err, zts_errno);
printf(
"Error creating ZeroTier socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
err,
zts_errno);
exit(1);
}
printf("Binding...\n");
if ((err = zts_bind(fd, (struct zts_sockaddr*)&in4, sizeof(struct zts_sockaddr_in)) < 0)) {
printf("Error binding to interface (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno);
printf(
"Error binding to interface (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
err,
zts_errno);
exit(1);
}
printf("Listening...\n");
int backlog = 100;
if ((err = zts_listen(fd, backlog)) < 0) {
printf("Error placing socket in LISTENING state (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno);
printf(
"Error placing socket in LISTENING state (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
err,
zts_errno);
exit(1);
}
zts_socklen_t client_addrlen = sizeof(zts_sockaddr_in);
if ((accfd = zts_accept(fd, (struct zts_sockaddr*)&acc_in4, &client_addrlen)) < 0) {
printf("Error accepting connection (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno);
printf(
"Error accepting connection (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
err,
zts_errno);
}
zts_socklen_t peer_addrlen = sizeof(struct zts_sockaddr_storage);
@@ -311,17 +359,14 @@ int main(int argc, char **argv)
zts_fd_set active_fd_set, read_fd_set;
ZTS_FD_ZERO(&active_fd_set);
ZTS_FD_SET(accfd, &active_fd_set);
while (1)
{
while (1) {
read_fd_set = active_fd_set;
if ((result = zts_select(ZTS_FD_SETSIZE, &read_fd_set, NULL, NULL, &tv) < 0))
{
if ((result = zts_select(ZTS_FD_SETSIZE, &read_fd_set, NULL, NULL, &tv) < 0)) {
// perror ("select");
exit(1);
}
for (int i = 0; i < ZTS_FD_SETSIZE; i++) {
if (ZTS_FD_ISSET(i, &read_fd_set))
{
if (ZTS_FD_ISSET(i, &read_fd_set)) {
bytes = zts_recv(accfd, recvBuf, sizeof(recvBuf), 0);
printf("zts_recv(%d, ...)=%d\n", i, bytes);
}
@@ -345,8 +390,7 @@ int main(int argc, char **argv)
while (1) {
result = zts_poll(poll_set, numfds, timeout_ms);
printf("zts_poll()=%d\n", result);
for(int i = 0; i < numfds; i++)
{
for (int i = 0; i < numfds; i++) {
if (poll_set[i].revents & ZTS_POLLIN) {
bytes = zts_recv(poll_set[i].fd, recvBuf, sizeof(recvBuf), 0);
printf("zts_recv(%d, ...)=%d\n", i, bytes);

View File

@@ -2,16 +2,17 @@
* libzt API example
*/
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "ZeroTierSockets.h"
struct Node
struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {}
}
bool online;
bool joinedAtLeastOneNetwork;
uint64_t id;
@@ -33,7 +34,8 @@ void on_zts_event(void *msgPtr)
myNode.online = true;
}
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) {
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n");
printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, "
"firewall, etc. What ports are you blocking?\n");
myNode.online = false;
}
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
@@ -42,23 +44,33 @@ void on_zts_event(void *msgPtr)
// Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) {
printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
printf(
"ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) {
printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", msg->network->nwid);
printf(
"ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a "
"few seconds...\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) {
printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n",
printf(
"ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. "
"Did you authorize the node yet?\n",
msg->network->nwid);
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) {
printf("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) {
printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n",
printf(
"ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent "
"over network %llx\n",
msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true;
}
@@ -71,29 +83,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid, ipstr);
printf(
"ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n",
msg->addr->nwid,
ipstr);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN);
printf("ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n",
ipstr, msg->addr->nwid);
printf(
"ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx "
"has been removed.\n",
ipstr,
msg->addr->nwid);
}
// Peer events
if (msg->peer) {
@@ -103,18 +125,22 @@ void on_zts_event(void *msgPtr)
return;
}
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) {
printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
printf(
"ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) {
printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for "
"node=%llx\n",
msg->peer->address);
}
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) {
printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
printf(
"ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n",
msg->peer->address);
}
}
@@ -211,7 +237,8 @@ int main(int argc, char **argv)
}
uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
int serverBindPort = atoi(argv[3]); // Port the application should bind to
int ztServicePort = atoi(argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
int ztServicePort = atoi(
argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994)
struct zts_sockaddr_in in4, acc_in4;
in4.sin_port = htons(serverBindPort);
@@ -227,9 +254,11 @@ int main(int argc, char **argv)
int fd, accfd;
int err = ZTS_ERR_OK;
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node
// If disabled: (network) details will NOT be written to or read from (networks.d/). It may take
// slightly longer to start the node
zts_allow_network_caching(1);
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer
// If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take
// slightly longer to contact a remote peer
zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1);
@@ -239,7 +268,9 @@ int main(int argc, char **argv)
exit(1);
}
printf("Waiting for node to come online...\n");
while (!myNode.online) { zts_delay_ms(50); }
while (! myNode.online) {
zts_delay_ms(50);
}
printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(nwid)) != ZTS_ERR_OK) {
@@ -248,24 +279,38 @@ int main(int argc, char **argv)
}
printf("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n");
while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); }
while (! myNode.joinedAtLeastOneNetwork) {
zts_delay_ms(50);
}
// Socket-like API example
printf("Creating socket...\n");
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) {
printf("Error creating ZeroTier socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",fd, err, zts_errno);
printf(
"Error creating ZeroTier socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
err,
zts_errno);
exit(1);
}
printf("Binding...\n");
if ((err = zts_bind(fd, (struct zts_sockaddr*)&in4, sizeof(struct zts_sockaddr_in)) < 0)) {
printf("Error binding to interface (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno);
printf(
"Error binding to interface (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
err,
zts_errno);
exit(1);
}
printf("Listening...\n");
int backlog = 100;
if ((err = zts_listen(fd, backlog)) < 0) {
printf("Error placing socket in LISTENING state (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno);
printf(
"Error placing socket in LISTENING state (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
err,
zts_errno);
exit(1);
}
@@ -276,7 +321,11 @@ int main(int argc, char **argv)
while (true) {
zts_socklen_t client_addrlen = sizeof(zts_sockaddr_in);
if ((accfd = zts_accept(fd, (struct zts_sockaddr*)&acc_in4, &client_addrlen)) < 0) {
printf("Error accepting connection (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno);
printf(
"Error accepting connection (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
err,
zts_errno);
}
zts_socklen_t peer_addrlen = sizeof(struct zts_sockaddr_storage);
zts_getpeername(accfd, (struct zts_sockaddr*)&acc_in4, &peer_addrlen);
@@ -288,13 +337,21 @@ int main(int argc, char **argv)
printf("Reading message string from client...\n");
if ((bytes = zts_read(accfd, recvBuf, sizeof(recvBuf))) < 0) {
printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno);
printf(
"Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
bytes,
zts_errno);
exit(1);
}
printf("Read %d bytes: %s\n", bytes, recvBuf);
printf("Sending message string to client...\n");
if ((bytes = zts_write(accfd, recvBuf, bytes)) < 0) {
printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno);
printf(
"Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",
fd,
bytes,
zts_errno);
exit(1);
}
printf("Sent %d bytes: %s\n", bytes, recvBuf);

View File

@@ -29,8 +29,7 @@ extern "C" {
//----------------------------------------------------------------------------//
/** Common error return values */
enum zts_error
{
enum zts_error {
/** No error */
ZTS_ERR_OK = 0,
/** Socket error, see `zts_errno` */
@@ -50,8 +49,7 @@ enum zts_error
//----------------------------------------------------------------------------//
/** Event codes used by the callback API */
enum zts_event
{
enum zts_event {
/** The node service started successfully (no action needed) */
ZTS_EVENT_NODE_UP = 200,
/** The node can reach the Internet */
@@ -407,8 +405,10 @@ extern int zts_errno;
#define ZTS_IOC_IN 0x80000000UL
#define ZTS_IOC_INOUT (ZTS_IOC_IN | ZTS_IOC_OUT)
#define ZTS_IO(x, y) (ZTS_IOC_VOID | ((x) << 8) | (y))
#define ZTS_IOR(x,y,t) (ZTS_IOC_OUT | (((long)sizeof(t) & ZTS_IOCPARM_MASK)<<16) | ((x)<<8) | (y))
#define ZTS_IOW(x,y,t) (ZTS_IOC_IN | (((long)sizeof(t) & ZTS_IOCPARM_MASK)<<16) | ((x)<<8) | (y))
#define ZTS_IOR(x, y, t) \
(ZTS_IOC_OUT | (((long)sizeof(t) & ZTS_IOCPARM_MASK) << 16) | ((x) << 8) | (y))
#define ZTS_IOW(x, y, t) \
(ZTS_IOC_IN | (((long)sizeof(t) & ZTS_IOCPARM_MASK) << 16) | ((x) << 8) | (y))
// ioctl() commands
#define ZTS_FIONREAD ZTS_IOR('f', 127, unsigned long)
#define ZTS_FIONBIO ZTS_IOW('f', 126, unsigned long)
@@ -493,8 +493,7 @@ struct zts_sockaddr_storage {
/**
* What trust hierarchy role does this peer have?
*/
enum zts_peer_role
{
enum zts_peer_role {
ZTS_PEER_ROLE_LEAF = 0, // ordinary node
ZTS_PEER_ROLE_MOON = 1, // moon root
ZTS_PEER_ROLE_PLANET = 2 // planetary root
@@ -504,8 +503,7 @@ enum zts_peer_role
* A structure used to convey details about the current node
* to the user application
*/
struct zts_node_details
{
struct zts_node_details {
/**
* The node ID
*/
@@ -531,8 +529,7 @@ struct zts_node_details
* A structure used to convey information to a user application via
* a callback function.
*/
struct zts_callback_msg
{
struct zts_callback_msg {
/**
* Event identifier
*/
@@ -546,8 +543,7 @@ struct zts_callback_msg
struct zts_addr_details* addr;
};
struct zts_addr_details
{
struct zts_addr_details {
uint64_t nwid;
struct zts_sockaddr_storage addr;
};
@@ -556,8 +552,7 @@ struct zts_addr_details
* A structure used to convey information about a virtual network
* interface (netif) to a user application.
*/
struct zts_netif_details
{
struct zts_netif_details {
/**
* The virtual network that this interface was commissioned for.
*/
@@ -577,8 +572,7 @@ struct zts_netif_details
/**
* A structure used to represent a virtual network route
*/
struct zts_virtual_network_route
{
struct zts_virtual_network_route {
/**
* Target network / netmask bits (in port field) or NULL or 0.0.0.0/0 for default
*/
@@ -600,7 +594,6 @@ struct zts_virtual_network_route
uint16_t metric;
};
/**
* Maximum length of network short name
*/
@@ -612,7 +605,8 @@ struct zts_virtual_network_route
#define ZTS_MAX_NETWORK_ROUTES 32
/**
* Maximum number of statically assigned IP addresses per network endpoint using ZT address management (not DHCP)
* Maximum number of statically assigned IP addresses per network endpoint using ZT address
* management (not DHCP)
*/
#define ZTS_MAX_ZT_ASSIGNED_ADDRESSES 16
@@ -624,8 +618,7 @@ struct zts_virtual_network_route
/**
* Virtual network status codes
*/
enum ZTS_VirtualNetworkStatus
{
enum ZTS_VirtualNetworkStatus {
/**
* Waiting for network configuration (also means revision == 0)
*/
@@ -660,8 +653,7 @@ enum ZTS_VirtualNetworkStatus
/**
* Virtual network type codes
*/
enum ZTS_VirtualNetworkType
{
enum ZTS_VirtualNetworkType {
/**
* Private networks are authorized via certificates of membership
*/
@@ -676,8 +668,7 @@ enum ZTS_VirtualNetworkType
/**
* A route to be pushed on a virtual network
*/
typedef struct
{
typedef struct {
/**
* Target network / netmask bits (in port field) or NULL or 0.0.0.0/0 for default
*/
@@ -702,8 +693,7 @@ typedef struct
/**
* Virtual network configuration
*/
struct zts_network_details
{
struct zts_network_details {
/**
* 64-bit ZeroTier network ID
*/
@@ -757,7 +747,8 @@ struct zts_network_details
int broadcastEnabled;
/**
* If the network is in PORT_ERROR state, this is the (negative) error code most recently reported
* If the network is in PORT_ERROR state, this is the (negative) error code most recently
* reported
*/
int portError;
@@ -803,15 +794,15 @@ struct zts_network_details
*/
struct {
uint64_t mac; /* MAC in lower 48 bits */
uint32_t adi; /* Additional distinguishing information, usually zero except for IPv4 ARP groups */
uint32_t adi; /* Additional distinguishing information, usually zero except for IPv4 ARP
groups */
} multicastSubscriptions[ZTS_MAX_MULTICAST_SUBSCRIPTIONS];
};
/**
* Physical network path to a peer
*/
struct zts_physical_path
{
struct zts_physical_path {
/**
* Address of endpoint
*/
@@ -846,8 +837,7 @@ struct zts_physical_path
/**
* Peer status result buffer
*/
struct zts_peer_details
{
struct zts_peer_details {
/**
* ZeroTier address (40 bits)
*/
@@ -892,8 +882,7 @@ struct zts_peer_details
/**
* List of peers
*/
struct zts_peer_list
{
struct zts_peer_list {
struct zts_peer_details* peers;
unsigned long peerCount;
};
@@ -910,8 +899,7 @@ struct zts_peer_list
* Abstract class used as a director. Pointer to an instance of this class
* is provided to the Python layer.
*/
class PythonDirectorCallbackClass
{
class PythonDirectorCallbackClass {
public:
/**
* Called by native code on event. Implemented in Python
@@ -997,8 +985,8 @@ ZTS_API void ZTCALL zts_central_clear_resp_buf();
* @param buf_len Size of buffer for server response (specify `0` for default size)
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/
ZTS_API int ZTCALL zts_central_init(
const char *url_str, const char *token_str, char *resp_buf, uint32_t buf_len);
ZTS_API int ZTCALL
zts_central_init(const char* url_str, const char* token_str, char* resp_buf, uint32_t buf_len);
ZTS_API void ZTCALL zts_central_cleanup();
@@ -1011,8 +999,7 @@ ZTS_API void ZTCALL zts_central_cleanup();
* @return `ZTS_ERR_OK` if all contents were copied successfully.
* `ZTS_ERR_ARG` if provided buffer was too small.
*/
ZTS_API int ZTCALL zts_central_get_last_response_buf(
char *dest_buffer, int dest_buf_len);
ZTS_API int ZTCALL zts_central_get_last_response_buf(char* dest_buffer, int dest_buf_len);
/**
* @brief Get the status of the Central API server.
@@ -1033,8 +1020,7 @@ ZTS_API int ZTCALL zts_central_get_self(int *http_response_code);
*
* @return Standard HTTP response codes.
*/
ZTS_API int ZTCALL zts_central_get_network(
int *http_response_code, uint64_t nwid);
ZTS_API int ZTCALL zts_central_get_network(int* http_response_code, uint64_t nwid);
/**
* @brief Update or create a Network.
@@ -1046,8 +1032,7 @@ ZTS_API int ZTCALL zts_central_get_network(
*
* @return Standard HTTP response codes.
*/
ZTS_API int ZTCALL zts_central_update_network(
int *http_response_code, uint64_t nwid);
ZTS_API int ZTCALL zts_central_update_network(int* http_response_code, uint64_t nwid);
/**
* @brief Delete a Network.
@@ -1057,8 +1042,7 @@ ZTS_API int ZTCALL zts_central_update_network(
*
* @return Standard HTTP response codes.
*/
ZTS_API int ZTCALL zts_central_delete_network(
int *http_response_code, uint64_t nwid);
ZTS_API int ZTCALL zts_central_delete_network(int* http_response_code, uint64_t nwid);
/**
* @brief Get All Viewable Networks.
@@ -1073,8 +1057,7 @@ ZTS_API int ZTCALL zts_central_get_networks(int *http_response_code);
*
* @return Standard HTTP response codes.
*/
ZTS_API int ZTCALL zts_central_get_member(
int *http_response_code, uint64_t nwid, uint64_t nodeid);
ZTS_API int ZTCALL zts_central_get_member(int* http_response_code, uint64_t nwid, uint64_t nodeid);
/**
* @brief Update or add a Member.
@@ -1083,8 +1066,8 @@ ZTS_API int ZTCALL zts_central_get_member(
*
* @return Standard HTTP response codes.
*/
ZTS_API int ZTCALL zts_central_update_member(
int *http_response_code, uint64_t nwid, uint64_t nodeid, char *post_data);
ZTS_API int ZTCALL
zts_central_update_member(int* http_response_code, uint64_t nwid, uint64_t nodeid, char* post_data);
/**
* @brief Authorize or (De)authorize a node on a network. This operation
@@ -1096,7 +1079,10 @@ ZTS_API int ZTCALL zts_central_update_member(
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/
ZTS_API int ZTCALL zts_central_set_node_auth(
int *http_response_code, uint64_t nwid, uint64_t nodeid, uint8_t is_authed);
int* http_response_code,
uint64_t nwid,
uint64_t nodeid,
uint8_t is_authed);
/**
* @brief Get All Members of a Network.
@@ -1105,8 +1091,7 @@ ZTS_API int ZTCALL zts_central_set_node_auth(
*
* @return Standard HTTP response codes.
*/
ZTS_API int ZTCALL zts_central_get_members_of_network(
int *http_response_code, uint64_t nwid);
ZTS_API int ZTCALL zts_central_get_members_of_network(int* http_response_code, uint64_t nwid);
#endif // NO_CENTRAL_API
@@ -1115,14 +1100,15 @@ ZTS_API int ZTCALL zts_central_get_members_of_network(
//----------------------------------------------------------------------------//
/**
* @brief Generates a node identity (public/secret key-pair) and stores it in a user-provided buffer.
* @brief Generates a node identity (public/secret key-pair) and stores it in a user-provided
* buffer.
*
* @param key_pair_str User-provided destination buffer
* @param key_buf_len Length of user-provided destination buffer. Will be set to number of bytes copied.
* @param key_buf_len Length of user-provided destination buffer. Will be set to number of bytes
* copied.
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/
ZTS_API int ZTCALL zts_generate_orphan_identity(
char *key_pair_str, uint16_t *key_buf_len);
ZTS_API int ZTCALL zts_generate_orphan_identity(char* key_pair_str, uint16_t* key_buf_len);
/**
* @brief Verifies that a key-pair is valid for use.
@@ -1136,12 +1122,12 @@ ZTS_API int ZTCALL zts_verify_identity(const char *key_pair_str);
* @brief Copies the current node's identity into a buffer
*
* @param key_pair_str User-provided destination buffer
* @param key_buf_len Length of user-provided destination buffer. Will be set to number of bytes copied.
* @param key_buf_len Length of user-provided destination buffer. Will be set to number of bytes
* copied.
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg.
*/
ZTS_API int ZTCALL zts_get_node_identity(
char *key_pair_str, uint16_t *key_buf_len);
ZTS_API int ZTCALL zts_get_node_identity(char* key_pair_str, uint16_t* key_buf_len);
/**
* @brief Starts the ZeroTier service and notifies user application of events via callback. This
@@ -1154,16 +1140,25 @@ ZTS_API int ZTCALL zts_get_node_identity(
* experiences a problem, `ZTS_ERR_ARG` if invalid arg.
*/
#ifdef ZTS_ENABLE_PYTHON
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len,
PythonDirectorCallbackClass *callback, uint16_t port);
int zts_start_with_identity(
const char* key_pair_str,
uint16_t key_buf_len,
PythonDirectorCallbackClass* callback,
uint16_t port);
#endif
#ifdef ZTS_ENABLE_PINVOKE
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len,
CppCallback callback, uint16_t port);
int zts_start_with_identity(
const char* key_pair_str,
uint16_t key_buf_len,
CppCallback callback,
uint16_t port);
#endif
#ifdef ZTS_C_API_ONLY
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len,
void (*callback)(void *), uint16_t port);
int zts_start_with_identity(
const char* key_pair_str,
uint16_t key_buf_len,
void (*callback)(void*),
uint16_t port);
#endif
/**
@@ -1201,7 +1196,8 @@ ZTS_API int ZTCALL zts_allow_network_caching(uint8_t allowed);
ZTS_API int ZTCALL zts_allow_peer_caching(uint8_t allowed);
/**
* @brief Enable or disable whether the service will read node configuration settings from a local.conf
* @brief Enable or disable whether the service will read node configuration settings from a
* local.conf
*
* Should be called before `zts_start()` if you intend on changing its state.
*
@@ -1231,7 +1227,8 @@ ZTS_API int ZTCALL zts_disable_local_storage(uint8_t disabled);
* experiences a problem, `ZTS_ERR_ARG` if invalid arg.
*/
#ifdef ZTS_ENABLE_PYTHON
ZTS_API int ZTCALL zts_start(const char *path, PythonDirectorCallbackClass *callback, uint16_t port);
ZTS_API int ZTCALL
zts_start(const char* path, PythonDirectorCallbackClass* callback, uint16_t port);
#endif
#ifdef ZTS_ENABLE_PINVOKE
ZTS_API int ZTCALL zts_start(const char* path, CppCallback callback, uint16_t port);
@@ -1319,7 +1316,10 @@ ZTS_API int ZTCALL zts_deorbit(uint64_t moonWorldId);
* @param nodeId Node ID
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/
ZTS_API int ZTCALL zts_get_6plane_addr(struct zts_sockaddr_storage *addr, const uint64_t networkId, const uint64_t nodeId);
ZTS_API int ZTCALL zts_get_6plane_addr(
struct zts_sockaddr_storage* addr,
const uint64_t networkId,
const uint64_t nodeId);
/**
* @brief Compute a `RFC4193` IPv6 address for the given Network ID and Node ID
@@ -1330,7 +1330,9 @@ ZTS_API int ZTCALL zts_get_6plane_addr(struct zts_sockaddr_storage *addr, const
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/
ZTS_API int ZTCALL zts_get_rfc4193_addr(
struct zts_sockaddr_storage *addr, const uint64_t networkId, const uint64_t nodeId);
struct zts_sockaddr_storage* addr,
const uint64_t networkId,
const uint64_t nodeId);
/**
* @brief Compute a `RFC4193` IPv6 address for the given Network ID and Node ID
@@ -1350,19 +1352,19 @@ ZTS_API int ZTCALL zts_get_rfc4193_addr(
* addresses. In addition an ad-hoc network ID encodes an IP port range. UDP packets and TCP SYN
* (connection open) packets are only allowed to destination ports within the encoded range.
*
* For example `ff00160016000000` is an ad-hoc network allowing only SSH, while `ff0000ffff000000` is an
* ad-hoc network allowing any UDP or TCP port.
* For example `ff00160016000000` is an ad-hoc network allowing only SSH, while `ff0000ffff000000`
* is an ad-hoc network allowing any UDP or TCP port.
*
* Keep in mind that these networks are public and anyone in the entire world can join them. Care must
* be taken to avoid exposing vulnerable services or sharing unwanted files or other resources.
* Keep in mind that these networks are public and anyone in the entire world can join them. Care
* must be taken to avoid exposing vulnerable services or sharing unwanted files or other resources.
*
*
* @param startPortOfRange Start of port allowed port range
* @param endPortOfRange End of allowed port range
* @return An Ad-hoc network ID
*/
ZTS_API uint64_t ZTCALL zts_generate_adhoc_nwid_from_range(
uint16_t startPortOfRange, uint16_t endPortOfRange);
ZTS_API uint64_t ZTCALL
zts_generate_adhoc_nwid_from_range(uint16_t startPortOfRange, uint16_t endPortOfRange);
/**
* @brief Platform-agnostic delay (provided for convenience)
@@ -1483,8 +1485,7 @@ ZTS_API int ZTCALL zts_get_all_stats(struct zts_stats *statsDest);
* This function can only be used in debug builds.
* @return ZTS_ERR_OK on success. ZTS_ERR_ARG or ZTS_ERR_NO_RESULT on failure.
*/
ZTS_API int ZTCALL zts_get_protocol_stats(
int protocolType, void *protoStatsDest);
ZTS_API int ZTCALL zts_get_protocol_stats(int protocolType, void* protoStatsDest);
#endif // ZTS_ENABLE_STATS
@@ -1501,8 +1502,7 @@ ZTS_API int ZTCALL zts_get_protocol_stats(
* @return Numbered file descriptor on success, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API int ZTCALL zts_socket(
const int socket_family, const int socket_type, const int protocol);
ZTS_API int ZTCALL zts_socket(const int socket_family, const int socket_type, const int protocol);
/**
* @brief Connect a socket to a remote host
@@ -1513,8 +1513,7 @@ ZTS_API int ZTCALL zts_socket(
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API int ZTCALL zts_connect(
int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen);
ZTS_API int ZTCALL zts_connect(int fd, const struct zts_sockaddr* addr, zts_socklen_t addrlen);
/**
* @brief Connect a socket to a remote host
@@ -1540,8 +1539,7 @@ ZTS_API int ZTCALL zts_connect(
* out with no connection made, `ZTS_ERR_SERVICE` if the node experiences a
* problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API int ZTCALL zts_connect_easy(
int fd, int family, char *ipstr, int port, int timeout_ms);
ZTS_API int ZTCALL zts_connect_easy(int fd, int family, char* ipstr, int port, int timeout_ms);
/**
* @brief Bind a socket to a local address
@@ -1552,8 +1550,7 @@ ZTS_API int ZTCALL zts_connect_easy(
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API int ZTCALL zts_bind(
int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen);
ZTS_API int ZTCALL zts_bind(int fd, const struct zts_sockaddr* addr, zts_socklen_t addrlen);
/**
* @brief Bind a socket to a local address
@@ -1586,8 +1583,7 @@ ZTS_API int ZTCALL zts_listen(int fd, int backlog);
* @return New file descriptor if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API int ZTCALL zts_accept(
int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen);
ZTS_API int ZTCALL zts_accept(int fd, struct zts_sockaddr* addr, zts_socklen_t* addrlen);
/**
* @brief Accept an incoming connection
@@ -1647,8 +1643,11 @@ struct zts_linger {
#define ZTS_TCP_KEEPINTVL 0x0004
#define ZTS_TCP_KEEPCNT 0x0005
// IPPROTO_IPV6 options
#define ZTS_IPV6_CHECKSUM 0x0007 /* RFC3542: calculate and insert the ICMPv6 checksum for raw sockets. */
#define ZTS_IPV6_V6ONLY 0x001b /* RFC3493: boolean control to restrict ZTS_AF_INET6 sockets to IPv6 communications only. */
#define ZTS_IPV6_CHECKSUM \
0x0007 /* RFC3542: calculate and insert the ICMPv6 checksum for raw sockets. */
#define ZTS_IPV6_V6ONLY \
0x001b /* RFC3493: boolean control to restrict ZTS_AF_INET6 sockets to IPv6 communications \
only. */
// UDPLITE options
#define ZTS_UDPLITE_SEND_CSCOV 0x01 /* sender checksum coverage */
#define ZTS_UDPLITE_RECV_CSCOV 0x02 /* minimal receiver checksum coverage */
@@ -1736,8 +1735,8 @@ typedef struct zts_ipv6_mreq {
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API int ZTCALL zts_setsockopt(
int fd, int level, int optname, const void *optval, zts_socklen_t optlen);
ZTS_API int ZTCALL
zts_setsockopt(int fd, int level, int optname, const void* optval, zts_socklen_t optlen);
/**
* @brief Get socket options
@@ -1750,8 +1749,8 @@ ZTS_API int ZTCALL zts_setsockopt(
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API int ZTCALL zts_getsockopt(
int fd, int level, int optname, void *optval, zts_socklen_t *optlen);
ZTS_API int ZTCALL
zts_getsockopt(int fd, int level, int optname, void* optval, zts_socklen_t* optlen);
/**
* @brief Get socket name
@@ -1793,18 +1792,29 @@ ZTS_API int ZTCALL zts_close(int fd);
#undef ZTS_FD_SETSIZE
// Make FD_SETSIZE match NUM_SOCKETS in socket.c
#define ZTS_FD_SETSIZE MEMP_NUM_NETCONN
#define ZTS_FDSETSAFESET(n, code) do { \
if (((n) - LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n) - LWIP_SOCKET_OFFSET) >= 0)) { \
code; }} while(0)
#define ZTS_FDSETSAFESET(n, code) \
do { \
if (((n)-LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) \
&& (((int)(n)-LWIP_SOCKET_OFFSET) >= 0)) { \
code; \
} \
} while (0)
#define ZTS_FDSETSAFEGET(n, code) \
(((n) - LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n) - LWIP_SOCKET_OFFSET) >= 0) ? \
(code) : 0)
(((n)-LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n)-LWIP_SOCKET_OFFSET) >= 0) \
? (code) \
: 0)
#define ZTS_FD_SET(n, p) \
ZTS_FDSETSAFESET(n, (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET)/8] |= (1 << (((n)-LWIP_SOCKET_OFFSET) & 7)))
ZTS_FDSETSAFESET( \
n, \
(p)->fd_bits[((n)-LWIP_SOCKET_OFFSET) / 8] |= (1 << (((n)-LWIP_SOCKET_OFFSET) & 7)))
#define ZTS_FD_CLR(n, p) \
ZTS_FDSETSAFESET(n, (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET)/8] &= ~(1 << (((n)-LWIP_SOCKET_OFFSET) & 7)))
ZTS_FDSETSAFESET( \
n, \
(p)->fd_bits[((n)-LWIP_SOCKET_OFFSET) / 8] &= ~(1 << (((n)-LWIP_SOCKET_OFFSET) & 7)))
#define ZTS_FD_ISSET(n, p) \
ZTS_FDSETSAFEGET(n, (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET)/8] & (1 << (((n)-LWIP_SOCKET_OFFSET) & 7)))
ZTS_FDSETSAFEGET( \
n, \
(p)->fd_bits[((n)-LWIP_SOCKET_OFFSET) / 8] & (1 << (((n)-LWIP_SOCKET_OFFSET) & 7)))
#define ZTS_FD_ZERO(p) memset((void*)(p), 0, sizeof(*(p)))
#elif LWIP_SOCKET_OFFSET
@@ -1813,8 +1823,7 @@ ZTS_API int ZTCALL zts_close(int fd);
#error "external ZTS_FD_SETSIZE too small for number of sockets"
#endif // FD_SET
typedef struct zts_fd_set
{
typedef struct zts_fd_set {
unsigned char fd_bits[(ZTS_FD_SETSIZE + 7) / 8];
} zts_fd_set;
@@ -1834,7 +1843,11 @@ struct zts_timeval {
* @return Number of ready file descriptors on success. ZTS_ERR_SOCKET, ZTS_ERR_SERVICE on failure.
*/
ZTS_API int ZTCALL zts_select(
int nfds, zts_fd_set *readfds, zts_fd_set *writefds, zts_fd_set *exceptfds, struct zts_timeval *timeout);
int nfds,
zts_fd_set* readfds,
zts_fd_set* writefds,
zts_fd_set* exceptfds,
struct zts_timeval* timeout);
// fnctl() commands
#define ZTS_F_GETFL 0x0003
@@ -1871,8 +1884,7 @@ ZTS_API int ZTCALL zts_fcntl(int fd, int cmd, int flags);
typedef unsigned int zts_nfds_t;
struct zts_pollfd
{
struct zts_pollfd {
int fd;
short events;
short revents;
@@ -1925,7 +1937,12 @@ ZTS_API ssize_t ZTCALL zts_send(int fd, const void *buf, size_t len, int flags);
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API ssize_t ZTCALL zts_sendto(
int fd, const void *buf, size_t len, int flags, const struct zts_sockaddr *addr, zts_socklen_t addrlen);
int fd,
const void* buf,
size_t len,
int flags,
const struct zts_sockaddr* addr,
zts_socklen_t addrlen);
struct zts_iovec {
void* iov_base;
@@ -1983,7 +2000,12 @@ ZTS_API ssize_t ZTCALL zts_recv(int fd, void *buf, size_t len, int flags);
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/
ZTS_API ssize_t ZTCALL zts_recvfrom(
int fd, void *buf, size_t len, int flags, struct zts_sockaddr *addr, zts_socklen_t *addrlen);
int fd,
void* buf,
size_t len,
int flags,
struct zts_sockaddr* addr,
zts_socklen_t* addrlen);
/**
* @brief Receive a message from remote host
@@ -2370,8 +2392,8 @@ int zts_ipaddr_aton(const char *cp, zts_ip_addr *addr);
* @param size Size of the destination buffer
* @return On success, returns a non-null pointer to the destination character array
*/
ZTS_API const char * ZTCALL zts_inet_ntop(
int family, const void *src, char *dst, zts_socklen_t size);
ZTS_API const char* ZTCALL
zts_inet_ntop(int family, const void* src, char* dst, zts_socklen_t size);
/**
* Convert C-string IPv4 and IPv6 addresses to binary form.
@@ -2390,11 +2412,16 @@ ZTS_API int ZTCALL zts_inet_pton(int family, const char *src, void *dst);
* @param src_ipstr Source IP string
* @param port Port
* @param dest_addr Pointer to destination structure `zts_sockaddr_in` or `zts_sockaddr_in6`
* @param addrlen Size of destination structure. Value-result: Will be set to actual size of data available
* @param addrlen Size of destination structure. Value-result: Will be set to actual size of data
* available
* @return return `ZTS_ERR_OK` on success, `ZTS_ERR_ARG` if invalid argument
*/
int ipstr2sockaddr(
int family, char *src_ipstr, int port, struct zts_sockaddr *dest_addr, zts_socklen_t *addrlen);
int family,
char* src_ipstr,
int port,
struct zts_sockaddr* dest_addr,
zts_socklen_t* addrlen);
#ifdef __cplusplus
} // extern "C"

View File

@@ -16,15 +16,15 @@
#ifdef ZTS_ENABLE_CENTRAL_API
#include <stdio.h>
#include "Debug.hpp"
#include "Mutex.hpp"
#include "ZeroTierSockets.h"
#include <curl/curl.h>
#include <string.h>
#include <iomanip>
#include <iostream>
#include "Mutex.hpp"
#include "Debug.hpp"
#include "ZeroTierSockets.h"
#include <stdio.h>
#include <string.h>
char api_url[ZTS_CENRTAL_MAX_URL_LEN];
char api_token[ZTS_CENTRAL_TOKEN_LEN + 1];
@@ -76,7 +76,10 @@ void zts_central_clear_resp_buf()
}
int zts_central_init(
const char *url_str, const char *token_str, char *resp_buf, uint32_t resp_buf_len)
const char* url_str,
const char* token_str,
char* resp_buf,
uint32_t resp_buf_len)
{
_access_modes = ZTS_CENTRAL_READ; // Defauly read-only
_bIsVerbose = 0; // Default disable libcurl verbose output
@@ -93,14 +96,16 @@ int zts_central_init(
int url_len = strlen(url_str);
if (url_len < 3 || url_len > ZTS_CENRTAL_MAX_URL_LEN) {
return ZTS_ERR_ARG;
} else {
}
else {
memset(api_url, 0, ZTS_CENRTAL_MAX_URL_LEN);
memcpy(api_url, url_str, url_len);
}
int token_len = strlen(token_str);
if (token_len != ZTS_CENTRAL_TOKEN_LEN) {
return ZTS_ERR_ARG;
} else {
}
else {
memset(api_token, 0, ZTS_CENTRAL_TOKEN_LEN);
memcpy(api_token, token_str, token_len);
}
@@ -113,8 +118,13 @@ void zts_central_cleanup()
curl_global_cleanup();
}
int _central_req(int request_type, char *central_str,
char *api_route_str, char *token_str, int *response_code, char *post_data)
int _central_req(
int request_type,
char* central_str,
char* api_route_str,
char* token_str,
int* response_code,
char* post_data)
{
int err = ZTS_ERR_OK;
if (! _bInit) {
@@ -196,7 +206,8 @@ int _central_req(int request_type, char *central_str,
DEBUG_INFO("Req. took %f second(s). HTTP code (%ld)", elapsed_time, hrc);
*response_code = hrc;
// curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
} else {
}
else {
DEBUG_ERROR("%s", curl_easy_strerror(res));
err = ZTS_ERR_SERVICE;
}
@@ -216,44 +227,38 @@ int zts_get_last_resp_buf(char *dest_buffer, int dest_buf_len)
int zts_central_get_status(int* resp_code)
{
return _central_req(
ZTS_HTTP_GET, api_url, (char*)"/api/status", api_token, resp_code, NULL);
return _central_req(ZTS_HTTP_GET, api_url, (char*)"/api/status", api_token, resp_code, NULL);
}
int zts_central_get_self(int* resp_code)
{
return _central_req(
ZTS_HTTP_GET, api_url, (char*)"/api/self", api_token, resp_code, NULL);
return _central_req(ZTS_HTTP_GET, api_url, (char*)"/api/self", api_token, resp_code, NULL);
}
int zts_central_get_network(int* resp_code, uint64_t nwid)
{
char req[64];
sprintf(req, "/api/network/%llx", nwid);
return _central_req(
ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL);
return _central_req(ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL);
}
int zts_central_update_network(int* resp_code, uint64_t nwid)
{
char req[64];
sprintf(req, "/api/network/%llx", nwid);
return _central_req(
ZTS_HTTP_POST, api_url, req, api_token, resp_code, NULL);
return _central_req(ZTS_HTTP_POST, api_url, req, api_token, resp_code, NULL);
}
int zts_central_delete_network(int* resp_code, uint64_t nwid)
{
char req[64];
sprintf(req, "/api/network/%llx", nwid);
return _central_req(
ZTS_HTTP_DELETE, api_url, req, api_token, resp_code, NULL);
return _central_req(ZTS_HTTP_DELETE, api_url, req, api_token, resp_code, NULL);
}
int zts_central_get_networks(int* resp_code)
{
return _central_req(
ZTS_HTTP_GET, api_url, (char*)"/api/network", api_token, resp_code, NULL);
return _central_req(ZTS_HTTP_GET, api_url, (char*)"/api/network", api_token, resp_code, NULL);
}
int zts_central_get_member(int* resp_code, uint64_t nwid, uint64_t nodeid)
@@ -263,24 +268,20 @@ int zts_central_get_member(int *resp_code, uint64_t nwid, uint64_t nodeid)
}
char req[64];
sprintf(req, "/api/network/%llx/member/%llx", nwid, nodeid);
return _central_req(
ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL);
return _central_req(ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL);
}
int zts_central_update_member(
int *resp_code, uint64_t nwid, uint64_t nodeid, char *post_data)
int zts_central_update_member(int* resp_code, uint64_t nwid, uint64_t nodeid, char* post_data)
{
if (nwid == 0 || nodeid == 0 || post_data == NULL) {
return ZTS_ERR_ARG;
}
char req[64];
sprintf(req, "/api/network/%llx/member/%llx", nwid, nodeid);
return _central_req(
ZTS_HTTP_POST, api_url, req, api_token, resp_code, post_data);
return _central_req(ZTS_HTTP_POST, api_url, req, api_token, resp_code, post_data);
}
int zts_central_set_node_auth(
int *resp_code, uint64_t nwid, uint64_t nodeid, uint8_t is_authed)
int zts_central_set_node_auth(int* resp_code, uint64_t nwid, uint64_t nodeid, uint8_t is_authed)
{
if (is_authed != 0 && is_authed != 1) {
return ZTS_ERR_ARG;
@@ -299,8 +300,7 @@ int zts_central_get_members_of_network(int *resp_code, uint64_t nwid)
{
char req[64];
sprintf(req, "/api/network/%llx/member", nwid);
return _central_req(
ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL);
return _central_req(ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL);
}
#ifdef __cplusplus

View File

@@ -17,21 +17,20 @@
* Node / Network control interface
*/
#include "Constants.hpp"
#include "Debug.hpp"
#include "Events.hpp"
#include "Mutex.hpp"
#include "Node.hpp"
#include "NodeService.hpp"
#include "OSUtils.hpp"
#include "Signals.hpp"
#include "VirtualTap.hpp"
#include "ZeroTierSockets.h"
#include <inttypes.h>
#include <sys/types.h>
#include "Constants.hpp"
#include "Node.hpp"
#include "Mutex.hpp"
#include "OSUtils.hpp"
#include "ZeroTierSockets.h"
#include "Debug.hpp"
#include "NodeService.hpp"
#include "VirtualTap.hpp"
#include "Events.hpp"
#include "Signals.hpp"
using namespace ZeroTier;
#ifdef ZTS_ENABLE_JAVA
@@ -47,8 +46,7 @@ WSADATA wsaData;
#define ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS 1
#endif
namespace ZeroTier
{
namespace ZeroTier {
extern NodeService* service;
extern Mutex serviceLock;
#ifdef ZTS_ENABLE_PYTHON
@@ -71,7 +69,7 @@ namespace ZeroTier
jmethodID _userCallbackMethodRef = NULL;
#endif
extern uint8_t _serviceStateFlags;
}
} // namespace ZeroTier
#ifdef __cplusplus
extern "C" {
@@ -124,16 +122,25 @@ int zts_get_node_identity(char *key_pair_str, uint16_t *key_buf_len)
// TODO: This logic should be further generalized in the next API redesign
#ifdef ZTS_ENABLE_PYTHON
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len,
PythonDirectorCallbackClass *callback, uint16_t port)
int zts_start_with_identity(
const char* key_pair_str,
uint16_t key_buf_len,
PythonDirectorCallbackClass* callback,
uint16_t port)
#endif
#ifdef ZTS_ENABLE_PINVOKE
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len,
CppCallback callback, uint16_t port)
int zts_start_with_identity(
const char* key_pair_str,
uint16_t key_buf_len,
CppCallback callback,
uint16_t port)
#endif
#ifdef ZTS_C_API_ONLY
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len,
void (*callback)(void *), uint16_t port)
int zts_start_with_identity(
const char* key_pair_str,
uint16_t key_buf_len,
void (*callback)(void*),
uint16_t port)
#endif
{
if (! zts_verify_identity(key_pair_str)) {
@@ -323,7 +330,11 @@ int zts_start(const char *path, void (*callback)(void *), uint16_t port)
#ifdef ZTS_ENABLE_JAVA
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_start(
JNIEnv *env, jobject thisObj, jstring path, jobject callback, jint port)
JNIEnv* env,
jobject thisObj,
jstring path,
jobject callback,
jint port)
{
if (! path) {
return ZTS_ERR_ARG;
@@ -333,7 +344,8 @@ JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_start(
DEBUG_ERROR("Couldn't find class for ZeroTierEventListener instance");
return ZTS_ERR_ARG;
}
jmethodID eventListenerCallbackMethod = env->GetMethodID(eventListenerClass, "onZeroTierEvent", "(JI)V");
jmethodID eventListenerCallbackMethod =
env->GetMethodID(eventListenerClass, "onZeroTierEvent", "(JI)V");
if (eventListenerCallbackMethod == NULL) {
DEBUG_ERROR("Couldn't find onZeroTierEvent method");
return ZTS_ERR_ARG;
@@ -366,8 +378,7 @@ int zts_stop()
return ZTS_ERR_SERVICE;
}
#ifdef ZTS_ENABLE_JAVA
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_stop(
JNIEnv *env, jobject thisObj)
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_stop(JNIEnv* env, jobject thisObj)
{
zts_stop();
}
@@ -414,8 +425,7 @@ int zts_restart()
#endif
}
#ifdef ZTS_ENABLE_JAVA
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_restart(
JNIEnv *env, jobject thisObj)
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_restart(JNIEnv* env, jobject thisObj)
{
zts_restart();
}
@@ -436,8 +446,7 @@ int zts_free()
return err;
}
#ifdef ZTS_ENABLE_JAVA
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_free(
JNIEnv *env, jobject thisObj)
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_free(JNIEnv* env, jobject thisObj)
{
zts_free();
}
@@ -448,8 +457,7 @@ JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_free(
* Called from Java, saves a static reference to the VM so it can be used
* later to call a user-specified callback method from C.
*/
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_init(
JNIEnv *env, jobject thisObj)
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_init(JNIEnv* env, jobject thisObj)
{
jint rs = env->GetJavaVM(&jvm);
return rs != JNI_OK ? ZTS_ERR_GENERAL : ZTS_ERR_OK;
@@ -468,8 +476,8 @@ int zts_join(const uint64_t networkId)
return ZTS_ERR_OK;
}
#ifdef ZTS_ENABLE_JAVA
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_join(
JNIEnv *env, jobject thisObj, jlong networkId)
JNIEXPORT jint JNICALL
Java_com_zerotier_libzt_ZeroTier_join(JNIEnv* env, jobject thisObj, jlong networkId)
{
return zts_join((uint64_t)networkId);
}
@@ -487,8 +495,8 @@ int zts_leave(const uint64_t networkId)
return ZTS_ERR_OK;
}
#ifdef ZTS_ENABLE_JAVA
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_leave(
JNIEnv *env, jobject thisObj, jlong networkId)
JNIEXPORT jint JNICALL
Java_com_zerotier_libzt_ZeroTier_leave(JNIEnv* env, jobject thisObj, jlong networkId)
{
return zts_leave((uint64_t)networkId);
}
@@ -500,7 +508,8 @@ int zts_orbit(uint64_t moonWorldId, uint64_t moonSeed)
void* tptr = NULL;
if (! _canPerformServiceOperation()) {
return ZTS_ERR_SERVICE;
} else {
}
else {
service->getNode()->orbit(tptr, moonWorldId, moonSeed);
}
return ZTS_ERR_OK;
@@ -514,7 +523,8 @@ int zts_deorbit(uint64_t moonWorldId)
void* tptr = NULL;
if (! _canPerformServiceOperation()) {
return ZTS_ERR_SERVICE;
} else {
}
else {
service->getNode()->deorbit(tptr, moonWorldId);
}
return ZTS_ERR_OK;
@@ -522,7 +532,10 @@ int zts_deorbit(uint64_t moonWorldId)
#ifdef ZTS_ENABLE_JAVA
#endif
int zts_get_6plane_addr(struct zts_sockaddr_storage *addr, const uint64_t networkId, const uint64_t nodeId)
int zts_get_6plane_addr(
struct zts_sockaddr_storage* addr,
const uint64_t networkId,
const uint64_t nodeId)
{
if (! addr || ! networkId || ! nodeId) {
return ZTS_ERR_ARG;
@@ -533,7 +546,10 @@ int zts_get_6plane_addr(struct zts_sockaddr_storage *addr, const uint64_t networ
return ZTS_ERR_OK;
}
int zts_get_rfc4193_addr(struct zts_sockaddr_storage *addr, const uint64_t networkId, const uint64_t nodeId)
int zts_get_rfc4193_addr(
struct zts_sockaddr_storage* addr,
const uint64_t networkId,
const uint64_t nodeId)
{
if (! addr || ! networkId || ! nodeId) {
return ZTS_ERR_ARG;

View File

@@ -25,8 +25,8 @@
//////////////////////////////////////////////////////////////////////////////
#if defined(__linux__) || defined(__APPLE__)
#include <sys/syscall.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>
#endif
#include <string.h>
@@ -42,7 +42,9 @@
#if defined(__APPLE__)
#include "TargetConditionals.h"
#endif
#if defined(ZT_COLOR) && !defined(_WIN32) && !defined(__ANDROID__) && !defined(TARGET_OS_IPHONE) && !defined(TARGET_IPHONE_SIMULATOR) && !defined(__APP_FRAMEWORK__)
#if defined(ZT_COLOR) && ! defined(_WIN32) && ! defined(__ANDROID__) \
&& ! defined(TARGET_OS_IPHONE) && ! defined(TARGET_IPHONE_SIMULATOR) \
&& ! defined(__APP_FRAMEWORK__)
#define ZT_RED "\x1B[31m"
#define ZT_GRN "\x1B[32m"
#define ZT_YEL "\x1B[33m"
@@ -76,14 +78,33 @@
//
#if ZT_MSG_ERROR == true
#if defined(__ANDROID__)
#define DEBUG_ERROR(fmt, args...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, ZT_LOG_TAG, \
"%17s:%5d:%20s: " fmt "\n", ZT_FILENAME, __LINE__, __FUNCTION__, ##args))
#define DEBUG_ERROR(fmt, args...) \
((void)__android_log_print( \
ANDROID_LOG_VERBOSE, \
ZT_LOG_TAG, \
"%17s:%5d:%20s: " fmt "\n", \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
##args))
#elif defined(_WIN32)
#define DEBUG_ERROR(fmt, ...) fprintf(stderr, ZT_RED "%17s:%5d:%25s: " fmt "\n" \
ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, __VA_ARGS__)
#define DEBUG_ERROR(fmt, ...) \
fprintf( \
stderr, \
ZT_RED "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
__VA_ARGS__)
#else
#define DEBUG_ERROR(fmt, args ...) fprintf(stderr, ZT_RED "%17s:%5d:%25s: " fmt "\n" \
ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args)
#define DEBUG_ERROR(fmt, args...) \
fprintf( \
stderr, \
ZT_RED "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
##args)
#endif
#else
#define DEBUG_ERROR(fmt, args...)
@@ -92,14 +113,33 @@
//
#if ZT_MSG_TEST == true
#if defined(__ANDROID__)
#define DEBUG_TEST(fmt, args...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, ZT_LOG_TAG, \
"%17s:%5d:%25s: " fmt "\n", ZT_FILENAME, __LINE__, __FUNCTION__, ##args))
#define DEBUG_TEST(fmt, args...) \
((void)__android_log_print( \
ANDROID_LOG_VERBOSE, \
ZT_LOG_TAG, \
"%17s:%5d:%25s: " fmt "\n", \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
##args))
#elif defined(_WIN32)
#define DEBUG_TEST(fmt, ...) fprintf(stderr, ZT_CYN "%17s:%5d:%25s: " fmt "\n" \
ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, __VA_ARGS__)
#define DEBUG_TEST(fmt, ...) \
fprintf( \
stderr, \
ZT_CYN "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
__VA_ARGS__)
#else
#define DEBUG_TEST(fmt, args ...) fprintf(stderr, ZT_CYN "%17s:%5d:%25s: " fmt "\n" \
ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args)
#define DEBUG_TEST(fmt, args...) \
fprintf( \
stderr, \
ZT_CYN "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
##args)
#endif
#else
#define DEBUG_TEST(fmt, args...)
@@ -108,14 +148,33 @@
//
#if ZT_MSG_INFO == true
#if defined(__ANDROID__)
#define DEBUG_INFO(fmt, args...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, ZT_LOG_TAG, \
"%17s:%5d:%20s: " fmt "\n", ZT_FILENAME, __LINE__, __FUNCTION__, ##args))
#define DEBUG_INFO(fmt, args...) \
((void)__android_log_print( \
ANDROID_LOG_VERBOSE, \
ZT_LOG_TAG, \
"%17s:%5d:%20s: " fmt "\n", \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
##args))
#elif defined(_WIN32)
#define DEBUG_INFO(fmt, ...) fprintf(stderr, ZT_WHT "%17s:%5d:%25s: " fmt "\n" \
ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, __VA_ARGS__)
#define DEBUG_INFO(fmt, ...) \
fprintf( \
stderr, \
ZT_WHT "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
__VA_ARGS__)
#else
#define DEBUG_INFO(fmt, args ...) fprintf(stderr, ZT_WHT "%17s:%5d:%25s: " fmt "\n" \
ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args)
#define DEBUG_INFO(fmt, args...) \
fprintf( \
stderr, \
ZT_WHT "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
##args)
#endif
#else
#define DEBUG_INFO(fmt, args...)
@@ -124,14 +183,33 @@
//
#if ZT_MSG_TRANSFER == true
#if defined(__ANDROID__)
#define DEBUG_TRANS(fmt, args...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, ZT_LOG_TAG, \
"%17s:%5d:%25s: " fmt "\n", ZT_FILENAME, __LINE__, __FUNCTION__, ##args))
#define DEBUG_TRANS(fmt, args...) \
((void)__android_log_print( \
ANDROID_LOG_VERBOSE, \
ZT_LOG_TAG, \
"%17s:%5d:%25s: " fmt "\n", \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
##args))
#elif defined(_WIN32)
#define DEBUG_TRANS(fmt, ...) fprintf(stderr, ZT_GRN "%17s:%5d:%25s: " fmt "\n" \
ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, __VA_ARGS__)
#define DEBUG_TRANS(fmt, ...) \
fprintf( \
stderr, \
ZT_GRN "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
__VA_ARGS__)
#else
#define DEBUG_TRANS(fmt, args ...) fprintf(stderr, ZT_GRN "%17s:%5d:%25s: " fmt "\n" \
ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args)
#define DEBUG_TRANS(fmt, args...) \
fprintf( \
stderr, \
ZT_GRN "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \
ZT_FILENAME, \
__LINE__, \
__FUNCTION__, \
##args)
#endif
#else
#define DEBUG_TRANS(fmt, args...)

View File

@@ -24,16 +24,16 @@
#endif
#include "Constants.hpp"
#include "Node.hpp"
#include "OSUtils.hpp"
#include "Debug.hpp"
#include "Events.hpp"
#include "ZeroTierSockets.h"
#include "Node.hpp"
#include "NodeService.hpp"
#include "OSUtils.hpp"
#include "ZeroTierSockets.h"
#define NODE_EVENT_TYPE(code) code >= ZTS_EVENT_NODE_UP&& code <= ZTS_EVENT_NODE_NORMAL_TERMINATION
#define NETWORK_EVENT_TYPE(code) code >= ZTS_EVENT_NETWORK_NOT_FOUND && code <= ZTS_EVENT_NETWORK_UPDATE
#define NETWORK_EVENT_TYPE(code) \
code >= ZTS_EVENT_NETWORK_NOT_FOUND&& code <= ZTS_EVENT_NETWORK_UPDATE
#define STACK_EVENT_TYPE(code) code >= ZTS_EVENT_STACK_UP&& code <= ZTS_EVENT_STACK_DOWN
#define NETIF_EVENT_TYPE(code) code >= ZTS_EVENT_NETIF_UP&& code <= ZTS_EVENT_NETIF_LINK_DOWN
#define PEER_EVENT_TYPE(code) code >= ZTS_EVENT_PEER_DIRECT&& code <= ZTS_EVENT_PEER_PATH_DEAD
@@ -43,7 +43,9 @@
#ifdef ZTS_ENABLE_PYTHON
#include "Python.h"
PythonDirectorCallbackClass* _userEventCallback = NULL;
void PythonDirectorCallbackClass::on_zerotier_event(struct zts_callback_msg *msg) { }
void PythonDirectorCallbackClass::on_zerotier_event(struct zts_callback_msg* msg)
{
}
#endif
namespace ZeroTier {
@@ -72,17 +74,23 @@ void _enqueueEvent(int16_t eventCode, void *arg)
if (NODE_EVENT_TYPE(eventCode)) {
msg->node = (struct zts_node_details*)arg;
} if (NETWORK_EVENT_TYPE(eventCode)) {
}
if (NETWORK_EVENT_TYPE(eventCode)) {
msg->network = (struct zts_network_details*)arg;
} if (STACK_EVENT_TYPE(eventCode)) {
}
if (STACK_EVENT_TYPE(eventCode)) {
/* nothing to convey to user */
} if (NETIF_EVENT_TYPE(eventCode)) {
}
if (NETIF_EVENT_TYPE(eventCode)) {
msg->netif = (struct zts_netif_details*)arg;
} if (ROUTE_EVENT_TYPE(eventCode)) {
}
if (ROUTE_EVENT_TYPE(eventCode)) {
msg->route = (struct zts_virtual_network_route*)arg;
} if (PEER_EVENT_TYPE(eventCode)) {
}
if (PEER_EVENT_TYPE(eventCode)) {
msg->peer = (struct zts_peer_details*)arg;
} if (ADDR_EVENT_TYPE(eventCode)) {
}
if (ADDR_EVENT_TYPE(eventCode)) {
msg->addr = (struct zts_addr_details*)arg;
}
@@ -100,12 +108,24 @@ void _freeEvent(struct zts_callback_msg *msg)
if (! msg) {
return;
}
if (msg->node) { delete msg->node; }
if (msg->network) { delete msg->network; }
if (msg->netif) { delete msg->netif; }
if (msg->route) { delete msg->route; }
if (msg->peer) { delete msg->peer; }
if (msg->addr) { delete msg->addr; }
if (msg->node) {
delete msg->node;
}
if (msg->network) {
delete msg->network;
}
if (msg->netif) {
delete msg->netif;
}
if (msg->route) {
delete msg->route;
}
if (msg->peer) {
delete msg->peer;
}
if (msg->addr) {
delete msg->addr;
}
}
void _passDequeuedEventToUser(struct zts_callback_msg* msg)
@@ -184,10 +204,7 @@ void _clearRegisteredCallback()
int _canPerformServiceOperation()
{
return service
&& service->isRunning()
&& service->getNode()
&& service->getNode()->online()
return service && service->isRunning() && service->getNode() && service->getNode()->online()
&& ! _getState(ZTS_STATE_FREE_CALLED);
}
@@ -202,10 +219,8 @@ void _setState(uint8_t newFlags)
return; // No effect. Not allowed to set this flag manually
}
SET_FLAGS(newFlags);
if ( GET_FLAGS(ZTS_STATE_NODE_RUNNING)
&& GET_FLAGS(ZTS_STATE_STACK_RUNNING)
&& !(GET_FLAGS(ZTS_STATE_FREE_CALLED)))
{
if (GET_FLAGS(ZTS_STATE_NODE_RUNNING) && GET_FLAGS(ZTS_STATE_STACK_RUNNING)
&& ! (GET_FLAGS(ZTS_STATE_FREE_CALLED))) {
SET_FLAGS(ZTS_STATE_NET_SERVICE_RUNNING);
}
else {
@@ -219,10 +234,8 @@ void _clrState(uint8_t newFlags)
return; // No effect. Not allowed to set this flag manually
}
CLR_FLAGS(newFlags);
if ( GET_FLAGS(ZTS_STATE_NODE_RUNNING)
&& GET_FLAGS(ZTS_STATE_STACK_RUNNING)
&& !(GET_FLAGS(ZTS_STATE_FREE_CALLED)))
{
if (GET_FLAGS(ZTS_STATE_NODE_RUNNING) && GET_FLAGS(ZTS_STATE_STACK_RUNNING)
&& ! (GET_FLAGS(ZTS_STATE_FREE_CALLED))) {
SET_FLAGS(ZTS_STATE_NET_SERVICE_RUNNING);
}
else {
@@ -244,8 +257,7 @@ void *_runCallbacks(void *thread_id)
#if defined(__APPLE__)
pthread_setname_np(ZTS_EVENT_CALLBACK_THREAD_NAME);
#endif
while (_getState(ZTS_STATE_CALLBACKS_RUNNING) || _callbackMsgQueue.size_approx() > 0)
{
while (_getState(ZTS_STATE_CALLBACKS_RUNNING) || _callbackMsgQueue.size_approx() > 0) {
struct zts_callback_msg* msg;
size_t sz = _callbackMsgQueue.size_approx();
for (size_t j = 0; j < sz; j++) {

View File

@@ -20,11 +20,11 @@
#ifndef ZT_EVENTS_HPP
#define ZT_EVENTS_HPP
#include <string>
#include "Constants.hpp"
#include "ZeroTierSockets.h"
#include <string>
#ifdef __WINDOWS__
#include <BaseTsd.h>
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -20,15 +20,15 @@
#ifndef ZT_NODE_SERVICE_HPP
#define ZT_NODE_SERVICE_HPP
#include <string>
#include <vector>
#include "Constants.hpp"
#include "Node.hpp"
#include "InetAddress.hpp"
#include "Mutex.hpp"
#include "Node.hpp"
#include "ZeroTierSockets.h"
#include <string>
#include <vector>
#define ZTS_SERVICE_THREAD_NAME "ZTServiceThread"
#define ZTS_EVENT_CALLBACK_THREAD_NAME "ZTEventCallbackThread"
// Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
@@ -48,10 +48,8 @@ namespace ZeroTier {
/**
* Local service for ZeroTier One as system VPN/NFV provider
*/
class NodeService
{
class NodeService {
public:
uint16_t _userProvidedPort;
std::string _userProvidedPath;
char _userProvidedPublicIdentity[ZT_IDENTITY_STRING_BUFFER_LENGTH];
@@ -60,8 +58,7 @@ public:
/**
* Returned by node main if/when it terminates
*/
enum ReasonForTermination
{
enum ReasonForTermination {
/**
* Instance is still running
*/
@@ -86,8 +83,7 @@ public:
/**
* Local settings for each network
*/
struct NetworkSettings
{
struct NetworkSettings {
/**
* Allow this network to configure IP addresses and routes?
*/
@@ -152,7 +148,8 @@ public:
virtual std::string fatalErrorMessage() const = 0;
/**
* @return System device name corresponding with a given ZeroTier network ID or empty string if not opened yet or network ID not found
* @return System device name corresponding with a given ZeroTier network ID or empty string if
* not opened yet or network ID not found
*/
virtual std::string portDeviceName(uint64_t nwid) const = 0;
@@ -192,18 +189,27 @@ public:
/**
* @return True if service is still running
*/
inline bool isRunning() const { return (this->reasonForTermination() == ONE_STILL_RUNNING); }
inline bool isRunning() const
{
return (this->reasonForTermination() == ONE_STILL_RUNNING);
}
protected:
NodeService() {}
NodeService()
{
}
private:
NodeService(const NodeService &one) {}
inline NodeService &operator=(const NodeService &one) { return *this; }
NodeService(const NodeService& one)
{
}
inline NodeService& operator=(const NodeService& one)
{
return *this;
}
};
struct serviceParameters
{
struct serviceParameters {
int port;
std::string path;
char publicIdentityStr[ZT_IDENTITY_STRING_BUFFER_LENGTH];

View File

@@ -28,12 +28,13 @@
#ifdef ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS
#include "ZeroTierSockets.h"
#include "Signals.hpp"
#include <signal.h>
#include <execinfo.h>
#include "ZeroTierSockets.h"
#include <cstdlib>
#include <execinfo.h>
#include <signal.h>
void _signal_handler(int signal)
{

View File

@@ -18,14 +18,14 @@
*/
#include "lwip/sockets.h"
#include "lwip/def.h"
#include "lwip/inet.h"
#include "lwip/stats.h"
#include "lwip/netdb.h"
#include "lwip/dns.h"
#include "lwip/ip_addr.h"
#include "ZeroTierSockets.h"
#include "lwip/def.h"
#include "lwip/dns.h"
#include "lwip/inet.h"
#include "lwip/ip_addr.h"
#include "lwip/netdb.h"
#include "lwip/stats.h"
#define ZTS_STATE_NODE_RUNNING 0x01
#define ZTS_STATE_STACK_RUNNING 0x02
@@ -66,7 +66,8 @@ int zts_connect(int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen)
return lwip_connect(fd, (sockaddr*)addr, addrlen);
}
int zts_connect_easy(int fd, int family, char *ipstr, int port, int timeout_ms) {
int zts_connect_easy(int fd, int family, char* ipstr, int port, int timeout_ms)
{
if (timeout_ms < 0) {
return ZTS_ERR_ARG;
}
@@ -84,14 +85,12 @@ int zts_connect_easy(int fd, int family, char *ipstr, int port, int timeout_ms)
if (family == ZTS_AF_INET) {
addrlen = sizeof(ss);
ipstr2sockaddr(
family, ipstr, port, (struct zts_sockaddr *)&ss, &addrlen);
ipstr2sockaddr(family, ipstr, port, (struct zts_sockaddr*)&ss, &addrlen);
sa = (struct zts_sockaddr*)&ss;
}
if (family == ZTS_AF_INET6) {
addrlen = sizeof(ss);
ipstr2sockaddr(
family, ipstr, port, (struct zts_sockaddr *)&ss, &addrlen);
ipstr2sockaddr(family, ipstr, port, (struct zts_sockaddr*)&ss, &addrlen);
sa = (struct zts_sockaddr*)&ss;
}
if (addrlen > 0 && sa != NULL) {
@@ -100,8 +99,7 @@ int zts_connect_easy(int fd, int family, char *ipstr, int port, int timeout_ms)
err = zts_connect(fd, sa, addrlen);
zts_delay_ms(connect_delay);
n_tries--;
}
while ((err < 0) && (zts_errno != 0) && (n_tries > 0));
} while ((err < 0) && (zts_errno != 0) && (n_tries > 0));
}
return err;
}
@@ -123,20 +121,19 @@ int zts_bind(int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen)
return lwip_bind(fd, (sockaddr*)addr, addrlen);
}
int zts_bind_easy(int fd, int family, char *ipstr, int port) {
int zts_bind_easy(int fd, int family, char* ipstr, int port)
{
if (family == ZTS_AF_INET) {
struct zts_sockaddr_in in4;
zts_socklen_t addrlen = sizeof(in4);
ipstr2sockaddr(
family, ipstr, port, (struct zts_sockaddr *)&in4, &addrlen);
ipstr2sockaddr(family, ipstr, port, (struct zts_sockaddr*)&in4, &addrlen);
struct zts_sockaddr* sa = (struct zts_sockaddr*)&in4;
return zts_bind(fd, sa, addrlen);
}
if (family == ZTS_AF_INET6) {
struct zts_sockaddr_in6 in6;
zts_socklen_t addrlen = sizeof(in6);
ipstr2sockaddr(
family, ipstr, port, (struct zts_sockaddr *)&in6, &addrlen);
ipstr2sockaddr(family, ipstr, port, (struct zts_sockaddr*)&in6, &addrlen);
struct zts_sockaddr* sa = (struct zts_sockaddr*)&in6;
return zts_bind(fd, sa, addrlen);
}
@@ -174,21 +171,18 @@ int zts_accept_easy(int fd, char *remoteIpStr, int len, int *port)
struct zts_sockaddr* sa = (struct zts_sockaddr*)&ss;
if (sa->sa_family == ZTS_AF_INET) {
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)sa;
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr),
remoteIpStr, ZTS_INET_ADDRSTRLEN);
zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), remoteIpStr, ZTS_INET_ADDRSTRLEN);
*port = ntohs(in4->sin_port);
}
if (sa->sa_family == ZTS_AF_INET6) {
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)sa;
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr),
remoteIpStr, ZTS_INET6_ADDRSTRLEN);
zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), remoteIpStr, ZTS_INET6_ADDRSTRLEN);
*port = ntohs(in6->sin6_port);
}
return acc_fd;
}
int zts_setsockopt(
int fd, int level, int optname, const void *optval,zts_socklen_t optlen)
int zts_setsockopt(int fd, int level, int optname, const void* optval, zts_socklen_t optlen)
{
if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) {
return ZTS_ERR_SERVICE;
@@ -196,8 +190,7 @@ int zts_setsockopt(
return lwip_setsockopt(fd, level, optname, optval, optlen);
}
int zts_getsockopt(
int fd, int level, int optname, void *optval, zts_socklen_t *optlen)
int zts_getsockopt(int fd, int level, int optname, void* optval, zts_socklen_t* optlen)
{
if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) {
return ZTS_ERR_SERVICE;
@@ -244,14 +237,21 @@ int zts_close(int fd)
}
int zts_select(
int nfds, zts_fd_set *readfds, zts_fd_set *writefds, zts_fd_set *exceptfds,
int nfds,
zts_fd_set* readfds,
zts_fd_set* writefds,
zts_fd_set* exceptfds,
struct zts_timeval* timeout)
{
if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) {
return ZTS_ERR_SERVICE;
}
return lwip_select(
nfds, (fd_set*)readfds, (fd_set*)writefds, (fd_set*)exceptfds, (timeval*)timeout);
nfds,
(fd_set*)readfds,
(fd_set*)writefds,
(fd_set*)exceptfds,
(timeval*)timeout);
}
int zts_fcntl(int fd, int cmd, int flags)
@@ -292,8 +292,13 @@ ssize_t zts_send(int fd, const void *buf, size_t len, int flags)
return lwip_send(fd, buf, len, flags);
}
ssize_t zts_sendto(int fd, const void *buf, size_t len, int flags,
const struct zts_sockaddr *addr,zts_socklen_t addrlen)
ssize_t zts_sendto(
int fd,
const void* buf,
size_t len,
int flags,
const struct zts_sockaddr* addr,
zts_socklen_t addrlen)
{
if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) {
return ZTS_ERR_SERVICE;
@@ -328,8 +333,13 @@ ssize_t zts_recv(int fd, void *buf, size_t len, int flags)
return lwip_recv(fd, buf, len, flags);
}
ssize_t zts_recvfrom(int fd, void *buf, size_t len, int flags,
struct zts_sockaddr *addr, zts_socklen_t *addrlen)
ssize_t zts_recvfrom(
int fd,
void* buf,
size_t len,
int flags,
struct zts_sockaddr* addr,
zts_socklen_t* addrlen)
{
if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) {
return ZTS_ERR_SERVICE;
@@ -337,8 +347,7 @@ ssize_t zts_recvfrom(int fd, void *buf, size_t len, int flags,
if (! buf) {
return ZTS_ERR_ARG;
}
return lwip_recvfrom(
fd, buf, len, flags, (sockaddr*)addr, (socklen_t*)addrlen);
return lwip_recvfrom(fd, buf, len, flags, (sockaddr*)addr, (socklen_t*)addrlen);
}
ssize_t zts_recvmsg(int fd, struct zts_msghdr* msg, int flags)
@@ -448,8 +457,7 @@ int zts_ipaddr_aton(const char *cp, zts_ip_addr *addr)
return ipaddr_aton(cp, (ip_addr_t*)addr);
}
const char *zts_inet_ntop(
int family, const void *src, char *dst, zts_socklen_t size)
const char* zts_inet_ntop(int family, const void* src, char* dst, zts_socklen_t size)
{
return lwip_inet_ntop(family, src, dst, size);
}
@@ -460,7 +468,12 @@ int zts_inet_pton(int family, const char *src, void *dst)
}
int ipstr2sockaddr(
int family, char *src_ipstr, int port, struct zts_sockaddr *dest_addr, zts_socklen_t *addrlen) {
int family,
char* src_ipstr,
int port,
struct zts_sockaddr* dest_addr,
zts_socklen_t* addrlen)
{
if (family == ZTS_AF_INET) {
struct zts_sockaddr_in in4;
in4.sin_port = htons(port);
@@ -501,15 +514,15 @@ int ipstr2sockaddr(
* needing to manipulate the content of structures in a non-native language.
*/
int zts_set_no_delay(int fd, int enabled) {
int zts_set_no_delay(int fd, int enabled)
{
if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) {
return ZTS_ERR_SERVICE;
}
if (enabled != 0 && enabled != 1) {
return ZTS_ERR_ARG;
}
return zts_setsockopt(
fd, ZTS_IPPROTO_TCP, ZTS_TCP_NODELAY, (void *)&enabled, sizeof(int));
return zts_setsockopt(fd, ZTS_IPPROTO_TCP, ZTS_TCP_NODELAY, (void*)&enabled, sizeof(int));
}
int zts_get_no_delay(int fd)
@@ -519,14 +532,14 @@ int zts_get_no_delay(int fd)
}
int err, optval = 0;
zts_socklen_t len = sizeof(optval);
if ((err = zts_getsockopt(
fd, ZTS_IPPROTO_TCP, ZTS_TCP_NODELAY, (void *)&optval, &len)) < 0) {
if ((err = zts_getsockopt(fd, ZTS_IPPROTO_TCP, ZTS_TCP_NODELAY, (void*)&optval, &len)) < 0) {
return err;
}
return optval != 0;
}
int zts_set_linger(int fd, int enabled, int value) {
int zts_set_linger(int fd, int enabled, int value)
{
if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) {
return ZTS_ERR_SERVICE;
}
@@ -539,8 +552,7 @@ int zts_set_linger(int fd, int enabled, int value) {
struct zts_linger linger;
linger.l_onoff = enabled;
linger.l_linger = value;
return zts_setsockopt(
fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void *)&linger, sizeof(linger));
return zts_setsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void*)&linger, sizeof(linger));
}
int zts_get_linger_enabled(int fd)
@@ -551,8 +563,7 @@ int zts_get_linger_enabled(int fd)
int err;
struct zts_linger linger;
zts_socklen_t len = sizeof(linger);
if ((err = zts_getsockopt(
fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void *)&linger, &len)) < 0) {
if ((err = zts_getsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void*)&linger, &len)) < 0) {
return err;
}
return linger.l_onoff;
@@ -566,8 +577,7 @@ int zts_get_linger_value(int fd)
int err;
struct zts_linger linger;
zts_socklen_t len = sizeof(linger);
if ((err = zts_getsockopt(
fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void *)&linger, &len)) < 0) {
if ((err = zts_getsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void*)&linger, &len)) < 0) {
return err;
}
return linger.l_linger;
@@ -581,8 +591,7 @@ int zts_set_reuse_addr(int fd, int enabled)
if (enabled != 0 && enabled != 1) {
return ZTS_ERR_ARG;
}
return zts_setsockopt(
fd, ZTS_SOL_SOCKET, ZTS_SO_REUSEADDR, (void *)&enabled, sizeof(enabled));
return zts_setsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_REUSEADDR, (void*)&enabled, sizeof(enabled));
}
int zts_get_reuse_addr(int fd)
@@ -593,8 +602,7 @@ int zts_get_reuse_addr(int fd)
int err;
int optval = 0;
zts_socklen_t optlen = sizeof(optval);
if ((err = zts_getsockopt(
fd, ZTS_SOL_SOCKET, ZTS_SO_REUSEADDR, (void *)&optval, &optlen)) < 0) {
if ((err = zts_getsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_REUSEADDR, (void*)&optval, &optlen)) < 0) {
return err;
}
return optval != 0;
@@ -611,8 +619,7 @@ int zts_set_recv_timeout(int fd, int seconds, int microseconds)
struct timeval tv;
tv.tv_sec = seconds;
tv.tv_usec = microseconds;
return zts_setsockopt(
fd, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, sizeof(tv));
return zts_setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, sizeof(tv));
}
int zts_get_recv_timeout(int fd)
@@ -623,8 +630,7 @@ int zts_get_recv_timeout(int fd)
struct timeval tv;
zts_socklen_t optlen = sizeof(tv);
int err;
if ((err = zts_getsockopt(
fd, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, &optlen)) < 0) {
if ((err = zts_getsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &optlen)) < 0) {
return err;
}
return tv.tv_sec; // TODO microseconds
@@ -641,8 +647,7 @@ int zts_set_send_timeout(int fd, int seconds, int microseconds)
struct timeval tv;
tv.tv_sec = seconds;
tv.tv_usec = microseconds;
return zts_setsockopt(
fd, SOL_SOCKET, SO_SNDTIMEO, (void *)&tv, sizeof(tv));
return zts_setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (void*)&tv, sizeof(tv));
}
int zts_get_send_timeout(int fd)
@@ -653,8 +658,7 @@ int zts_get_send_timeout(int fd)
struct zts_timeval tv;
zts_socklen_t optlen = sizeof(tv);
int err;
if ((err = zts_getsockopt(
fd, SOL_SOCKET, SO_SNDTIMEO, (void *)&tv, &optlen)) < 0) {
if ((err = zts_getsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (void*)&tv, &optlen)) < 0) {
return err;
}
return tv.tv_sec; // TODO microseconds
@@ -668,8 +672,7 @@ int zts_set_send_buf_size(int fd, int size)
if (size < 0) {
return ZTS_ERR_ARG;
}
return zts_setsockopt(
fd, SOL_SOCKET, SO_SNDBUF, (void *)&size, sizeof(int));
return zts_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void*)&size, sizeof(int));
}
int zts_get_send_buf_size(int fd)
@@ -679,8 +682,7 @@ int zts_get_send_buf_size(int fd)
}
int err, optval = 0;
zts_socklen_t optlen = sizeof(optval);
if ((err = zts_getsockopt(
fd, SOL_SOCKET, SO_SNDBUF, (char *)&optval, &optlen)) < 0) {
if ((err = zts_getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&optval, &optlen)) < 0) {
return err;
}
return optval;
@@ -694,8 +696,7 @@ int zts_set_recv_buf_size(int fd, int size)
if (size < 0) {
return ZTS_ERR_ARG;
}
return zts_setsockopt(
fd, SOL_SOCKET, SO_RCVBUF, (void *)&size, sizeof(int));
return zts_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void*)&size, sizeof(int));
}
int zts_get_recv_buf_size(int fd)
@@ -705,8 +706,7 @@ int zts_get_recv_buf_size(int fd)
}
int err, optval = 0;
zts_socklen_t optlen = sizeof(optval);
if ((err = zts_getsockopt(
fd, SOL_SOCKET, SO_RCVBUF, (char *)&optval, &optlen)) < 0) {
if ((err = zts_getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&optval, &optlen)) < 0) {
return err;
}
return optval;
@@ -776,8 +776,7 @@ int zts_set_keepalive(int fd, int enabled)
return ZTS_ERR_ARG;
}
int keepalive = enabled;
return zts_setsockopt(
fd, ZTS_SOL_SOCKET, ZTS_SO_KEEPALIVE, &keepalive , sizeof(keepalive));
return zts_setsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_KEEPALIVE, &keepalive, sizeof(keepalive));
}
int zts_get_keepalive(int fd)
@@ -788,8 +787,7 @@ int zts_get_keepalive(int fd)
int err;
int optval = 0;
zts_socklen_t optlen = sizeof(optval);
if ((err = zts_getsockopt(
fd, ZTS_SOL_SOCKET, ZTS_SO_KEEPALIVE, (void *)&optval, &optlen)) < 0) {
if ((err = zts_getsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_KEEPALIVE, (void*)&optval, &optlen)) < 0) {
return err;
}
return optval != 0;
@@ -850,8 +848,7 @@ int zts_get_protocol_stats(int protocolType, void *protoStatsDest)
return ZTS_ERR_ARG;
}
memset(protoStatsDest, 0, sizeof(struct stats_proto));
switch (protocolType)
{
switch (protocolType) {
case ZTS_STATS_PROTOCOL_LINK:
memcpy(protoStatsDest, &(lwip_stats.link), sizeof(struct stats_proto));
break;
@@ -882,8 +879,7 @@ int zts_get_protocol_stats(int protocolType, void *protoStatsDest)
case ZTS_STATS_PROTOCOL_IP6_FRAG:
memcpy(protoStatsDest, &(lwip_stats.ip6_frag), sizeof(struct stats_proto));
break;
default:
return ZTS_ERR_ARG;
default: return ZTS_ERR_ARG;
}
return ZTS_ERR_OK;
#else

View File

@@ -18,15 +18,14 @@
*/
#include "Constants.hpp"
#include "MAC.hpp"
#include "Mutex.hpp"
#include "InetAddress.hpp"
#include "MAC.hpp"
#include "MulticastGroup.hpp"
#include "lwip/netif.h"
#include "Mutex.hpp"
#include "lwip/etharp.h"
#include "lwip/sys.h"
#include "lwip/ethip6.h"
#include "lwip/netif.h"
#include "lwip/sys.h"
#include "lwip/tcpip.h"
#include "netif/ethernet.h"
@@ -34,14 +33,15 @@
#include "lwip/stats.h"
#endif
#include "Debug.hpp"
#include "Events.hpp"
#include "VirtualTap.hpp"
#include "ZeroTierSockets.h"
#include "Events.hpp"
#include "Debug.hpp"
#if defined(__WINDOWS__)
#include <time.h>
#include "Synchapi.h"
#include <time.h>
#endif
#define ZTS_TAP_THREAD_POLLING_INTERVAL 50
@@ -62,20 +62,28 @@ VirtualTap::VirtualTap(
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) :
_handler(handler),
_homePath(homePath),
_arg(arg),
_initialized(false),
_enabled(true),
_run(true),
_mac(mac),
_mtu(mtu),
_nwid(nwid),
_unixListenSocket((PhySocket *)0),
_phy(this,false,true)
void (*handler)(
void*,
void*,
uint64_t,
const MAC&,
const MAC&,
unsigned int,
unsigned int,
const void*,
unsigned int),
void* arg)
: _handler(handler)
, _homePath(homePath)
, _arg(arg)
, _initialized(false)
, _enabled(true)
, _run(true)
, _mac(mac)
, _mtu(mtu)
, _nwid(nwid)
, _unixListenSocket((PhySocket*)0)
, _phy(this, false, true)
{
memset(vtap_full_name, 0, sizeof(vtap_full_name));
snprintf(vtap_full_name, sizeof(vtap_full_name), "libzt%llx", (unsigned long long)_nwid);
@@ -128,7 +136,9 @@ bool VirtualTap::hasIpv4Addr()
Mutex::Lock _l(_ips_m);
std::vector<InetAddress>::iterator it(_ips.begin());
while (it != _ips.end()) {
if ((*it).isV4()) { return true; }
if ((*it).isV4()) {
return true;
}
++it;
}
return false;
@@ -139,7 +149,9 @@ bool VirtualTap::hasIpv6Addr()
Mutex::Lock _l(_ips_m);
std::vector<InetAddress>::iterator it(_ips.begin());
while (it != _ips.end()) {
if ((*it).isV6()) { return true; }
if ((*it).isV6()) {
return true;
}
++it;
}
return false;
@@ -194,8 +206,12 @@ std::vector<InetAddress> VirtualTap::ips() const
return _ips;
}
void VirtualTap::put(const MAC &from,const MAC &to,unsigned int etherType,
const void *data,unsigned int len)
void VirtualTap::put(
const MAC& from,
const MAC& to,
unsigned int etherType,
const void* data,
unsigned int len)
{
if (len && _enabled) {
_lwip_eth_rx(this, from, to, etherType, data, len);
@@ -212,7 +228,8 @@ void VirtualTap::setFriendlyName(const char *friendlyName)
DEBUG_INFO("%s", friendlyName);
}
void VirtualTap::scanMulticastGroups(std::vector<MulticastGroup> &added,
void VirtualTap::scanMulticastGroups(
std::vector<MulticastGroup>& added,
std::vector<MulticastGroup>& removed)
{
std::vector<MulticastGroup> newGroups;
@@ -228,7 +245,9 @@ void VirtualTap::scanMulticastGroups(std::vector<MulticastGroup> &added,
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) {
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);
}
@@ -240,8 +259,7 @@ void VirtualTap::setMtu(unsigned int mtu)
_mtu = mtu;
}
void VirtualTap::threadMain()
throw()
void VirtualTap::threadMain() throw()
{
fd_set readfds, nullfds;
struct timeval tv;
@@ -273,15 +291,38 @@ void VirtualTap::threadMain()
}
}
void VirtualTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *local_address,
const struct sockaddr *from,void *data,unsigned long len) {}
void VirtualTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
void VirtualTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,
const struct sockaddr *from) {}
void VirtualTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
void VirtualTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
void VirtualTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
void VirtualTap::phyOnUnixClose(PhySocket *sock,void **uptr) {}
void VirtualTap::phyOnDatagram(
PhySocket* sock,
void** uptr,
const struct sockaddr* local_address,
const struct sockaddr* from,
void* data,
unsigned long len)
{
}
void VirtualTap::phyOnTcpConnect(PhySocket* sock, void** uptr, bool success)
{
}
void VirtualTap::phyOnTcpAccept(
PhySocket* sockL,
PhySocket* sockN,
void** uptrL,
void** uptrN,
const struct sockaddr* from)
{
}
void VirtualTap::phyOnTcpClose(PhySocket* sock, void** uptr)
{
}
void VirtualTap::phyOnTcpData(PhySocket* sock, void** uptr, void* data, unsigned long len)
{
}
void VirtualTap::phyOnTcpWritable(PhySocket* sock, void** uptr)
{
}
void VirtualTap::phyOnUnixClose(PhySocket* sock, void** uptr)
{
}
//////////////////////////////////////////////////////////////////////////////
// Netif driver code for lwIP network stack //
@@ -348,8 +389,12 @@ void _lwip_driver_init()
#if defined(__WINDOWS__)
sys_init(); // Required for win32 init of critical sections
#endif
sys_thread_new(ZTS_LWIP_DRIVER_THREAD_NAME, _main_lwip_driver_loop,
NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO);
sys_thread_new(
ZTS_LWIP_DRIVER_THREAD_NAME,
_main_lwip_driver_loop,
NULL,
DEFAULT_THREAD_STACKSIZE,
DEFAULT_THREAD_PRIO);
}
void _lwip_driver_shutdown()
@@ -362,7 +407,9 @@ void _lwip_driver_shutdown()
_clrState(ZTS_STATE_STACK_RUNNING);
// Wait until the main lwIP thread has exited
if (_has_started) {
while (!_has_exited) { zts_delay_ms(LWIP_DRIVER_LOOP_INTERVAL); }
while (! _has_exited) {
zts_delay_ms(LWIP_DRIVER_LOOP_INTERVAL);
}
}
}
@@ -412,22 +459,34 @@ err_t _lwip_eth_tx(struct netif *n, struct pbuf *p)
char flagbuf[32];
memset(&flagbuf, 0, 32);
char macBuf[ZTS_MAC_ADDRSTRLEN], nodeBuf[16];
snprintf(macBuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x",
ethhdr->dest.addr[0], ethhdr->dest.addr[1], ethhdr->dest.addr[2],
ethhdr->dest.addr[3], ethhdr->dest.addr[4], ethhdr->dest.addr[5]);
snprintf(
macBuf,
ZTS_MAC_ADDRSTRLEN,
"%02x:%02x:%02x:%02x:%02x:%02x",
ethhdr->dest.addr[0],
ethhdr->dest.addr[1],
ethhdr->dest.addr[2],
ethhdr->dest.addr[3],
ethhdr->dest.addr[4],
ethhdr->dest.addr[5]);
MAC mac;
mac.setTo(ethhdr->dest.addr, 6);
mac.toAddress(tap->_nwid).toString(nodeBuf);
/*
DEBUG_TRANS("len=%5d dst=%s [%s TX <-- %s] ethertype=0x%04x %s", totalLength, macBuf, nodeBuf, tap->nodeId().c_str(),
Utils::ntoh(ethhdr->type), flagbuf);
DEBUG_TRANS("len=%5d dst=%s [%s TX <-- %s] ethertype=0x%04x %s", totalLength, macBuf,
nodeBuf, tap->nodeId().c_str(), Utils::ntoh(ethhdr->type), flagbuf);
*/
}
return ERR_OK;
}
void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int etherType,
const void *data, unsigned int len)
void _lwip_eth_rx(
VirtualTap* tap,
const MAC& from,
const MAC& to,
unsigned int etherType,
const void* data,
unsigned int len)
{
#ifdef LWIP_STATS
stats_display();
@@ -445,15 +504,22 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int
char flagbuf[32];
memset(&flagbuf, 0, 32);
char macBuf[ZTS_MAC_ADDRSTRLEN], nodeBuf[16];
snprintf(macBuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x",
ethhdr.dest.addr[0], ethhdr.dest.addr[1], ethhdr.dest.addr[2],
ethhdr.dest.addr[3], ethhdr.dest.addr[4], ethhdr.dest.addr[5]);
snprintf(
macBuf,
ZTS_MAC_ADDRSTRLEN,
"%02x:%02x:%02x:%02x:%02x:%02x",
ethhdr.dest.addr[0],
ethhdr.dest.addr[1],
ethhdr.dest.addr[2],
ethhdr.dest.addr[3],
ethhdr.dest.addr[4],
ethhdr.dest.addr[5]);
MAC mac;
mac.setTo(ethhdr.src.addr, 6);
mac.toAddress(tap->_nwid).toString(nodeBuf);
/*
DEBUG_TRANS("len=%5d dst=%s [%s RX --> %s] ethertype=0x%04x %s", len, macBuf, nodeBuf, tap->nodeId().c_str(),
Utils::ntoh(ethhdr.type), flagbuf);
DEBUG_TRANS("len=%5d dst=%s [%s RX --> %s] ethertype=0x%04x %s", len, macBuf, nodeBuf,
tap->nodeId().c_str(), Utils::ntoh(ethhdr.type), flagbuf);
*/
}
@@ -486,7 +552,8 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int
if (Utils::ntoh(ethhdr.type) == 0x800 || Utils::ntoh(ethhdr.type) == 0x806) {
if (tap->netif4) {
if ((err = ((struct netif *)tap->netif4)->input(p, (struct netif *)tap->netif4)) != ERR_OK) {
if ((err = ((struct netif*)tap->netif4)->input(p, (struct netif*)tap->netif4))
!= ERR_OK) {
DEBUG_ERROR("packet input error (%d)", err);
pbuf_free(p);
}
@@ -494,7 +561,8 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int
}
if (Utils::ntoh(ethhdr.type) == 0x86DD) {
if (tap->netif6) {
if ((err = ((struct netif *)tap->netif6)->input(p, (struct netif *)tap->netif6)) != ERR_OK) {
if ((err = ((struct netif*)tap->netif6)->input(p, (struct netif*)tap->netif6))
!= ERR_OK) {
DEBUG_ERROR("packet input error (%d)", err);
pbuf_free(p);
}
@@ -579,13 +647,8 @@ static err_t _netif_init4(struct netif *n)
n->linkoutput = _lwip_eth_tx;
n->output = etharp_output;
n->mtu = std::min(LWIP_MTU, (int)tap->_mtu);
n->flags = NETIF_FLAG_BROADCAST
| NETIF_FLAG_ETHARP
| NETIF_FLAG_ETHERNET
| NETIF_FLAG_IGMP
| NETIF_FLAG_MLD6
| NETIF_FLAG_LINK_UP
| NETIF_FLAG_UP;
n->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP
| NETIF_FLAG_MLD6 | NETIF_FLAG_LINK_UP | NETIF_FLAG_UP;
n->hwaddr_len = sizeof(n->hwaddr);
tap->_mac.copyTo(n->hwaddr, n->hwaddr_len);
return ERR_OK;
@@ -606,13 +669,8 @@ static err_t _netif_init6(struct netif *n)
n->linkoutput = _lwip_eth_tx;
n->output_ip6 = ethip6_output;
n->mtu = std::min(LWIP_MTU, (int)tap->_mtu);
n->flags = NETIF_FLAG_BROADCAST
| NETIF_FLAG_ETHARP
| NETIF_FLAG_ETHERNET
| NETIF_FLAG_IGMP
| NETIF_FLAG_MLD6
| NETIF_FLAG_LINK_UP
| NETIF_FLAG_UP;
n->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP
| NETIF_FLAG_MLD6 | NETIF_FLAG_LINK_UP | NETIF_FLAG_UP;
return ERR_OK;
}
@@ -646,9 +704,16 @@ void _lwip_init_interface(void *tapref, const InetAddress &ip)
netif_add(n, &ip4, &netmask, &gw, (void*)vtap, _netif_init4, tcpip_input);
vtap->netif4 = (void*)n;
UNLOCK_TCPIP_CORE();
snprintf(macbuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x",
n->hwaddr[0], n->hwaddr[1], n->hwaddr[2],
n->hwaddr[3], n->hwaddr[4], n->hwaddr[5]);
snprintf(
macbuf,
ZTS_MAC_ADDRSTRLEN,
"%02x:%02x:%02x:%02x:%02x:%02x",
n->hwaddr[0],
n->hwaddr[1],
n->hwaddr[2],
n->hwaddr[3],
n->hwaddr[4],
n->hwaddr[5]);
/*
char nmbuf[INET6_ADDRSTRLEN];
char ipbuf[INET6_ADDRSTRLEN];
@@ -685,9 +750,16 @@ void _lwip_init_interface(void *tapref, const InetAddress &ip)
netif_add_ip6_address(n, &ip6, NULL);
n->output_ip6 = ethip6_output;
UNLOCK_TCPIP_CORE();
snprintf(macbuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x",
n->hwaddr[0], n->hwaddr[1], n->hwaddr[2],
n->hwaddr[3], n->hwaddr[4], n->hwaddr[5]);
snprintf(
macbuf,
ZTS_MAC_ADDRSTRLEN,
"%02x:%02x:%02x:%02x:%02x:%02x",
n->hwaddr[0],
n->hwaddr[1],
n->hwaddr[2],
n->hwaddr[3],
n->hwaddr[4],
n->hwaddr[5]);
/*
DEBUG_INFO("initialized netif=%p as [mac=%s, addr=%s, tap=%p]", n,
macbuf, ip.toString(ipbuf), vtap);

View File

@@ -39,8 +39,7 @@ struct InetAddress;
* A virtual tap device. The ZeroTier Node Service will create one per
* joined network. It will be destroyed upon leave().
*/
class VirtualTap
{
class VirtualTap {
friend class Phy<VirtualTap*>;
public:
@@ -51,8 +50,16 @@ public:
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 (*handler)(
void*,
void*,
uint64_t,
const MAC&,
const MAC&,
unsigned int,
unsigned int,
const void*,
unsigned int),
void* arg);
~VirtualTap();
@@ -89,8 +96,8 @@ public:
/**
* Presents data to the user-space stack
*/
void put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,
unsigned int len);
void
put(const MAC& from, const MAC& to, unsigned int etherType, const void* data, unsigned int len);
/**
* Get VirtualTap device name (e.g. 'libzt17d72843bc2c5760')
@@ -105,8 +112,8 @@ public:
/**
* Scan multicast groups
*/
void scanMulticastGroups(std::vector<MulticastGroup> &added,
std::vector<MulticastGroup> &removed);
void
scanMulticastGroups(std::vector<MulticastGroup>& added, std::vector<MulticastGroup>& removed);
/**
* Set MTU
@@ -116,14 +123,21 @@ public:
/**
* Calls main network stack loops
*/
void threadMain()
throw();
void threadMain() throw();
/**
* For moving data onto the ZeroTier virtual wire
*/
void (*_handler)(void *, void *, uint64_t, const MAC &, const MAC &, unsigned int, unsigned int,
const void *, unsigned int);
void (*_handler)(
void*,
void*,
uint64_t,
const MAC&,
const MAC&,
unsigned int,
unsigned int,
const void*,
unsigned int);
void* netif4 = NULL;
void* netif6 = NULL;
@@ -166,10 +180,19 @@ public:
// Not used in this implementation //
//////////////////////////////////////////////////////////////////////////////
void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *local_address,
const struct sockaddr *from,void *data,unsigned long len);
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,
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);
@@ -206,16 +229,17 @@ bool _lwip_is_up();
/**
* @brief Initialize network stack semaphores, threads, and timers.
*
* @usage This is called during the initial setup of each VirtualTap but is only allowed to execute once
* @usage This is called during the initial setup of each VirtualTap but is only allowed to execute
* once
*/
void _lwip_driver_init();
/**
* @brief Shutdown the stack as completely as possible (not officially supported by lwIP)
*
* @usage This is to be called after it is determined that no further network activity will take place.
* The tcpip thread will be stopped, all interfaces will be brought down and all resources will
* be deallocated. A full application restart will be required to bring the stack back online.
* @usage This is to be called after it is determined that no further network activity will take
* place. The tcpip thread will be stopped, all interfaces will be brought down and all resources
* will be deallocated. A full application restart will be required to bring the stack back online.
*/
void _lwip_driver_shutdown();
@@ -246,7 +270,8 @@ static void _netif_remove_callback(struct netif *netif);
#endif
/**
* @brief Called when a link is brought up or down (ZTS_EVENT_NETIF_LINK_UP, ZTS_EVENT_NETIF_LINK_DOWN)
* @brief Called when a link is brought up or down (ZTS_EVENT_NETIF_LINK_UP,
* ZTS_EVENT_NETIF_LINK_DOWN)
*/
#if LWIP_NETIF_LINK_CALLBACK
static void _netif_link_callback(struct netif* netif);
@@ -269,10 +294,12 @@ void _lwip_init_interface(void *tapref, const InetAddress &ip);
void _lwip_remove_address_from_netif(void* tapref, const InetAddress& ip);
/**
* @brief Called from the stack, outbound ethernet frames from the network stack enter the ZeroTier virtual wire here.
* @brief Called from the stack, outbound ethernet frames from the network stack enter the ZeroTier
* virtual wire here.
*
* @usage This shall only be called from the stack or the stack driver. Not the application thread.
* @param netif Transmits an outgoing Ethernet fram from the network stack onto the ZeroTier virtual wire
* @param netif Transmits an outgoing Ethernet fram from the network stack onto the ZeroTier virtual
* wire
* @param p A pointer to the beginning of a chain pf struct pbufs
* @return
*/
@@ -289,10 +316,14 @@ err_t _lwip_eth_tx(struct netif *netif, struct pbuf *p);
* @param data Pointer to Ethernet frame
* @param len Length of Ethernet frame
*/
void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int etherType,
const void *data, unsigned int len);
void _lwip_eth_rx(
VirtualTap* tap,
const MAC& from,
const MAC& to,
unsigned int etherType,
const void* data,
unsigned int len);
} // namespace ZeroTier
#endif // _H