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 <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include "ZeroTierSockets.h" struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
struct Node
{ {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} }
bool online; bool online;
bool joinedAtLeastOneNetwork; bool joinedAtLeastOneNetwork;
uint64_t id; uint64_t id;
@@ -115,24 +116,33 @@ void on_zts_event(void *msgPtr)
myNode.online = true; myNode.online = true;
} }
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { 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; myNode.online = false;
} }
// Virtual network events // Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { 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) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
@@ -142,13 +152,15 @@ void on_zts_event(void *msgPtr)
// Network stack events // Network stack events
if (msg->eventCode == ZTS_EVENT_NETIF_UP) { 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->nwid,
msg->netif->mac, msg->netif->mac,
msg->netif->mtu); msg->netif->mtu);
} }
if (msg->eventCode == ZTS_EVENT_NETIF_DOWN) { 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->nwid,
msg->netif->mac); msg->netif->mac);
} }
@@ -158,8 +170,7 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr);
msg->addr->nwid, ipstr);
} }
// Peer events // Peer events
@@ -170,18 +181,22 @@ void on_zts_event(void *msgPtr)
return; return;
} }
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { 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); 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 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 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); uint64_t adhoc_nwid = zts_generate_adhoc_nwid_from_range(adhocStartPort, adhocEndPort);
int err = ZTS_ERR_OK; 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); 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); zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf // If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1); zts_allow_local_conf(1);
@@ -238,7 +256,9 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Waiting for node to come online...\n"); 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]); printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(adhoc_nwid)) != ZTS_ERR_OK) { if ((err = zts_join(adhoc_nwid)) != ZTS_ERR_OK) {
@@ -246,12 +266,16 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Joining network %llx\n", adhoc_nwid); 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 // Idle and just show callback events, stack statistics, etc
printf("Node will now idle...\n"); printf("Node will now idle...\n");
while (true) { zts_delay_ms(1000); } while (true) {
zts_delay_ms(1000);
}
// Shut down service and stack threads // Shut down service and stack threads

View File

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

View File

@@ -2,16 +2,17 @@
* libzt API example * libzt API example
*/ */
#include "ZeroTierSockets.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <string> #include <string>
#include "ZeroTierSockets.h" struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
struct Node
{ {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} }
bool online; bool online;
bool joinedAtLeastOneNetwork; bool joinedAtLeastOneNetwork;
uint64_t id; uint64_t id;
@@ -33,7 +34,8 @@ void on_zts_event(void *msgPtr)
myNode.online = true; myNode.online = true;
} }
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { 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; myNode.online = false;
} }
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
@@ -42,23 +44,33 @@ void on_zts_event(void *msgPtr)
// Virtual network events // Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { 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) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
@@ -71,29 +83,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "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 // Peer events
if (msg->peer) { if (msg->peer) {
@@ -103,18 +125,22 @@ void on_zts_event(void *msgPtr)
return; return;
} }
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { 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); 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 uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
std::string remoteAddr = argv[3]; // Remote application's virtual ZT address 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 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; struct zts_sockaddr_in in4;
in4.sin_port = htons(remotePort); in4.sin_port = htons(remotePort);
@@ -227,9 +254,11 @@ int main(int argc, char **argv)
int err = ZTS_ERR_OK; 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); 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); zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf // If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1); zts_allow_local_conf(1);
@@ -239,7 +268,9 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Waiting for node to come online...\n"); 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]); printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(nwid)) != ZTS_ERR_OK) { 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("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); 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 // Socket-like API example
@@ -265,12 +298,18 @@ int main(int argc, char **argv)
for (;;) { for (;;) {
printf("Connecting to remote host...\n"); printf("Connecting to remote host...\n");
if ((err = zts_connect(fd, (const struct zts_sockaddr*)&in4, sizeof(in4))) < 0) { 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", printf(
fd, err, zts_errno); "Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n",
fd,
err,
zts_errno);
zts_close(fd); zts_close(fd);
printf("Creating socket...\n"); printf("Creating socket...\n");
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { 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); exit(1);
} }
zts_delay_ms(250); zts_delay_ms(250);
@@ -282,13 +321,21 @@ int main(int argc, char **argv)
} }
printf("Sending message string to server...\n"); printf("Sending message string to server...\n");
if ((bytes = zts_write(fd, msgStr, strlen(msgStr))) < 0) { 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); exit(1);
} }
printf("Sent %d bytes: %s\n", bytes, msgStr); printf("Sent %d bytes: %s\n", bytes, msgStr);
printf("Reading message string from server...\n"); printf("Reading message string from server...\n");
if ((bytes = zts_read(fd, recvBuf, sizeof(recvBuf))) < 0) { 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); exit(1);
} }
printf("Read %d bytes: %s\n", bytes, recvBuf); printf("Read %d bytes: %s\n", bytes, recvBuf);

View File

@@ -86,18 +86,19 @@
* *
*/ */
#include "ZeroTierSockets.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string> #include <string>
#include "ZeroTierSockets.h"
#ifdef __WINDOWS__ #ifdef __WINDOWS__
#include "winsock.h" #include "winsock.h"
#endif #endif
struct Node struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
{ {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} }
bool online; bool online;
bool joinedAtLeastOneNetwork; bool joinedAtLeastOneNetwork;
uint64_t id; uint64_t id;
@@ -108,7 +109,11 @@ void printNodeDetails(const char *msgStr, struct zts_node_details *d)
{ {
printf("\n%s\n", msgStr); printf("\n%s\n", msgStr);
printf("\t- id : %llx\n", d->address); 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- primaryPort : %d\n", d->primaryPort);
printf("\t- secondaryPort : %d\n", d->secondaryPort); 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- peer : %llx\n", d->address);
printf("\t- role : %llx\n", d->role); printf("\t- role : %llx\n", d->role);
printf("\t- latency : %d\n", d->latency); 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- pathCount : %d\n", d->pathCount);
printf("\t- paths:\n"); 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); printf("\t- multicastSubscriptionCount : %d\n", d->multicastSubscriptionCount);
for (int i = 0; i < d->multicastSubscriptionCount; i++) { 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"); printf("\t- addresses:\n");
@@ -230,33 +242,44 @@ void on_zts_event(void *msgPtr)
myNode.online = true; myNode.online = true;
} }
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { 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; myNode.online = false;
} }
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { 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; myNode.online = false;
} }
// Virtual network events // Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { 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; myNode.joinedAtLeastOneNetwork = true;
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { 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; myNode.joinedAtLeastOneNetwork = true;
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) { if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) {
@@ -271,29 +294,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "\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) { if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "\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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "\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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "\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 // Peer events
@@ -310,7 +343,9 @@ void on_zts_event(void *msgPtr)
printPeerDetails("ZTS_EVENT_PEER_RELAY --- No direct path known.", msg->peer); printPeerDetails("ZTS_EVENT_PEER_RELAY --- No direct path known.", msg->peer);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { 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) { if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) {
printPeerDetails("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died.", msg->peer); 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"); printf("\nZTS_EVENT_STACK_UP --- No action required.\n");
} }
if (msg->eventCode == ZTS_EVENT_STACK_DOWN) { 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; int err = 0;
// Count received pings // 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); printf("zts_get_proto_stats()=%d", err);
return; return;
} }
@@ -380,15 +417,18 @@ int main(int argc, char **argv)
} }
std::string configPath = std::string(argv[1]); std::string configPath = std::string(argv[1]);
uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join 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 // Bring up ZeroTier service and join network
int err = ZTS_ERR_OK; 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); 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); zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf // If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1); zts_allow_local_conf(1);
@@ -398,7 +438,9 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Waiting for node to come online...\n"); 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]); printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(nwid)) != ZTS_ERR_OK) { 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("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); 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 // Idle and just show callback events, stack statistics, etc
// Alternatively, this is where you could start making calls to the socket API // 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 <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include "ZeroTierSockets.h" struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
struct Node
{ {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} }
bool online; bool online;
bool joinedAtLeastOneNetwork; bool joinedAtLeastOneNetwork;
uint64_t id; uint64_t id;
@@ -114,18 +115,26 @@ void on_zts_event(void *msgPtr)
myNode.online = true; myNode.online = true;
} }
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { 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; myNode.online = false;
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { 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) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
@@ -136,15 +145,13 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf("ZTS_EVENT_ADDR_NEW_IP4 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr);
msg->addr->nwid, ipstr);
} }
if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) { if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr);
msg->addr->nwid, ipstr);
} }
// Peer events // Peer events
if (msg->peer) { if (msg->peer) {
@@ -154,18 +161,22 @@ void on_zts_event(void *msgPtr)
return; return;
} }
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { 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); msg->peer->address);
} }
} }
@@ -178,13 +189,16 @@ int main(int argc, char **argv)
printf("earthtest <config_file_path> <ztServicePort>\n"); printf("earthtest <config_file_path> <ztServicePort>\n");
exit(0); 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; 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); 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); zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf // If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1); zts_allow_local_conf(1);
@@ -194,7 +208,9 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Waiting for node to come online...\n"); 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]); printf("This node's identity is stored in %s\n", argv[1]);
uint64_t nwid = 0x8056c2e21c000001; uint64_t nwid = 0x8056c2e21c000001;
@@ -204,12 +220,16 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Joining network %llx\n", nwid); 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 // Idle and just show callback events, stack statistics, etc
printf("Node will now idle...\n"); printf("Node will now idle...\n");
while (true) { zts_delay_ms(1000); } while (true) {
zts_delay_ms(1000);
}
// Shut down service and stack threads // Shut down service and stack threads

View File

@@ -5,15 +5,16 @@
* local storage. In this mode you are responsible for saving keys. * local storage. In this mode you are responsible for saving keys.
*/ */
#include "ZeroTierSockets.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "ZeroTierSockets.h" struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
struct Node
{ {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} }
bool online; bool online;
bool joinedAtLeastOneNetwork; bool joinedAtLeastOneNetwork;
uint64_t id; uint64_t id;
@@ -34,11 +35,14 @@ void on_zts_event(void *msgPtr)
myNode.online = true; myNode.online = true;
} }
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { 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; myNode.online = false;
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
@@ -53,17 +57,17 @@ int main(int argc, char **argv)
printf("earthtest <config_file_path> <ztServicePort>\n"); printf("earthtest <config_file_path> <ztServicePort>\n");
exit(0); 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; int err = ZTS_ERR_OK;
// BEGIN key handling // BEGIN key handling
// Do not allow ZT to write anything to disk // Do not allow ZT to write anything to disk
zts_disable_local_storage(1); 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]; char keypair[KEY_BUF_LEN];
memset(keypair, 0, KEY_BUF_LEN); memset(keypair, 0, KEY_BUF_LEN);
@@ -77,7 +81,8 @@ int main(int argc, char **argv)
printf("\n\nVerifying ident...\n"); printf("\n\nVerifying ident...\n");
if (zts_verify_identity(keypair)) { if (zts_verify_identity(keypair)) {
printf("\tIdentity is valid\n"); printf("\tIdentity is valid\n");
} else { }
else {
printf("\tIdentity is invalid\n"); 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); zts_start_with_identity(keypair, keypair_len, &on_zts_event, ztServicePort);
printf("\n\nWaiting for node to come online...\n"); 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"); printf("\n\nAs a test, copy node's identity keypair back into buffer...\n");
memset(keypair, 0, KEY_BUF_LEN); memset(keypair, 0, KEY_BUF_LEN);
@@ -93,10 +100,8 @@ int main(int argc, char **argv)
zts_get_node_identity(keypair, &keypair_len); zts_get_node_identity(keypair, &keypair_len);
printf("keypair(len=%d) = [%s]\n", keypair_len, keypair); printf("keypair(len=%d) = [%s]\n", keypair_len, keypair);
// END key handling // END key handling
uint64_t nwid = 0x8056c2e21c000001; uint64_t nwid = 0x8056c2e21c000001;
if ((err = zts_join(nwid)) != ZTS_ERR_OK) { if ((err = zts_join(nwid)) != ZTS_ERR_OK) {
@@ -104,12 +109,16 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Joining network %llx\n", nwid); 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 // Idle and just show callback events, stack statistics, etc
printf("Node will now idle...\n"); printf("Node will now idle...\n");
while (true) { zts_delay_ms(1000); } while (true) {
zts_delay_ms(1000);
}
// Shut down service and stack threads // Shut down service and stack threads

View File

@@ -84,16 +84,17 @@
* *
*/ */
#include "ZeroTierSockets.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <string> #include <string>
#include "ZeroTierSockets.h" struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
struct Node
{ {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} }
bool online; bool online;
bool joinedAtLeastOneNetwork; bool joinedAtLeastOneNetwork;
uint64_t id; uint64_t id;
@@ -115,7 +116,8 @@ void on_zts_event(void *msgPtr)
myNode.online = true; myNode.online = true;
} }
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { 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; myNode.online = false;
} }
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
@@ -125,24 +127,33 @@ void on_zts_event(void *msgPtr)
// Virtual network events // Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
@@ -155,29 +166,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "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 // Peer events
@@ -188,18 +209,22 @@ void on_zts_event(void *msgPtr)
return; return;
} }
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { 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); msg->peer->address);
} }
} }
@@ -209,13 +234,15 @@ int main(int argc, char **argv)
{ {
if (argc != 6) { if (argc != 6) {
printf("\nlibzt example non-blocking client\n"); 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); exit(0);
} }
uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
std::string remoteAddr = argv[3]; // Remote application's virtual ZT address 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 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; struct zts_sockaddr_in in4;
in4.sin_port = htons(remotePort); in4.sin_port = htons(remotePort);
@@ -230,9 +257,11 @@ int main(int argc, char **argv)
int err = ZTS_ERR_OK; 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); 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); zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf // If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1); zts_allow_local_conf(1);
@@ -242,7 +271,9 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Waiting for node to come online...\n"); 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]); printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(nwid)) != ZTS_ERR_OK) { 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("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); 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 // Socket-like API example
@@ -268,12 +301,18 @@ int main(int argc, char **argv)
for (;;) { for (;;) {
printf("Connecting to remote host...\n"); printf("Connecting to remote host...\n");
if ((err = zts_connect(fd, (const struct zts_sockaddr*)&in4, sizeof(in4))) < 0) { 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", printf(
fd, err, zts_errno); "Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n",
fd,
err,
zts_errno);
zts_close(fd); zts_close(fd);
printf("Creating socket...\n"); printf("Creating socket...\n");
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { 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); exit(1);
} }
zts_delay_ms(250); zts_delay_ms(250);
@@ -288,7 +327,11 @@ int main(int argc, char **argv)
// The non-blocking aspect of this example is server-side // The non-blocking aspect of this example is server-side
while (1) { while (1) {
if ((bytes = zts_send(fd, msgStr, strlen(msgStr), 0)) < 0) { 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); exit(1);
} }
printf("zts_send()=%d\n", bytes); printf("zts_send()=%d\n", bytes);

View File

@@ -84,15 +84,16 @@
* *
*/ */
#include "ZeroTierSockets.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "ZeroTierSockets.h" struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
struct Node
{ {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} }
bool online; bool online;
bool joinedAtLeastOneNetwork; bool joinedAtLeastOneNetwork;
uint64_t id; uint64_t id;
@@ -114,7 +115,8 @@ void on_zts_event(void *msgPtr)
myNode.online = true; myNode.online = true;
} }
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { 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; myNode.online = false;
} }
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
@@ -124,24 +126,33 @@ void on_zts_event(void *msgPtr)
// Virtual network events // Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
@@ -154,29 +165,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "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 // Peer events
@@ -187,18 +208,22 @@ void on_zts_event(void *msgPtr)
return; return;
} }
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { 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); 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 uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
int serverBindPort = atoi(argv[3]); // Port the application should bind to 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; struct zts_sockaddr_in in4, acc_in4;
in4.sin_port = htons(serverBindPort); in4.sin_port = htons(serverBindPort);
@@ -229,9 +255,11 @@ int main(int argc, char **argv)
int fd, accfd; int fd, accfd;
int err = ZTS_ERR_OK; 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); 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); zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf // If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1); zts_allow_local_conf(1);
@@ -241,7 +269,9 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Waiting for node to come online...\n"); 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 ID is %llx\n", myNode.id);
printf("This node's identity is stored in %s\n", argv[1]); 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("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); 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 // Socket-like API example
printf("Creating socket...\n"); printf("Creating socket...\n");
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { 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); exit(1);
} }
printf("Binding...\n"); printf("Binding...\n");
if ((err = zts_bind(fd, (struct zts_sockaddr*)&in4, sizeof(struct zts_sockaddr_in)) < 0)) { 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); exit(1);
} }
printf("Listening...\n"); printf("Listening...\n");
int backlog = 100; int backlog = 100;
if ((err = zts_listen(fd, backlog)) < 0) { 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); exit(1);
} }
zts_socklen_t client_addrlen = sizeof(zts_sockaddr_in); zts_socklen_t client_addrlen = sizeof(zts_sockaddr_in);
if ((accfd = zts_accept(fd, (struct zts_sockaddr*)&acc_in4, &client_addrlen)) < 0) { 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_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_set active_fd_set, read_fd_set;
ZTS_FD_ZERO(&active_fd_set); ZTS_FD_ZERO(&active_fd_set);
ZTS_FD_SET(accfd, &active_fd_set); ZTS_FD_SET(accfd, &active_fd_set);
while (1) while (1) {
{
read_fd_set = active_fd_set; 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"); // perror ("select");
exit(1); exit(1);
} }
for (int i = 0; i < ZTS_FD_SETSIZE; i++) { 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); bytes = zts_recv(accfd, recvBuf, sizeof(recvBuf), 0);
printf("zts_recv(%d, ...)=%d\n", i, bytes); printf("zts_recv(%d, ...)=%d\n", i, bytes);
} }
@@ -345,8 +390,7 @@ int main(int argc, char **argv)
while (1) { while (1) {
result = zts_poll(poll_set, numfds, timeout_ms); result = zts_poll(poll_set, numfds, timeout_ms);
printf("zts_poll()=%d\n", result); 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) { if (poll_set[i].revents & ZTS_POLLIN) {
bytes = zts_recv(poll_set[i].fd, recvBuf, sizeof(recvBuf), 0); bytes = zts_recv(poll_set[i].fd, recvBuf, sizeof(recvBuf), 0);
printf("zts_recv(%d, ...)=%d\n", i, bytes); printf("zts_recv(%d, ...)=%d\n", i, bytes);

View File

@@ -2,16 +2,17 @@
* libzt API example * libzt API example
*/ */
#include "ZeroTierSockets.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <string> #include <string>
#include "ZeroTierSockets.h" struct Node {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0)
struct Node
{ {
Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} }
bool online; bool online;
bool joinedAtLeastOneNetwork; bool joinedAtLeastOneNetwork;
uint64_t id; uint64_t id;
@@ -33,7 +34,8 @@ void on_zts_event(void *msgPtr)
myNode.online = true; myNode.online = true;
} }
if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { 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; myNode.online = false;
} }
if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) {
@@ -42,23 +44,33 @@ void on_zts_event(void *msgPtr)
// Virtual network events // Virtual network events
if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { 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) { 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); msg->network->nwid);
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { 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); msg->network->nwid);
myNode.joinedAtLeastOneNetwork = true; myNode.joinedAtLeastOneNetwork = true;
} }
@@ -71,29 +83,39 @@ void on_zts_event(void *msgPtr)
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
msg->addr->nwid, ipstr); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) {
char ipstr[ZTS_INET_ADDRSTRLEN]; char ipstr[ZTS_INET_ADDRSTRLEN];
struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "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) { if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) {
char ipstr[ZTS_INET6_ADDRSTRLEN]; char ipstr[ZTS_INET6_ADDRSTRLEN];
struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); 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); 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", printf(
ipstr, msg->addr->nwid); "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 // Peer events
if (msg->peer) { if (msg->peer) {
@@ -103,18 +125,22 @@ void on_zts_event(void *msgPtr)
return; return;
} }
if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { if (msg->eventCode == ZTS_EVENT_PEER_RELAY) {
printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { 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); msg->peer->address);
} }
if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { 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); 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 uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join
int serverBindPort = atoi(argv[3]); // Port the application should bind to 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; struct zts_sockaddr_in in4, acc_in4;
in4.sin_port = htons(serverBindPort); in4.sin_port = htons(serverBindPort);
@@ -227,9 +254,11 @@ int main(int argc, char **argv)
int fd, accfd; int fd, accfd;
int err = ZTS_ERR_OK; 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); 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); zts_allow_peer_caching(1);
// If disabled: Settings will NOT be read from local.conf // If disabled: Settings will NOT be read from local.conf
zts_allow_local_conf(1); zts_allow_local_conf(1);
@@ -239,7 +268,9 @@ int main(int argc, char **argv)
exit(1); exit(1);
} }
printf("Waiting for node to come online...\n"); 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]); printf("This node's identity is stored in %s\n", argv[1]);
if ((err = zts_join(nwid)) != ZTS_ERR_OK) { 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("Joining network %llx\n", nwid);
printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); 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 // Socket-like API example
printf("Creating socket...\n"); printf("Creating socket...\n");
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { 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); exit(1);
} }
printf("Binding...\n"); printf("Binding...\n");
if ((err = zts_bind(fd, (struct zts_sockaddr*)&in4, sizeof(struct zts_sockaddr_in)) < 0)) { 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); exit(1);
} }
printf("Listening...\n"); printf("Listening...\n");
int backlog = 100; int backlog = 100;
if ((err = zts_listen(fd, backlog)) < 0) { 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); exit(1);
} }
@@ -276,7 +321,11 @@ int main(int argc, char **argv)
while (true) { while (true) {
zts_socklen_t client_addrlen = sizeof(zts_sockaddr_in); zts_socklen_t client_addrlen = sizeof(zts_sockaddr_in);
if ((accfd = zts_accept(fd, (struct zts_sockaddr*)&acc_in4, &client_addrlen)) < 0) { 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_socklen_t peer_addrlen = sizeof(struct zts_sockaddr_storage);
zts_getpeername(accfd, (struct zts_sockaddr*)&acc_in4, &peer_addrlen); 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"); printf("Reading message string from client...\n");
if ((bytes = zts_read(accfd, recvBuf, sizeof(recvBuf))) < 0) { 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); exit(1);
} }
printf("Read %d bytes: %s\n", bytes, recvBuf); printf("Read %d bytes: %s\n", bytes, recvBuf);
printf("Sending message string to client...\n"); printf("Sending message string to client...\n");
if ((bytes = zts_write(accfd, recvBuf, bytes)) < 0) { 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); exit(1);
} }
printf("Sent %d bytes: %s\n", bytes, recvBuf); printf("Sent %d bytes: %s\n", bytes, recvBuf);

View File

@@ -29,8 +29,7 @@ extern "C" {
//----------------------------------------------------------------------------// //----------------------------------------------------------------------------//
/** Common error return values */ /** Common error return values */
enum zts_error enum zts_error {
{
/** No error */ /** No error */
ZTS_ERR_OK = 0, ZTS_ERR_OK = 0,
/** Socket error, see `zts_errno` */ /** Socket error, see `zts_errno` */
@@ -50,8 +49,7 @@ enum zts_error
//----------------------------------------------------------------------------// //----------------------------------------------------------------------------//
/** Event codes used by the callback API */ /** Event codes used by the callback API */
enum zts_event enum zts_event {
{
/** The node service started successfully (no action needed) */ /** The node service started successfully (no action needed) */
ZTS_EVENT_NODE_UP = 200, ZTS_EVENT_NODE_UP = 200,
/** The node can reach the Internet */ /** The node can reach the Internet */
@@ -407,8 +405,10 @@ extern int zts_errno;
#define ZTS_IOC_IN 0x80000000UL #define ZTS_IOC_IN 0x80000000UL
#define ZTS_IOC_INOUT (ZTS_IOC_IN | ZTS_IOC_OUT) #define ZTS_IOC_INOUT (ZTS_IOC_IN | ZTS_IOC_OUT)
#define ZTS_IO(x, y) (ZTS_IOC_VOID | ((x) << 8) | (y)) #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_IOR(x, y, t) \
#define ZTS_IOW(x,y,t) (ZTS_IOC_IN | (((long)sizeof(t) & ZTS_IOCPARM_MASK)<<16) | ((x)<<8) | (y)) (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 // ioctl() commands
#define ZTS_FIONREAD ZTS_IOR('f', 127, unsigned long) #define ZTS_FIONREAD ZTS_IOR('f', 127, unsigned long)
#define ZTS_FIONBIO ZTS_IOW('f', 126, 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? * 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_LEAF = 0, // ordinary node
ZTS_PEER_ROLE_MOON = 1, // moon root ZTS_PEER_ROLE_MOON = 1, // moon root
ZTS_PEER_ROLE_PLANET = 2 // planetary 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 * A structure used to convey details about the current node
* to the user application * to the user application
*/ */
struct zts_node_details struct zts_node_details {
{
/** /**
* The node ID * The node ID
*/ */
@@ -531,8 +529,7 @@ struct zts_node_details
* A structure used to convey information to a user application via * A structure used to convey information to a user application via
* a callback function. * a callback function.
*/ */
struct zts_callback_msg struct zts_callback_msg {
{
/** /**
* Event identifier * Event identifier
*/ */
@@ -546,8 +543,7 @@ struct zts_callback_msg
struct zts_addr_details* addr; struct zts_addr_details* addr;
}; };
struct zts_addr_details struct zts_addr_details {
{
uint64_t nwid; uint64_t nwid;
struct zts_sockaddr_storage addr; struct zts_sockaddr_storage addr;
}; };
@@ -556,8 +552,7 @@ struct zts_addr_details
* A structure used to convey information about a virtual network * A structure used to convey information about a virtual network
* interface (netif) to a user application. * interface (netif) to a user application.
*/ */
struct zts_netif_details struct zts_netif_details {
{
/** /**
* The virtual network that this interface was commissioned for. * 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 * 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 * 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; uint16_t metric;
}; };
/** /**
* Maximum length of network short name * Maximum length of network short name
*/ */
@@ -612,7 +605,8 @@ struct zts_virtual_network_route
#define ZTS_MAX_NETWORK_ROUTES 32 #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 #define ZTS_MAX_ZT_ASSIGNED_ADDRESSES 16
@@ -624,8 +618,7 @@ struct zts_virtual_network_route
/** /**
* Virtual network status codes * Virtual network status codes
*/ */
enum ZTS_VirtualNetworkStatus enum ZTS_VirtualNetworkStatus {
{
/** /**
* Waiting for network configuration (also means revision == 0) * Waiting for network configuration (also means revision == 0)
*/ */
@@ -660,8 +653,7 @@ enum ZTS_VirtualNetworkStatus
/** /**
* Virtual network type codes * Virtual network type codes
*/ */
enum ZTS_VirtualNetworkType enum ZTS_VirtualNetworkType {
{
/** /**
* Private networks are authorized via certificates of membership * Private networks are authorized via certificates of membership
*/ */
@@ -676,8 +668,7 @@ enum ZTS_VirtualNetworkType
/** /**
* A route to be pushed on a virtual network * 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 * 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 * Virtual network configuration
*/ */
struct zts_network_details struct zts_network_details {
{
/** /**
* 64-bit ZeroTier network ID * 64-bit ZeroTier network ID
*/ */
@@ -757,7 +747,8 @@ struct zts_network_details
int broadcastEnabled; 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; int portError;
@@ -803,15 +794,15 @@ struct zts_network_details
*/ */
struct { struct {
uint64_t mac; /* MAC in lower 48 bits */ 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]; } multicastSubscriptions[ZTS_MAX_MULTICAST_SUBSCRIPTIONS];
}; };
/** /**
* Physical network path to a peer * Physical network path to a peer
*/ */
struct zts_physical_path struct zts_physical_path {
{
/** /**
* Address of endpoint * Address of endpoint
*/ */
@@ -846,8 +837,7 @@ struct zts_physical_path
/** /**
* Peer status result buffer * Peer status result buffer
*/ */
struct zts_peer_details struct zts_peer_details {
{
/** /**
* ZeroTier address (40 bits) * ZeroTier address (40 bits)
*/ */
@@ -892,8 +882,7 @@ struct zts_peer_details
/** /**
* List of peers * List of peers
*/ */
struct zts_peer_list struct zts_peer_list {
{
struct zts_peer_details* peers; struct zts_peer_details* peers;
unsigned long peerCount; unsigned long peerCount;
}; };
@@ -910,8 +899,7 @@ struct zts_peer_list
* Abstract class used as a director. Pointer to an instance of this class * Abstract class used as a director. Pointer to an instance of this class
* is provided to the Python layer. * is provided to the Python layer.
*/ */
class PythonDirectorCallbackClass class PythonDirectorCallbackClass {
{
public: public:
/** /**
* Called by native code on event. Implemented in Python * 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) * @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. * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/ */
ZTS_API int ZTCALL zts_central_init( ZTS_API int ZTCALL
const char *url_str, const char *token_str, char *resp_buf, uint32_t buf_len); 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(); 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. * @return `ZTS_ERR_OK` if all contents were copied successfully.
* `ZTS_ERR_ARG` if provided buffer was too small. * `ZTS_ERR_ARG` if provided buffer was too small.
*/ */
ZTS_API int ZTCALL zts_central_get_last_response_buf( ZTS_API int ZTCALL zts_central_get_last_response_buf(char* dest_buffer, int dest_buf_len);
char *dest_buffer, int dest_buf_len);
/** /**
* @brief Get the status of the Central API server. * @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. * @return Standard HTTP response codes.
*/ */
ZTS_API int ZTCALL zts_central_get_network( ZTS_API int ZTCALL zts_central_get_network(int* http_response_code, uint64_t nwid);
int *http_response_code, uint64_t nwid);
/** /**
* @brief Update or create a Network. * @brief Update or create a Network.
@@ -1046,8 +1032,7 @@ ZTS_API int ZTCALL zts_central_get_network(
* *
* @return Standard HTTP response codes. * @return Standard HTTP response codes.
*/ */
ZTS_API int ZTCALL zts_central_update_network( ZTS_API int ZTCALL zts_central_update_network(int* http_response_code, uint64_t nwid);
int *http_response_code, uint64_t nwid);
/** /**
* @brief Delete a Network. * @brief Delete a Network.
@@ -1057,8 +1042,7 @@ ZTS_API int ZTCALL zts_central_update_network(
* *
* @return Standard HTTP response codes. * @return Standard HTTP response codes.
*/ */
ZTS_API int ZTCALL zts_central_delete_network( ZTS_API int ZTCALL zts_central_delete_network(int* http_response_code, uint64_t nwid);
int *http_response_code, uint64_t nwid);
/** /**
* @brief Get All Viewable Networks. * @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. * @return Standard HTTP response codes.
*/ */
ZTS_API int ZTCALL zts_central_get_member( ZTS_API int ZTCALL zts_central_get_member(int* http_response_code, uint64_t nwid, uint64_t nodeid);
int *http_response_code, uint64_t nwid, uint64_t nodeid);
/** /**
* @brief Update or add a Member. * @brief Update or add a Member.
@@ -1083,8 +1066,8 @@ ZTS_API int ZTCALL zts_central_get_member(
* *
* @return Standard HTTP response codes. * @return Standard HTTP response codes.
*/ */
ZTS_API int ZTCALL zts_central_update_member( ZTS_API int ZTCALL
int *http_response_code, uint64_t nwid, uint64_t nodeid, char *post_data); 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 * @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. * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/ */
ZTS_API int ZTCALL zts_central_set_node_auth( 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. * @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. * @return Standard HTTP response codes.
*/ */
ZTS_API int ZTCALL zts_central_get_members_of_network( ZTS_API int ZTCALL zts_central_get_members_of_network(int* http_response_code, uint64_t nwid);
int *http_response_code, uint64_t nwid);
#endif // NO_CENTRAL_API #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_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. * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/ */
ZTS_API int ZTCALL zts_generate_orphan_identity( ZTS_API int ZTCALL zts_generate_orphan_identity(char* key_pair_str, uint16_t* key_buf_len);
char *key_pair_str, uint16_t *key_buf_len);
/** /**
* @brief Verifies that a key-pair is valid for use. * @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 * @brief Copies the current node's identity into a buffer
* *
* @param key_pair_str User-provided destination 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 * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. * experiences a problem, `ZTS_ERR_ARG` if invalid arg.
*/ */
ZTS_API int ZTCALL zts_get_node_identity( ZTS_API int ZTCALL zts_get_node_identity(char* key_pair_str, uint16_t* key_buf_len);
char *key_pair_str, uint16_t *key_buf_len);
/** /**
* @brief Starts the ZeroTier service and notifies user application of events via callback. This * @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. * experiences a problem, `ZTS_ERR_ARG` if invalid arg.
*/ */
#ifdef ZTS_ENABLE_PYTHON #ifdef ZTS_ENABLE_PYTHON
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, int zts_start_with_identity(
PythonDirectorCallbackClass *callback, uint16_t port); const char* key_pair_str,
uint16_t key_buf_len,
PythonDirectorCallbackClass* callback,
uint16_t port);
#endif #endif
#ifdef ZTS_ENABLE_PINVOKE #ifdef ZTS_ENABLE_PINVOKE
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, int zts_start_with_identity(
CppCallback callback, uint16_t port); const char* key_pair_str,
uint16_t key_buf_len,
CppCallback callback,
uint16_t port);
#endif #endif
#ifdef ZTS_C_API_ONLY #ifdef ZTS_C_API_ONLY
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, int zts_start_with_identity(
void (*callback)(void *), uint16_t port); const char* key_pair_str,
uint16_t key_buf_len,
void (*callback)(void*),
uint16_t port);
#endif #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); 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. * 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. * experiences a problem, `ZTS_ERR_ARG` if invalid arg.
*/ */
#ifdef ZTS_ENABLE_PYTHON #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 #endif
#ifdef ZTS_ENABLE_PINVOKE #ifdef ZTS_ENABLE_PINVOKE
ZTS_API int ZTCALL zts_start(const char* path, CppCallback callback, uint16_t port); 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 * @param nodeId Node ID
* @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg. * @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 * @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. * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg.
*/ */
ZTS_API int ZTCALL zts_get_rfc4193_addr( 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 * @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 * 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. * (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 * For example `ff00160016000000` is an ad-hoc network allowing only SSH, while `ff0000ffff000000`
* ad-hoc network allowing any UDP or TCP port. * 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 * Keep in mind that these networks are public and anyone in the entire world can join them. Care
* be taken to avoid exposing vulnerable services or sharing unwanted files or other resources. * must be taken to avoid exposing vulnerable services or sharing unwanted files or other resources.
* *
* *
* @param startPortOfRange Start of port allowed port range * @param startPortOfRange Start of port allowed port range
* @param endPortOfRange End of allowed port range * @param endPortOfRange End of allowed port range
* @return An Ad-hoc network ID * @return An Ad-hoc network ID
*/ */
ZTS_API uint64_t ZTCALL zts_generate_adhoc_nwid_from_range( ZTS_API uint64_t ZTCALL
uint16_t startPortOfRange, uint16_t endPortOfRange); zts_generate_adhoc_nwid_from_range(uint16_t startPortOfRange, uint16_t endPortOfRange);
/** /**
* @brief Platform-agnostic delay (provided for convenience) * @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. * 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. * @return ZTS_ERR_OK on success. ZTS_ERR_ARG or ZTS_ERR_NO_RESULT on failure.
*/ */
ZTS_API int ZTCALL zts_get_protocol_stats( ZTS_API int ZTCALL zts_get_protocol_stats(int protocolType, void* protoStatsDest);
int protocolType, void *protoStatsDest);
#endif // ZTS_ENABLE_STATS #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 * @return Numbered file descriptor on success, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API int ZTCALL zts_socket( ZTS_API int ZTCALL zts_socket(const int socket_family, const int socket_type, const int protocol);
const int socket_family, const int socket_type, const int protocol);
/** /**
* @brief Connect a socket to a remote host * @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 * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API int ZTCALL zts_connect( ZTS_API int ZTCALL zts_connect(int fd, const struct zts_sockaddr* addr, zts_socklen_t addrlen);
int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen);
/** /**
* @brief Connect a socket to a remote host * @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 * out with no connection made, `ZTS_ERR_SERVICE` if the node experiences a
* problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` * problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API int ZTCALL zts_connect_easy( ZTS_API int ZTCALL zts_connect_easy(int fd, int family, char* ipstr, int port, int timeout_ms);
int fd, int family, char *ipstr, int port, int timeout_ms);
/** /**
* @brief Bind a socket to a local address * @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 * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API int ZTCALL zts_bind( ZTS_API int ZTCALL zts_bind(int fd, const struct zts_sockaddr* addr, zts_socklen_t addrlen);
int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen);
/** /**
* @brief Bind a socket to a local address * @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 * @return New file descriptor if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API int ZTCALL zts_accept( ZTS_API int ZTCALL zts_accept(int fd, struct zts_sockaddr* addr, zts_socklen_t* addrlen);
int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen);
/** /**
* @brief Accept an incoming connection * @brief Accept an incoming connection
@@ -1647,8 +1643,11 @@ struct zts_linger {
#define ZTS_TCP_KEEPINTVL 0x0004 #define ZTS_TCP_KEEPINTVL 0x0004
#define ZTS_TCP_KEEPCNT 0x0005 #define ZTS_TCP_KEEPCNT 0x0005
// IPPROTO_IPV6 options // IPPROTO_IPV6 options
#define ZTS_IPV6_CHECKSUM 0x0007 /* RFC3542: calculate and insert the ICMPv6 checksum for raw sockets. */ #define ZTS_IPV6_CHECKSUM \
#define ZTS_IPV6_V6ONLY 0x001b /* RFC3493: boolean control to restrict ZTS_AF_INET6 sockets to IPv6 communications only. */ 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 // UDPLITE options
#define ZTS_UDPLITE_SEND_CSCOV 0x01 /* sender checksum coverage */ #define ZTS_UDPLITE_SEND_CSCOV 0x01 /* sender checksum coverage */
#define ZTS_UDPLITE_RECV_CSCOV 0x02 /* minimal receiver 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 * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API int ZTCALL zts_setsockopt( ZTS_API int ZTCALL
int fd, int level, int optname, const void *optval, zts_socklen_t optlen); zts_setsockopt(int fd, int level, int optname, const void* optval, zts_socklen_t optlen);
/** /**
* @brief Get socket options * @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 * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node
* experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API int ZTCALL zts_getsockopt( ZTS_API int ZTCALL
int fd, int level, int optname, void *optval, zts_socklen_t *optlen); zts_getsockopt(int fd, int level, int optname, void* optval, zts_socklen_t* optlen);
/** /**
* @brief Get socket name * @brief Get socket name
@@ -1793,18 +1792,29 @@ ZTS_API int ZTCALL zts_close(int fd);
#undef ZTS_FD_SETSIZE #undef ZTS_FD_SETSIZE
// Make FD_SETSIZE match NUM_SOCKETS in socket.c // Make FD_SETSIZE match NUM_SOCKETS in socket.c
#define ZTS_FD_SETSIZE MEMP_NUM_NETCONN #define ZTS_FD_SETSIZE MEMP_NUM_NETCONN
#define ZTS_FDSETSAFESET(n, code) do { \ #define ZTS_FDSETSAFESET(n, code) \
if (((n) - LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n) - LWIP_SOCKET_OFFSET) >= 0)) { \ do { \
code; }} while(0) if (((n)-LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) \
&& (((int)(n)-LWIP_SOCKET_OFFSET) >= 0)) { \
code; \
} \
} while (0)
#define ZTS_FDSETSAFEGET(n, code) \ #define ZTS_FDSETSAFEGET(n, code) \
(((n) - LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n) - LWIP_SOCKET_OFFSET) >= 0) ? \ (((n)-LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n)-LWIP_SOCKET_OFFSET) >= 0) \
(code) : 0) ? (code) \
: 0)
#define ZTS_FD_SET(n, p) \ #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) \ #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) \ #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))) #define ZTS_FD_ZERO(p) memset((void*)(p), 0, sizeof(*(p)))
#elif LWIP_SOCKET_OFFSET #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" #error "external ZTS_FD_SETSIZE too small for number of sockets"
#endif // FD_SET #endif // FD_SET
typedef struct zts_fd_set typedef struct zts_fd_set {
{
unsigned char fd_bits[(ZTS_FD_SETSIZE + 7) / 8]; unsigned char fd_bits[(ZTS_FD_SETSIZE + 7) / 8];
} zts_fd_set; } 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. * @return Number of ready file descriptors on success. ZTS_ERR_SOCKET, ZTS_ERR_SERVICE on failure.
*/ */
ZTS_API int ZTCALL zts_select( 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 // fnctl() commands
#define ZTS_F_GETFL 0x0003 #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; typedef unsigned int zts_nfds_t;
struct zts_pollfd struct zts_pollfd {
{
int fd; int fd;
short events; short events;
short revents; 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` * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API ssize_t ZTCALL zts_sendto( 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 { struct zts_iovec {
void* iov_base; 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` * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno`
*/ */
ZTS_API ssize_t ZTCALL zts_recvfrom( 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 * @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 * @param size Size of the destination buffer
* @return On success, returns a non-null pointer to the destination character array * @return On success, returns a non-null pointer to the destination character array
*/ */
ZTS_API const char * ZTCALL zts_inet_ntop( ZTS_API const char* ZTCALL
int family, const void *src, char *dst, zts_socklen_t size); zts_inet_ntop(int family, const void* src, char* dst, zts_socklen_t size);
/** /**
* Convert C-string IPv4 and IPv6 addresses to binary form. * 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 src_ipstr Source IP string
* @param port Port * @param port Port
* @param dest_addr Pointer to destination structure `zts_sockaddr_in` or `zts_sockaddr_in6` * @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 * @return return `ZTS_ERR_OK` on success, `ZTS_ERR_ARG` if invalid argument
*/ */
int ipstr2sockaddr( 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 #ifdef __cplusplus
} // extern "C" } // extern "C"

View File

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

View File

@@ -17,21 +17,20 @@
* Node / Network control interface * 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 <inttypes.h>
#include <sys/types.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; using namespace ZeroTier;
#ifdef ZTS_ENABLE_JAVA #ifdef ZTS_ENABLE_JAVA
@@ -47,8 +46,7 @@ WSADATA wsaData;
#define ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS 1 #define ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS 1
#endif #endif
namespace ZeroTier namespace ZeroTier {
{
extern NodeService* service; extern NodeService* service;
extern Mutex serviceLock; extern Mutex serviceLock;
#ifdef ZTS_ENABLE_PYTHON #ifdef ZTS_ENABLE_PYTHON
@@ -71,7 +69,7 @@ namespace ZeroTier
jmethodID _userCallbackMethodRef = NULL; jmethodID _userCallbackMethodRef = NULL;
#endif #endif
extern uint8_t _serviceStateFlags; extern uint8_t _serviceStateFlags;
} } // namespace ZeroTier
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { 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 // TODO: This logic should be further generalized in the next API redesign
#ifdef ZTS_ENABLE_PYTHON #ifdef ZTS_ENABLE_PYTHON
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, int zts_start_with_identity(
PythonDirectorCallbackClass *callback, uint16_t port) const char* key_pair_str,
uint16_t key_buf_len,
PythonDirectorCallbackClass* callback,
uint16_t port)
#endif #endif
#ifdef ZTS_ENABLE_PINVOKE #ifdef ZTS_ENABLE_PINVOKE
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, int zts_start_with_identity(
CppCallback callback, uint16_t port) const char* key_pair_str,
uint16_t key_buf_len,
CppCallback callback,
uint16_t port)
#endif #endif
#ifdef ZTS_C_API_ONLY #ifdef ZTS_C_API_ONLY
int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, int zts_start_with_identity(
void (*callback)(void *), uint16_t port) const char* key_pair_str,
uint16_t key_buf_len,
void (*callback)(void*),
uint16_t port)
#endif #endif
{ {
if (! zts_verify_identity(key_pair_str)) { 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 #ifdef ZTS_ENABLE_JAVA
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_start( 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) { if (! path) {
return ZTS_ERR_ARG; 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"); DEBUG_ERROR("Couldn't find class for ZeroTierEventListener instance");
return ZTS_ERR_ARG; return ZTS_ERR_ARG;
} }
jmethodID eventListenerCallbackMethod = env->GetMethodID(eventListenerClass, "onZeroTierEvent", "(JI)V"); jmethodID eventListenerCallbackMethod =
env->GetMethodID(eventListenerClass, "onZeroTierEvent", "(JI)V");
if (eventListenerCallbackMethod == NULL) { if (eventListenerCallbackMethod == NULL) {
DEBUG_ERROR("Couldn't find onZeroTierEvent method"); DEBUG_ERROR("Couldn't find onZeroTierEvent method");
return ZTS_ERR_ARG; return ZTS_ERR_ARG;
@@ -366,8 +378,7 @@ int zts_stop()
return ZTS_ERR_SERVICE; return ZTS_ERR_SERVICE;
} }
#ifdef ZTS_ENABLE_JAVA #ifdef ZTS_ENABLE_JAVA
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_stop( JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_stop(JNIEnv* env, jobject thisObj)
JNIEnv *env, jobject thisObj)
{ {
zts_stop(); zts_stop();
} }
@@ -414,8 +425,7 @@ int zts_restart()
#endif #endif
} }
#ifdef ZTS_ENABLE_JAVA #ifdef ZTS_ENABLE_JAVA
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_restart( JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_restart(JNIEnv* env, jobject thisObj)
JNIEnv *env, jobject thisObj)
{ {
zts_restart(); zts_restart();
} }
@@ -436,8 +446,7 @@ int zts_free()
return err; return err;
} }
#ifdef ZTS_ENABLE_JAVA #ifdef ZTS_ENABLE_JAVA
JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_free( JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_free(JNIEnv* env, jobject thisObj)
JNIEnv *env, jobject thisObj)
{ {
zts_free(); 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 * 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. * later to call a user-specified callback method from C.
*/ */
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_init( JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_init(JNIEnv* env, jobject thisObj)
JNIEnv *env, jobject thisObj)
{ {
jint rs = env->GetJavaVM(&jvm); jint rs = env->GetJavaVM(&jvm);
return rs != JNI_OK ? ZTS_ERR_GENERAL : ZTS_ERR_OK; 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; return ZTS_ERR_OK;
} }
#ifdef ZTS_ENABLE_JAVA #ifdef ZTS_ENABLE_JAVA
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_join( JNIEXPORT jint JNICALL
JNIEnv *env, jobject thisObj, jlong networkId) Java_com_zerotier_libzt_ZeroTier_join(JNIEnv* env, jobject thisObj, jlong networkId)
{ {
return zts_join((uint64_t)networkId); return zts_join((uint64_t)networkId);
} }
@@ -487,8 +495,8 @@ int zts_leave(const uint64_t networkId)
return ZTS_ERR_OK; return ZTS_ERR_OK;
} }
#ifdef ZTS_ENABLE_JAVA #ifdef ZTS_ENABLE_JAVA
JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_leave( JNIEXPORT jint JNICALL
JNIEnv *env, jobject thisObj, jlong networkId) Java_com_zerotier_libzt_ZeroTier_leave(JNIEnv* env, jobject thisObj, jlong networkId)
{ {
return zts_leave((uint64_t)networkId); return zts_leave((uint64_t)networkId);
} }
@@ -500,7 +508,8 @@ int zts_orbit(uint64_t moonWorldId, uint64_t moonSeed)
void* tptr = NULL; void* tptr = NULL;
if (! _canPerformServiceOperation()) { if (! _canPerformServiceOperation()) {
return ZTS_ERR_SERVICE; return ZTS_ERR_SERVICE;
} else { }
else {
service->getNode()->orbit(tptr, moonWorldId, moonSeed); service->getNode()->orbit(tptr, moonWorldId, moonSeed);
} }
return ZTS_ERR_OK; return ZTS_ERR_OK;
@@ -514,7 +523,8 @@ int zts_deorbit(uint64_t moonWorldId)
void* tptr = NULL; void* tptr = NULL;
if (! _canPerformServiceOperation()) { if (! _canPerformServiceOperation()) {
return ZTS_ERR_SERVICE; return ZTS_ERR_SERVICE;
} else { }
else {
service->getNode()->deorbit(tptr, moonWorldId); service->getNode()->deorbit(tptr, moonWorldId);
} }
return ZTS_ERR_OK; return ZTS_ERR_OK;
@@ -522,7 +532,10 @@ int zts_deorbit(uint64_t moonWorldId)
#ifdef ZTS_ENABLE_JAVA #ifdef ZTS_ENABLE_JAVA
#endif #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) { if (! addr || ! networkId || ! nodeId) {
return ZTS_ERR_ARG; 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; 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) { if (! addr || ! networkId || ! nodeId) {
return ZTS_ERR_ARG; return ZTS_ERR_ARG;

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

@@ -18,15 +18,14 @@
*/ */
#include "Constants.hpp" #include "Constants.hpp"
#include "MAC.hpp"
#include "Mutex.hpp"
#include "InetAddress.hpp" #include "InetAddress.hpp"
#include "MAC.hpp"
#include "MulticastGroup.hpp" #include "MulticastGroup.hpp"
#include "Mutex.hpp"
#include "lwip/netif.h"
#include "lwip/etharp.h" #include "lwip/etharp.h"
#include "lwip/sys.h"
#include "lwip/ethip6.h" #include "lwip/ethip6.h"
#include "lwip/netif.h"
#include "lwip/sys.h"
#include "lwip/tcpip.h" #include "lwip/tcpip.h"
#include "netif/ethernet.h" #include "netif/ethernet.h"
@@ -34,14 +33,15 @@
#include "lwip/stats.h" #include "lwip/stats.h"
#endif #endif
#include "Debug.hpp"
#include "Events.hpp"
#include "VirtualTap.hpp" #include "VirtualTap.hpp"
#include "ZeroTierSockets.h" #include "ZeroTierSockets.h"
#include "Events.hpp"
#include "Debug.hpp"
#if defined(__WINDOWS__) #if defined(__WINDOWS__)
#include <time.h>
#include "Synchapi.h" #include "Synchapi.h"
#include <time.h>
#endif #endif
#define ZTS_TAP_THREAD_POLLING_INTERVAL 50 #define ZTS_TAP_THREAD_POLLING_INTERVAL 50
@@ -62,20 +62,28 @@ VirtualTap::VirtualTap(
unsigned int metric, unsigned int metric,
uint64_t nwid, uint64_t nwid,
const char* friendlyName, const char* friendlyName,
void (*handler)(void *,void*,uint64_t,const MAC &,const MAC &, void (*handler)(
unsigned int,unsigned int,const void *,unsigned int), void*,
void *arg) : void*,
_handler(handler), uint64_t,
_homePath(homePath), const MAC&,
_arg(arg), const MAC&,
_initialized(false), unsigned int,
_enabled(true), unsigned int,
_run(true), const void*,
_mac(mac), unsigned int),
_mtu(mtu), void* arg)
_nwid(nwid), : _handler(handler)
_unixListenSocket((PhySocket *)0), , _homePath(homePath)
_phy(this,false,true) , _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)); memset(vtap_full_name, 0, sizeof(vtap_full_name));
snprintf(vtap_full_name, sizeof(vtap_full_name), "libzt%llx", (unsigned long long)_nwid); 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); Mutex::Lock _l(_ips_m);
std::vector<InetAddress>::iterator it(_ips.begin()); std::vector<InetAddress>::iterator it(_ips.begin());
while (it != _ips.end()) { while (it != _ips.end()) {
if ((*it).isV4()) { return true; } if ((*it).isV4()) {
return true;
}
++it; ++it;
} }
return false; return false;
@@ -139,7 +149,9 @@ bool VirtualTap::hasIpv6Addr()
Mutex::Lock _l(_ips_m); Mutex::Lock _l(_ips_m);
std::vector<InetAddress>::iterator it(_ips.begin()); std::vector<InetAddress>::iterator it(_ips.begin());
while (it != _ips.end()) { while (it != _ips.end()) {
if ((*it).isV6()) { return true; } if ((*it).isV6()) {
return true;
}
++it; ++it;
} }
return false; return false;
@@ -194,8 +206,12 @@ std::vector<InetAddress> VirtualTap::ips() const
return _ips; return _ips;
} }
void VirtualTap::put(const MAC &from,const MAC &to,unsigned int etherType, void VirtualTap::put(
const void *data,unsigned int len) const MAC& from,
const MAC& to,
unsigned int etherType,
const void* data,
unsigned int len)
{ {
if (len && _enabled) { if (len && _enabled) {
_lwip_eth_rx(this, from, to, etherType, data, len); _lwip_eth_rx(this, from, to, etherType, data, len);
@@ -212,7 +228,8 @@ void VirtualTap::setFriendlyName(const char *friendlyName)
DEBUG_INFO("%s", 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>& removed)
{ {
std::vector<MulticastGroup> newGroups; std::vector<MulticastGroup> newGroups;
@@ -228,7 +245,9 @@ void VirtualTap::scanMulticastGroups(std::vector<MulticastGroup> &added,
if (! std::binary_search(_multicastGroups.begin(), _multicastGroups.end(), *m)) if (! std::binary_search(_multicastGroups.begin(), _multicastGroups.end(), *m))
added.push_back(*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)) if (! std::binary_search(newGroups.begin(), newGroups.end(), *m))
removed.push_back(*m); removed.push_back(*m);
} }
@@ -240,8 +259,7 @@ void VirtualTap::setMtu(unsigned int mtu)
_mtu = mtu; _mtu = mtu;
} }
void VirtualTap::threadMain() void VirtualTap::threadMain() throw()
throw()
{ {
fd_set readfds, nullfds; fd_set readfds, nullfds;
struct timeval tv; struct timeval tv;
@@ -273,15 +291,38 @@ void VirtualTap::threadMain()
} }
} }
void VirtualTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *local_address, void VirtualTap::phyOnDatagram(
const struct sockaddr *from,void *data,unsigned long len) {} PhySocket* sock,
void VirtualTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {} void** uptr,
void VirtualTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN, const struct sockaddr* local_address,
const struct sockaddr *from) {} const struct sockaddr* from,
void VirtualTap::phyOnTcpClose(PhySocket *sock,void **uptr) {} void* data,
void VirtualTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {} unsigned long len)
void VirtualTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {} {
void VirtualTap::phyOnUnixClose(PhySocket *sock,void **uptr) {} }
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 // // Netif driver code for lwIP network stack //
@@ -348,8 +389,12 @@ void _lwip_driver_init()
#if defined(__WINDOWS__) #if defined(__WINDOWS__)
sys_init(); // Required for win32 init of critical sections sys_init(); // Required for win32 init of critical sections
#endif #endif
sys_thread_new(ZTS_LWIP_DRIVER_THREAD_NAME, _main_lwip_driver_loop, sys_thread_new(
NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); ZTS_LWIP_DRIVER_THREAD_NAME,
_main_lwip_driver_loop,
NULL,
DEFAULT_THREAD_STACKSIZE,
DEFAULT_THREAD_PRIO);
} }
void _lwip_driver_shutdown() void _lwip_driver_shutdown()
@@ -362,7 +407,9 @@ void _lwip_driver_shutdown()
_clrState(ZTS_STATE_STACK_RUNNING); _clrState(ZTS_STATE_STACK_RUNNING);
// Wait until the main lwIP thread has exited // Wait until the main lwIP thread has exited
if (_has_started) { 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]; char flagbuf[32];
memset(&flagbuf, 0, 32); memset(&flagbuf, 0, 32);
char macBuf[ZTS_MAC_ADDRSTRLEN], nodeBuf[16]; char macBuf[ZTS_MAC_ADDRSTRLEN], nodeBuf[16];
snprintf(macBuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x", snprintf(
ethhdr->dest.addr[0], ethhdr->dest.addr[1], ethhdr->dest.addr[2], macBuf,
ethhdr->dest.addr[3], ethhdr->dest.addr[4], ethhdr->dest.addr[5]); 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 mac;
mac.setTo(ethhdr->dest.addr, 6); mac.setTo(ethhdr->dest.addr, 6);
mac.toAddress(tap->_nwid).toString(nodeBuf); 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(), DEBUG_TRANS("len=%5d dst=%s [%s TX <-- %s] ethertype=0x%04x %s", totalLength, macBuf,
Utils::ntoh(ethhdr->type), flagbuf); nodeBuf, tap->nodeId().c_str(), Utils::ntoh(ethhdr->type), flagbuf);
*/ */
} }
return ERR_OK; return ERR_OK;
} }
void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int etherType, void _lwip_eth_rx(
const void *data, unsigned int len) VirtualTap* tap,
const MAC& from,
const MAC& to,
unsigned int etherType,
const void* data,
unsigned int len)
{ {
#ifdef LWIP_STATS #ifdef LWIP_STATS
stats_display(); stats_display();
@@ -445,15 +504,22 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int
char flagbuf[32]; char flagbuf[32];
memset(&flagbuf, 0, 32); memset(&flagbuf, 0, 32);
char macBuf[ZTS_MAC_ADDRSTRLEN], nodeBuf[16]; char macBuf[ZTS_MAC_ADDRSTRLEN], nodeBuf[16];
snprintf(macBuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x", snprintf(
ethhdr.dest.addr[0], ethhdr.dest.addr[1], ethhdr.dest.addr[2], macBuf,
ethhdr.dest.addr[3], ethhdr.dest.addr[4], ethhdr.dest.addr[5]); 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 mac;
mac.setTo(ethhdr.src.addr, 6); mac.setTo(ethhdr.src.addr, 6);
mac.toAddress(tap->_nwid).toString(nodeBuf); 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(), DEBUG_TRANS("len=%5d dst=%s [%s RX --> %s] ethertype=0x%04x %s", len, macBuf, nodeBuf,
Utils::ntoh(ethhdr.type), flagbuf); 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 (Utils::ntoh(ethhdr.type) == 0x800 || Utils::ntoh(ethhdr.type) == 0x806) {
if (tap->netif4) { 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); DEBUG_ERROR("packet input error (%d)", err);
pbuf_free(p); 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 (Utils::ntoh(ethhdr.type) == 0x86DD) {
if (tap->netif6) { 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); DEBUG_ERROR("packet input error (%d)", err);
pbuf_free(p); pbuf_free(p);
} }
@@ -579,13 +647,8 @@ static err_t _netif_init4(struct netif *n)
n->linkoutput = _lwip_eth_tx; n->linkoutput = _lwip_eth_tx;
n->output = etharp_output; n->output = etharp_output;
n->mtu = std::min(LWIP_MTU, (int)tap->_mtu); n->mtu = std::min(LWIP_MTU, (int)tap->_mtu);
n->flags = NETIF_FLAG_BROADCAST n->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP
| NETIF_FLAG_ETHARP | NETIF_FLAG_MLD6 | NETIF_FLAG_LINK_UP | NETIF_FLAG_UP;
| NETIF_FLAG_ETHERNET
| NETIF_FLAG_IGMP
| NETIF_FLAG_MLD6
| NETIF_FLAG_LINK_UP
| NETIF_FLAG_UP;
n->hwaddr_len = sizeof(n->hwaddr); n->hwaddr_len = sizeof(n->hwaddr);
tap->_mac.copyTo(n->hwaddr, n->hwaddr_len); tap->_mac.copyTo(n->hwaddr, n->hwaddr_len);
return ERR_OK; return ERR_OK;
@@ -606,13 +669,8 @@ static err_t _netif_init6(struct netif *n)
n->linkoutput = _lwip_eth_tx; n->linkoutput = _lwip_eth_tx;
n->output_ip6 = ethip6_output; n->output_ip6 = ethip6_output;
n->mtu = std::min(LWIP_MTU, (int)tap->_mtu); n->mtu = std::min(LWIP_MTU, (int)tap->_mtu);
n->flags = NETIF_FLAG_BROADCAST n->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP
| NETIF_FLAG_ETHARP | NETIF_FLAG_MLD6 | NETIF_FLAG_LINK_UP | NETIF_FLAG_UP;
| NETIF_FLAG_ETHERNET
| NETIF_FLAG_IGMP
| NETIF_FLAG_MLD6
| NETIF_FLAG_LINK_UP
| NETIF_FLAG_UP;
return ERR_OK; 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); netif_add(n, &ip4, &netmask, &gw, (void*)vtap, _netif_init4, tcpip_input);
vtap->netif4 = (void*)n; vtap->netif4 = (void*)n;
UNLOCK_TCPIP_CORE(); UNLOCK_TCPIP_CORE();
snprintf(macbuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x", snprintf(
n->hwaddr[0], n->hwaddr[1], n->hwaddr[2], macbuf,
n->hwaddr[3], n->hwaddr[4], n->hwaddr[5]); 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 nmbuf[INET6_ADDRSTRLEN];
char ipbuf[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); netif_add_ip6_address(n, &ip6, NULL);
n->output_ip6 = ethip6_output; n->output_ip6 = ethip6_output;
UNLOCK_TCPIP_CORE(); UNLOCK_TCPIP_CORE();
snprintf(macbuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x", snprintf(
n->hwaddr[0], n->hwaddr[1], n->hwaddr[2], macbuf,
n->hwaddr[3], n->hwaddr[4], n->hwaddr[5]); 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, DEBUG_INFO("initialized netif=%p as [mac=%s, addr=%s, tap=%p]", n,
macbuf, ip.toString(ipbuf), vtap); 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 * A virtual tap device. The ZeroTier Node Service will create one per
* joined network. It will be destroyed upon leave(). * joined network. It will be destroyed upon leave().
*/ */
class VirtualTap class VirtualTap {
{
friend class Phy<VirtualTap*>; friend class Phy<VirtualTap*>;
public: public:
@@ -51,8 +50,16 @@ public:
unsigned int metric, unsigned int metric,
uint64_t nwid, uint64_t nwid,
const char* friendlyName, const char* friendlyName,
void (*handler)(void *, void *, uint64_t, const MAC &, void (*handler)(
const MAC &, unsigned int, unsigned int, const void *, unsigned int), void*,
void*,
uint64_t,
const MAC&,
const MAC&,
unsigned int,
unsigned int,
const void*,
unsigned int),
void* arg); void* arg);
~VirtualTap(); ~VirtualTap();
@@ -89,8 +96,8 @@ public:
/** /**
* Presents data to the user-space stack * Presents data to the user-space stack
*/ */
void put(const MAC &from,const MAC &to,unsigned int etherType,const void *data, void
unsigned int len); put(const MAC& from, const MAC& to, unsigned int etherType, const void* data, unsigned int len);
/** /**
* Get VirtualTap device name (e.g. 'libzt17d72843bc2c5760') * Get VirtualTap device name (e.g. 'libzt17d72843bc2c5760')
@@ -105,8 +112,8 @@ public:
/** /**
* Scan multicast groups * Scan multicast groups
*/ */
void scanMulticastGroups(std::vector<MulticastGroup> &added, void
std::vector<MulticastGroup> &removed); scanMulticastGroups(std::vector<MulticastGroup>& added, std::vector<MulticastGroup>& removed);
/** /**
* Set MTU * Set MTU
@@ -116,14 +123,21 @@ public:
/** /**
* Calls main network stack loops * Calls main network stack loops
*/ */
void threadMain() void threadMain() throw();
throw();
/** /**
* For moving data onto the ZeroTier virtual wire * For moving data onto the ZeroTier virtual wire
*/ */
void (*_handler)(void *, void *, uint64_t, const MAC &, const MAC &, unsigned int, unsigned int, void (*_handler)(
const void *, unsigned int); void*,
void*,
uint64_t,
const MAC&,
const MAC&,
unsigned int,
unsigned int,
const void*,
unsigned int);
void* netif4 = NULL; void* netif4 = NULL;
void* netif6 = NULL; void* netif6 = NULL;
@@ -166,10 +180,19 @@ public:
// Not used in this implementation // // Not used in this implementation //
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *local_address, void phyOnDatagram(
const struct sockaddr *from,void *data,unsigned long len); 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 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); const struct sockaddr* from);
void phyOnTcpClose(PhySocket* sock, void** uptr); void phyOnTcpClose(PhySocket* sock, void** uptr);
void phyOnTcpData(PhySocket* sock, void** uptr, void* data, unsigned long len); 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. * @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(); void _lwip_driver_init();
/** /**
* @brief Shutdown the stack as completely as possible (not officially supported by lwIP) * @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. * @usage This is to be called after it is determined that no further network activity will take
* The tcpip thread will be stopped, all interfaces will be brought down and all resources will * place. The tcpip thread will be stopped, all interfaces will be brought down and all resources
* be deallocated. A full application restart will be required to bring the stack back online. * will be deallocated. A full application restart will be required to bring the stack back online.
*/ */
void _lwip_driver_shutdown(); void _lwip_driver_shutdown();
@@ -246,7 +270,8 @@ static void _netif_remove_callback(struct netif *netif);
#endif #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 #if LWIP_NETIF_LINK_CALLBACK
static void _netif_link_callback(struct netif* netif); 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); 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. * @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 * @param p A pointer to the beginning of a chain pf struct pbufs
* @return * @return
*/ */
@@ -289,10 +316,14 @@ err_t _lwip_eth_tx(struct netif *netif, struct pbuf *p);
* @param data Pointer to Ethernet frame * @param data Pointer to Ethernet frame
* @param len Length of Ethernet frame * @param len Length of Ethernet frame
*/ */
void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int etherType, void _lwip_eth_rx(
const void *data, unsigned int len); VirtualTap* tap,
const MAC& from,
const MAC& to,
unsigned int etherType,
const void* data,
unsigned int len);
} // namespace ZeroTier } // namespace ZeroTier
#endif // _H #endif // _H