diff --git a/examples/cpp/adhoc.cpp b/examples/cpp/adhoc.cpp index b83ece2..812cbc9 100644 --- a/examples/cpp/adhoc.cpp +++ b/examples/cpp/adhoc.cpp @@ -86,14 +86,15 @@ * */ +#include "ZeroTierSockets.h" + #include #include -#include "ZeroTierSockets.h" - -struct Node -{ - Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} +struct Node { + Node() : online(false), joinedAtLeastOneNetwork(false), id(0) + { + } bool online; bool joinedAtLeastOneNetwork; uint64_t id; @@ -104,9 +105,9 @@ struct Node to ensure timely receipt of future events. You should not call libzt API functions from this function unless it's something trivial like zts_inet_ntop() or similar that has no state-change implications. */ -void on_zts_event(void *msgPtr) +void on_zts_event(void* msgPtr) { - struct zts_callback_msg *msg = (struct zts_callback_msg *)msgPtr; + struct zts_callback_msg* msg = (struct zts_callback_msg*)msgPtr; // Node events if (msg->eventCode == ZTS_EVENT_NODE_ONLINE) { @@ -115,25 +116,34 @@ void on_zts_event(void *msgPtr) myNode.online = true; } if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { - printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n"); + printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, " + "firewall, etc. What ports are you blocking?\n"); myNode.online = false; } // Virtual network events if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { - printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { - printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a " + "few seconds...\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { - printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. " + "Did you authorize the node yet?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { - printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) { @@ -142,24 +152,25 @@ void on_zts_event(void *msgPtr) // Network stack events if (msg->eventCode == ZTS_EVENT_NETIF_UP) { - printf("ZTS_EVENT_NETIF_UP --- network=%llx, mac=%llx, mtu=%d\n", - msg->netif->nwid, - msg->netif->mac, - msg->netif->mtu); + printf( + "ZTS_EVENT_NETIF_UP --- network=%llx, mac=%llx, mtu=%d\n", + msg->netif->nwid, + msg->netif->mac, + msg->netif->mtu); } if (msg->eventCode == ZTS_EVENT_NETIF_DOWN) { - printf("ZTS_EVENT_NETIF_DOWN --- network=%llx, mac=%llx\n", - msg->netif->nwid, - msg->netif->mac); + printf( + "ZTS_EVENT_NETIF_DOWN --- network=%llx, mac=%llx\n", + msg->netif->nwid, + msg->netif->mac); } // Address events if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n", - msg->addr->nwid, ipstr); + printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr); } // Peer events @@ -170,19 +181,23 @@ void on_zts_event(void *msgPtr) return; } if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { - printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { - printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for " + "node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { - printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", + msg->peer->address); } } } @@ -212,46 +227,55 @@ be taken to avoid exposing vulnerable services or sharing unwanted files or othe */ -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 5) { printf("\nlibzt example\n"); printf("adhoc \n"); exit(0); } - int adhocStartPort = atoi(argv[2]); // Start of port range your application will use - int adhocEndPort = atoi(argv[3]); // End of port range your application will use - int ztServicePort = atoi(argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) + int adhocStartPort = atoi(argv[2]); // Start of port range your application will use + int adhocEndPort = atoi(argv[3]); // End of port range your application will use + int ztServicePort = atoi( + argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) uint64_t adhoc_nwid = zts_generate_adhoc_nwid_from_range(adhocStartPort, adhocEndPort); int err = ZTS_ERR_OK; - // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node + // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take + // slightly longer to start the node zts_allow_network_caching(1); - // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer + // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take + // slightly longer to contact a remote peer zts_allow_peer_caching(1); // If disabled: Settings will NOT be read from local.conf zts_allow_local_conf(1); - if((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { + if ((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { printf("Unable to start service, error = %d. Exiting.\n", err); exit(1); } printf("Waiting for node to come online...\n"); - while (!myNode.online) { zts_delay_ms(50); } + while (! myNode.online) { + zts_delay_ms(50); + } printf("This node's identity is stored in %s\n", argv[1]); - if((err = zts_join(adhoc_nwid)) != ZTS_ERR_OK) { + if ((err = zts_join(adhoc_nwid)) != ZTS_ERR_OK) { printf("Unable to join network, error = %d. Exiting.\n", err); exit(1); } printf("Joining network %llx\n", adhoc_nwid); - while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); } + while (! myNode.joinedAtLeastOneNetwork) { + zts_delay_ms(50); + } // Idle and just show callback events, stack statistics, etc printf("Node will now idle...\n"); - while (true) { zts_delay_ms(1000); } + while (true) { + zts_delay_ms(1000); + } // Shut down service and stack threads diff --git a/examples/cpp/centralapi.cpp b/examples/cpp/centralapi.cpp index f5fa9f6..f0e0286 100644 --- a/examples/cpp/centralapi.cpp +++ b/examples/cpp/centralapi.cpp @@ -1,17 +1,16 @@ +#include "ZeroTierSockets.h" + +#include +#include #include #include #include - #include -#include -#include - -#include "ZeroTierSockets.h" // For optional JSON parsing #include "../ext/ZeroTierOne/ext/json/json.hpp" -void process_response(char *response, int http_response_code) +void process_response(char* response, int http_response_code) { if (http_response_code == 0) { // Request failed at library level, do nothing. There would be no HTTP code at this point. @@ -23,22 +22,22 @@ void process_response(char *response, int http_response_code) return; } nlohmann::json res = nlohmann::json::parse(response); - if (!res.is_object()) { + if (! res.is_object()) { fprintf(stderr, "Unable to parse (root element is not a JSON object)"); } // Pretty print JSON blob std::cout << std::setw(4) << res << std::endl; } -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 3) { printf("\nlibzt example central API client\n"); printf("centralapi \n"); exit(0); } - std::string central_url = argv[1]; // API endpoint - std::string api_token = argv[2]; // User token (generate at my.zerotier.com) + std::string central_url = argv[1]; // API endpoint + std::string api_token = argv[2]; // User token (generate at my.zerotier.com) /** * This example demonstrates how to use the ZeroTier Central API to: @@ -67,12 +66,17 @@ int main(int argc, char **argv) // Provide URL to Central API server and user API token generated at https://my.zerotier.com printf("Initializing Central API client...\n"); - if ((err = zts_central_init(central_url.c_str(), api_token.c_str(), rbuf, ZTS_CENTRAL_RESP_BUF_DEFAULT_SZ)) != ZTS_ERR_OK) { + if ((err = zts_central_init( + central_url.c_str(), + api_token.c_str(), + rbuf, + ZTS_CENTRAL_RESP_BUF_DEFAULT_SZ)) + != ZTS_ERR_OK) { fprintf(stderr, "Error while initializing client's Central API parameters\n"); return 0; } - zts_central_set_verbose(false); // (optiona) Turn on reporting from libcurl + zts_central_set_verbose(false); // (optiona) Turn on reporting from libcurl zts_central_set_access_mode(ZTS_CENTRAL_READ | ZTS_CENTRAL_WRITE); int http_res_code = 0; @@ -81,7 +85,8 @@ int main(int argc, char **argv) printf("Requesting Central API server status (/api/status):\n"); if ((err = zts_central_get_status(&http_res_code)) != ZTS_ERR_OK) { fprintf(stderr, "Error (%d) making the request.\n", err); - } else { + } + else { process_response(rbuf, http_res_code); } // Get network config @@ -89,15 +94,18 @@ int main(int argc, char **argv) printf("Requesting network config: /api/network/%llx\n", nwid); if ((err = zts_central_get_network(&http_res_code, nwid)) != ZTS_ERR_OK) { fprintf(stderr, "Error (%d) making the request.\n", err); - } else { + } + else { process_response(rbuf, http_res_code); } // Authorize a node on a network int64_t nodeid = 0x9934343434; printf("Authorizing: /api/network/%llx/member/%llx\n", nwid, nodeid); - if ((err = zts_central_set_node_auth(&http_res_code, nwid, nodeid, ZTS_CENTRAL_NODE_AUTH_TRUE)) != ZTS_ERR_OK) { + if ((err = zts_central_set_node_auth(&http_res_code, nwid, nodeid, ZTS_CENTRAL_NODE_AUTH_TRUE)) + != ZTS_ERR_OK) { fprintf(stderr, "Error (%d) making the request.\n", err); - } else { + } + else { process_response(rbuf, http_res_code); } diff --git a/examples/cpp/client.cpp b/examples/cpp/client.cpp index c05483b..799dcf2 100644 --- a/examples/cpp/client.cpp +++ b/examples/cpp/client.cpp @@ -2,16 +2,17 @@ * libzt API example */ +#include "ZeroTierSockets.h" + #include #include #include #include -#include "ZeroTierSockets.h" - -struct Node -{ - Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} +struct Node { + Node() : online(false), joinedAtLeastOneNetwork(false), id(0) + { + } bool online; bool joinedAtLeastOneNetwork; uint64_t id; @@ -22,9 +23,9 @@ struct Node to ensure timely receipt of future events. You should not call libzt API functions from this function unless it's something trivial like zts_inet_ntop() or similar that has no state-change implications. */ -void on_zts_event(void *msgPtr) +void on_zts_event(void* msgPtr) { - struct zts_callback_msg *msg = (struct zts_callback_msg *)msgPtr; + struct zts_callback_msg* msg = (struct zts_callback_msg*)msgPtr; // Node events if (msg->eventCode == ZTS_EVENT_NODE_ONLINE) { @@ -33,7 +34,8 @@ void on_zts_event(void *msgPtr) myNode.online = true; } if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { - printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n"); + printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, " + "firewall, etc. What ports are you blocking?\n"); myNode.online = false; } if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { @@ -42,24 +44,34 @@ void on_zts_event(void *msgPtr) // Virtual network events if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { - printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { - printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a " + "few seconds...\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { - printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. " + "Did you authorize the node yet?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { - printf("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { - printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) { @@ -69,31 +81,41 @@ void on_zts_event(void *msgPtr) // Address events if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP4) { 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); - printf("ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) { char ipstr[ZTS_INET_ADDRSTRLEN]; - struct zts_sockaddr_in *in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); + struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } // Peer events if (msg->peer) { @@ -103,19 +125,23 @@ void on_zts_event(void *msgPtr) return; } if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { - printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { - printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for " + "node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { - printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", + msg->peer->address); } } } @@ -202,17 +228,18 @@ void on_zts_event(void *msgPtr) * */ -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 6) { printf("\nlibzt example client\n"); printf("client \n"); exit(0); } - uint64_t nwid = strtoull(argv[2],NULL,16); // Network ID to join - std::string remoteAddr = argv[3]; // Remote application's virtual ZT address - int remotePort = atoi(argv[4]); // Port the application will try to connect to the server on - int ztServicePort = atoi(argv[5]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) + uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join + std::string remoteAddr = argv[3]; // Remote application's virtual ZT address + int remotePort = atoi(argv[4]); // Port the application will try to connect to the server on + int ztServicePort = atoi( + argv[5]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) struct zts_sockaddr_in in4; in4.sin_port = htons(remotePort); @@ -227,33 +254,39 @@ int main(int argc, char **argv) int err = ZTS_ERR_OK; - // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node + // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take + // slightly longer to start the node zts_allow_network_caching(1); - // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer + // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take + // slightly longer to contact a remote peer zts_allow_peer_caching(1); // If disabled: Settings will NOT be read from local.conf zts_allow_local_conf(1); - if((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { + if ((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { printf("Unable to start service, error = %d. Exiting.\n", err); exit(1); } printf("Waiting for node to come online...\n"); - while (!myNode.online) { zts_delay_ms(50); } + while (! myNode.online) { + zts_delay_ms(50); + } printf("This node's identity is stored in %s\n", argv[1]); - if((err = zts_join(nwid)) != ZTS_ERR_OK) { + if ((err = zts_join(nwid)) != ZTS_ERR_OK) { printf("Unable to join network, error = %d. Exiting.\n", err); exit(1); } printf("Joining network %llx\n", nwid); printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); - while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); } + while (! myNode.joinedAtLeastOneNetwork) { + zts_delay_ms(50); + } // Socket-like API example - char *msgStr = (char*)"Welcome to the machine"; - int bytes=0, fd; + char* msgStr = (char*)"Welcome to the machine"; + int bytes = 0, fd; char recvBuf[128]; memset(recvBuf, 0, sizeof(recvBuf)); @@ -264,13 +297,19 @@ int main(int argc, char **argv) // Retries are often required since ZT uses transport-triggered links (explained above) for (;;) { printf("Connecting to remote host...\n"); - if ((err = zts_connect(fd, (const struct zts_sockaddr *)&in4, sizeof(in4))) < 0) { - printf("Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n", - fd, err, zts_errno); + if ((err = zts_connect(fd, (const struct zts_sockaddr*)&in4, sizeof(in4))) < 0) { + printf( + "Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n", + fd, + err, + zts_errno); zts_close(fd); printf("Creating socket...\n"); if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { - printf("Error creating ZeroTier socket (fd=%d, zts_errno=%d). Exiting.\n", fd, zts_errno); + printf( + "Error creating ZeroTier socket (fd=%d, zts_errno=%d). Exiting.\n", + fd, + zts_errno); exit(1); } zts_delay_ms(250); @@ -281,14 +320,22 @@ int main(int argc, char **argv) } } printf("Sending message string to server...\n"); - if((bytes = zts_write(fd, msgStr, strlen(msgStr))) < 0) { - printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno); + 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); exit(1); } printf("Sent %d bytes: %s\n", bytes, msgStr); printf("Reading message string from server...\n"); - if((bytes = zts_read(fd, recvBuf, sizeof(recvBuf))) < 0) { - printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno); + 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); exit(1); } printf("Read %d bytes: %s\n", bytes, recvBuf); diff --git a/examples/cpp/comprehensive.cpp b/examples/cpp/comprehensive.cpp index 385b101..9aee249 100644 --- a/examples/cpp/comprehensive.cpp +++ b/examples/cpp/comprehensive.cpp @@ -86,55 +86,64 @@ * */ +#include "ZeroTierSockets.h" + #include #include #include -#include "ZeroTierSockets.h" - #ifdef __WINDOWS__ -#include "winsock.h" + #include "winsock.h" #endif -struct Node -{ - Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} +struct Node { + Node() : online(false), joinedAtLeastOneNetwork(false), id(0) + { + } bool online; bool joinedAtLeastOneNetwork; uint64_t id; // etc } myNode; -void printNodeDetails(const char *msgStr, struct zts_node_details *d) +void printNodeDetails(const char* msgStr, struct zts_node_details* d) { printf("\n%s\n", msgStr); printf("\t- id : %llx\n", d->address); - printf("\t- version : %d.%d.%d\n", d->versionMajor, d->versionMinor, d->versionRev); + printf( + "\t- version : %d.%d.%d\n", + d->versionMajor, + d->versionMinor, + d->versionRev); printf("\t- primaryPort : %d\n", d->primaryPort); printf("\t- secondaryPort : %d\n", d->secondaryPort); } -void printPeerDetails(const char *msgStr, struct zts_peer_details *d) +void printPeerDetails(const char* msgStr, struct zts_peer_details* d) { printf("\n%s\n", msgStr); printf("\t- peer : %llx\n", d->address); printf("\t- role : %llx\n", d->role); printf("\t- latency : %d\n", d->latency); - printf("\t- version : %d.%d.%d\n", d->versionMajor, d->versionMinor, d->versionRev); + printf( + "\t- version : %d.%d.%d\n", + d->versionMajor, + d->versionMinor, + d->versionRev); printf("\t- pathCount : %d\n", d->pathCount); printf("\t- paths:\n"); // Print all known paths for each peer - for (unsigned int j=0; jpathCount; j++) { + for (unsigned int j = 0; j < d->pathCount; j++) { char ipstr[ZTS_INET6_ADDRSTRLEN]; int port = 0; - struct zts_sockaddr *sa = (struct zts_sockaddr *)&(d->paths[j].address); + struct zts_sockaddr* sa = (struct zts_sockaddr*)&(d->paths[j].address); 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), ipstr, ZTS_INET_ADDRSTRLEN); port = ntohs(in4->sin_port); } if (sa->sa_family == ZTS_AF_INET6) { - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)sa; + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)sa; zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); } printf("\t - %15s : %6d\n", ipstr, port); @@ -142,7 +151,7 @@ void printPeerDetails(const char *msgStr, struct zts_peer_details *d) printf("\n"); } -void printNetworkDetails(const char *msgStr, struct zts_network_details *d) +void printNetworkDetails(const char* msgStr, struct zts_network_details* d) { printf("\n%s\n", msgStr); printf("\t- nwid : %llx\n", d->nwid); @@ -159,54 +168,57 @@ void printNetworkDetails(const char *msgStr, struct zts_network_details *d) printf("\t- routeCount : %d\n", d->routeCount); printf("\t- multicastSubscriptionCount : %d\n", d->multicastSubscriptionCount); - for (int i=0; imulticastSubscriptionCount; i++) { - printf("\t - mac=%llx, adi=%x\n", d->multicastSubscriptions[i].mac, d->multicastSubscriptions[i].adi); + 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- addresses:\n"); - for (int i=0; iassignedAddressCount; i++) { + for (int i = 0; i < d->assignedAddressCount; i++) { if (d->assignedAddresses[i].ss_family == ZTS_AF_INET) { char ipstr[ZTS_INET_ADDRSTRLEN]; - struct zts_sockaddr_in *in4 = (struct zts_sockaddr_in*)&(d->assignedAddresses[i]); + struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(d->assignedAddresses[i]); zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); - printf("\t - %s\n",ipstr); + printf("\t - %s\n", ipstr); } if (d->assignedAddresses[i].ss_family == ZTS_AF_INET6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(d->assignedAddresses[i]); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(d->assignedAddresses[i]); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("\t - %s\n",ipstr); + printf("\t - %s\n", ipstr); } } printf("\t- routes:\n"); - for (int i=0; irouteCount; i++) { + for (int i = 0; i < d->routeCount; i++) { if (d->routes[i].target.ss_family == ZTS_AF_INET) { char ipstr[ZTS_INET_ADDRSTRLEN]; - struct zts_sockaddr_in *in4 = (struct zts_sockaddr_in*)&(d->routes[i].target); + struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(d->routes[i].target); zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); - printf("\t - target : %s\n",ipstr); + printf("\t - target : %s\n", ipstr); in4 = (struct zts_sockaddr_in*)&(d->routes[i].via); zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); - printf("\t - via : %s\n",ipstr); + printf("\t - via : %s\n", ipstr); } if (d->routes[i].target.ss_family == ZTS_AF_INET6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(d->routes[i].target); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(d->routes[i].target); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("\t - target : %s\n",ipstr); + printf("\t - target : %s\n", ipstr); in6 = (struct zts_sockaddr_in6*)&(d->routes[i].via); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("\t - via : %s\n",ipstr); + printf("\t - via : %s\n", ipstr); } printf("\t - flags : %d\n", d->routes[i].flags); printf("\t - metric : %d\n", d->routes[i].metric); } } -void printNetifDetails(const char *msgStr, struct zts_netif_details *d) +void printNetifDetails(const char* msgStr, struct zts_netif_details* d) { printf("\n%s\n", msgStr); printf("\t- nwid : %llx\n", d->nwid); @@ -218,9 +230,9 @@ void printNetifDetails(const char *msgStr, struct zts_netif_details *d) to ensure timely receipt of future events. You should not call libzt API functions from this function unless it's something trivial like zts_inet_ntop() or similar that has no state-change implications. */ -void on_zts_event(void *msgPtr) +void on_zts_event(void* msgPtr) { - struct zts_callback_msg *msg = (struct zts_callback_msg *)msgPtr; + struct zts_callback_msg* msg = (struct zts_callback_msg*)msgPtr; printf("eventCode=%d\n", msg->eventCode); // Node events @@ -230,33 +242,44 @@ void on_zts_event(void *msgPtr) myNode.online = true; } if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { - printf("\nZTS_EVENT_NODE_OFFLINE --- Check your Internet connection, router, firewall, etc. What ports are you blocking?\n"); + printf("\nZTS_EVENT_NODE_OFFLINE --- Check your Internet connection, router, firewall, " + "etc. What ports are you blocking?\n"); myNode.online = false; } if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { - printf("\nZTS_EVENT_NODE_NORMAL_TERMINATION -- A call to zts_start() will restart ZeroTier.\n"); + printf("\nZTS_EVENT_NODE_NORMAL_TERMINATION -- A call to zts_start() will restart " + "ZeroTier.\n"); myNode.online = false; } // Virtual network events if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { - printf("\nZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", - msg->network->nwid); + printf( + "\nZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { - printf("\nZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", - msg->network->nwid); + printf( + "\nZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a " + "few seconds...\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { - printf("\nZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n", - msg->network->nwid); + printf( + "\nZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. " + "Did you authorize the node yet?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { - printNetworkDetails("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received.", msg->network); + printNetworkDetails( + "ZTS_EVENT_NETWORK_READY_IP4 --- Network config received.", + msg->network); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { - printNetworkDetails("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received.", msg->network); + printNetworkDetails( + "ZTS_EVENT_NETWORK_READY_IP6 --- Network config received.", + msg->network); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) { @@ -269,31 +292,41 @@ void on_zts_event(void *msgPtr) // Address events if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP4) { 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); - printf("\nZTS_EVENT_ADDR_ADDED_IP4 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "\nZTS_EVENT_ADDR_ADDED_IP4 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("\nZTS_EVENT_ADDR_ADDED_IP6 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "\nZTS_EVENT_ADDR_ADDED_IP6 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) { char ipstr[ZTS_INET_ADDRSTRLEN]; - struct zts_sockaddr_in *in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); + struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); - printf("\nZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "\nZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("\nZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "\nZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } // Peer events @@ -310,7 +343,9 @@ void on_zts_event(void *msgPtr) printPeerDetails("ZTS_EVENT_PEER_RELAY --- No direct path known.", msg->peer); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { - printPeerDetails("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered.", msg->peer); + printPeerDetails( + "ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered.", + msg->peer); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { printPeerDetails("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died.", msg->peer); @@ -338,16 +373,17 @@ void on_zts_event(void *msgPtr) printf("\nZTS_EVENT_STACK_UP --- No action required.\n"); } if (msg->eventCode == ZTS_EVENT_STACK_DOWN) { - printf("\nZTS_EVENT_STACK_DOWN --- No action required. An app restart is needed to use ZeroTier again.\n"); + printf("\nZTS_EVENT_STACK_DOWN --- No action required. An app restart is needed to use " + "ZeroTier again.\n"); } } void get6PLANEAddressOfPeer(uint64_t peerId, uint64_t nwId) { - char peerAddrStr[ZTS_INET6_ADDRSTRLEN] = {0}; + char peerAddrStr[ZTS_INET6_ADDRSTRLEN] = { 0 }; struct zts_sockaddr_storage sixplane_addr; zts_get_6plane_addr(&sixplane_addr, nwId, peerId); - struct zts_sockaddr_in6 *p6 = (struct zts_sockaddr_in6*)&sixplane_addr; + struct zts_sockaddr_in6* p6 = (struct zts_sockaddr_in6*)&sixplane_addr; zts_inet_ntop(ZTS_AF_INET6, &(p6->sin6_addr), peerAddrStr, ZTS_INET6_ADDRSTRLEN); printf("6PLANE address of peer is: %s\n", peerAddrStr); } @@ -358,7 +394,8 @@ void display_stack_stats() { int err = 0; // Count received pings - if ((err = zts_get_protocol_stats(ZTS_STATS_PROTOCOL_ICMP, &protoSpecificStats)) != ZTS_ERR_OK) { + if ((err = zts_get_protocol_stats(ZTS_STATS_PROTOCOL_ICMP, &protoSpecificStats)) + != ZTS_ERR_OK) { printf("zts_get_proto_stats()=%d", err); return; } @@ -371,7 +408,7 @@ void display_stack_stats() printf("tcp.drop=%d\n", protoSpecificStats.drop); } -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 4) { printf("\nlibzt example server\n"); @@ -379,52 +416,59 @@ int main(int argc, char **argv) exit(0); } std::string configPath = std::string(argv[1]); - uint64_t nwid = strtoull(argv[2],NULL,16); // Network ID to join - int ztServicePort = atoi(argv[3]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) + 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) // Bring up ZeroTier service and join network int err = ZTS_ERR_OK; - // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node + // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take + // slightly longer to start the node zts_allow_network_caching(1); - // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer + // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take + // slightly longer to contact a remote peer zts_allow_peer_caching(1); // If disabled: Settings will NOT be read from local.conf zts_allow_local_conf(1); - if((err = zts_start(configPath.c_str(), &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { + if ((err = zts_start(configPath.c_str(), &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { printf("Unable to start service, error = %d. Exiting.\n", err); exit(1); } printf("Waiting for node to come online...\n"); - while (!myNode.online) { zts_delay_ms(50); } + while (! myNode.online) { + zts_delay_ms(50); + } printf("This node's identity is stored in %s\n", argv[1]); - if((err = zts_join(nwid)) != ZTS_ERR_OK) { + if ((err = zts_join(nwid)) != ZTS_ERR_OK) { printf("Unable to join network, error = %d. Exiting.\n", err); exit(1); } printf("Joining network %llx\n", nwid); printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); - while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); } + while (! myNode.joinedAtLeastOneNetwork) { + zts_delay_ms(50); + } // Idle and just show callback events, stack statistics, etc // Alternatively, this is where you could start making calls to the socket API /* while(true) { - display_stack_stats(); - zts_delay_ms(1000); + display_stack_stats(); + zts_delay_ms(1000); } */ int delay = 500000; printf("This program will delay for %d seconds and then shut down.\n", (delay / 1000)); zts_delay_ms(delay); - //printf("Leaving network %llx\n", nwid); - //zts_leave(nwid); - //zts_delay_ms(3000); /* added for demo purposes so that events show up */ + // printf("Leaving network %llx\n", nwid); + // zts_leave(nwid); + // zts_delay_ms(3000); /* added for demo purposes so that events show up */ printf("Stopping ZeroTier\n"); zts_stop(); zts_delay_ms(delay); /* added for demo purposes so that events show up */ diff --git a/examples/cpp/earthtest.cpp b/examples/cpp/earthtest.cpp index 0807fa6..02e244c 100644 --- a/examples/cpp/earthtest.cpp +++ b/examples/cpp/earthtest.cpp @@ -86,14 +86,15 @@ * */ +#include "ZeroTierSockets.h" + #include #include -#include "ZeroTierSockets.h" - -struct Node -{ - Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} +struct Node { + Node() : online(false), joinedAtLeastOneNetwork(false), id(0) + { + } bool online; bool joinedAtLeastOneNetwork; uint64_t id; @@ -104,9 +105,9 @@ struct Node to ensure timely receipt of future events. You should not call libzt API functions from this function unless it's something trivial like zts_inet_ntop() or similar that has no state-change implications. */ -void on_zts_event(void *msgPtr) +void on_zts_event(void* msgPtr) { - struct zts_callback_msg *msg = (struct zts_callback_msg *)msgPtr; + struct zts_callback_msg* msg = (struct zts_callback_msg*)msgPtr; if (msg->eventCode == ZTS_EVENT_NODE_ONLINE) { printf("ZTS_EVENT_NODE_ONLINE --- This node's ID is %llx\n", msg->node->address); @@ -114,19 +115,27 @@ void on_zts_event(void *msgPtr) myNode.online = true; } if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { - printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n"); + printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, " + "firewall, etc. What ports are you blocking?\n"); myNode.online = false; } if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { - printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a " + "few seconds...\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { - printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. " + "Did you authorize the node yet?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { - printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) { @@ -134,17 +143,15 @@ void on_zts_event(void *msgPtr) } if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP4) { 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); - printf("ZTS_EVENT_ADDR_NEW_IP4 --- Join %llx and ping me at %s\n", - msg->addr->nwid, ipstr); + printf("ZTS_EVENT_ADDR_NEW_IP4 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n", - msg->addr->nwid, ipstr); + printf("ZTS_EVENT_ADDR_NEW_IP6 --- Join %llx and ping me at %s\n", msg->addr->nwid, ipstr); } // Peer events if (msg->peer) { @@ -154,62 +161,75 @@ void on_zts_event(void *msgPtr) return; } if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { - printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { - printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for " + "node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { - printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", + msg->peer->address); } } } -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 3) { printf("\nlibzt example\n"); printf("earthtest \n"); exit(0); } - int ztServicePort = atoi(argv[2]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) + int ztServicePort = atoi( + argv[2]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) int err = ZTS_ERR_OK; - // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node + // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take + // slightly longer to start the node zts_allow_network_caching(1); - // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer + // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take + // slightly longer to contact a remote peer zts_allow_peer_caching(1); // If disabled: Settings will NOT be read from local.conf zts_allow_local_conf(1); - if((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { + if ((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { printf("Unable to start service, error = %d. Exiting.\n", err); exit(1); } printf("Waiting for node to come online...\n"); - while (!myNode.online) { zts_delay_ms(50); } + while (! myNode.online) { + zts_delay_ms(50); + } printf("This node's identity is stored in %s\n", argv[1]); uint64_t nwid = 0x8056c2e21c000001; - if((err = zts_join(nwid)) != ZTS_ERR_OK) { + if ((err = zts_join(nwid)) != ZTS_ERR_OK) { printf("Unable to join network, error = %d. Exiting.\n", err); exit(1); } printf("Joining network %llx\n", nwid); - while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); } + while (! myNode.joinedAtLeastOneNetwork) { + zts_delay_ms(50); + } // Idle and just show callback events, stack statistics, etc printf("Node will now idle...\n"); - while (true) { zts_delay_ms(1000); } + while (true) { + zts_delay_ms(1000); + } // Shut down service and stack threads diff --git a/examples/cpp/keymanagement.cpp b/examples/cpp/keymanagement.cpp index 8164db7..88571f9 100644 --- a/examples/cpp/keymanagement.cpp +++ b/examples/cpp/keymanagement.cpp @@ -5,15 +5,16 @@ * local storage. In this mode you are responsible for saving keys. */ +#include "ZeroTierSockets.h" + #include #include #include -#include "ZeroTierSockets.h" - -struct Node -{ - Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} +struct Node { + Node() : online(false), joinedAtLeastOneNetwork(false), id(0) + { + } bool online; bool joinedAtLeastOneNetwork; uint64_t id; @@ -24,9 +25,9 @@ struct Node to ensure timely receipt of future events. You should not call libzt API functions from this function unless it's something trivial like zts_inet_ntop() or similar that has no state-change implications. */ -void on_zts_event(void *msgPtr) +void on_zts_event(void* msgPtr) { - struct zts_callback_msg *msg = (struct zts_callback_msg *)msgPtr; + struct zts_callback_msg* msg = (struct zts_callback_msg*)msgPtr; if (msg->eventCode == ZTS_EVENT_NODE_ONLINE) { printf("ZTS_EVENT_NODE_ONLINE --- This node's ID is %llx\n", msg->node->address); @@ -34,36 +35,39 @@ void on_zts_event(void *msgPtr) myNode.online = true; } if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { - printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n"); + printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, " + "firewall, etc. What ports are you blocking?\n"); myNode.online = false; } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { - printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } } #define KEY_BUF_LEN 2048 -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 3) { printf("\nlibzt example\n"); printf("earthtest \n"); exit(0); } - int ztServicePort = atoi(argv[2]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) + int ztServicePort = atoi( + argv[2]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) int err = ZTS_ERR_OK; - // BEGIN key handling - // Do not allow ZT to write anything to disk zts_disable_local_storage(1); - // Buffer used to store identity keypair (if someone can read this, they can impersonate your node!) + // Buffer used to store identity keypair (if someone can read this, they can impersonate your + // node!) char keypair[KEY_BUF_LEN]; memset(keypair, 0, KEY_BUF_LEN); @@ -77,15 +81,18 @@ int main(int argc, char **argv) printf("\n\nVerifying ident...\n"); if (zts_verify_identity(keypair)) { printf("\tIdentity is valid\n"); - } else { + } + else { printf("\tIdentity is invalid\n"); } printf("\n\nStarting node with generated identity...\n"); zts_start_with_identity(keypair, keypair_len, &on_zts_event, ztServicePort); - + printf("\n\nWaiting for node to come online...\n"); - while (!myNode.online) { zts_delay_ms(50); } + while (! myNode.online) { + zts_delay_ms(50); + } printf("\n\nAs a test, copy node's identity keypair back into buffer...\n"); memset(keypair, 0, KEY_BUF_LEN); @@ -93,23 +100,25 @@ int main(int argc, char **argv) zts_get_node_identity(keypair, &keypair_len); printf("keypair(len=%d) = [%s]\n", keypair_len, keypair); - // END key handling - uint64_t nwid = 0x8056c2e21c000001; - if((err = zts_join(nwid)) != ZTS_ERR_OK) { + if ((err = zts_join(nwid)) != ZTS_ERR_OK) { printf("Unable to join network, error = %d. Exiting.\n", err); exit(1); } printf("Joining network %llx\n", nwid); - while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); } + while (! myNode.joinedAtLeastOneNetwork) { + zts_delay_ms(50); + } // Idle and just show callback events, stack statistics, etc printf("Node will now idle...\n"); - while (true) { zts_delay_ms(1000); } + while (true) { + zts_delay_ms(1000); + } // Shut down service and stack threads diff --git a/examples/cpp/nonblockingclient.cpp b/examples/cpp/nonblockingclient.cpp index a5635da..b801029 100644 --- a/examples/cpp/nonblockingclient.cpp +++ b/examples/cpp/nonblockingclient.cpp @@ -84,16 +84,17 @@ * */ +#include "ZeroTierSockets.h" + #include #include #include #include -#include "ZeroTierSockets.h" - -struct Node -{ - Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} +struct Node { + Node() : online(false), joinedAtLeastOneNetwork(false), id(0) + { + } bool online; bool joinedAtLeastOneNetwork; uint64_t id; @@ -104,9 +105,9 @@ struct Node to ensure timely receipt of future events. You should not call libzt API functions from this function unless it's something trivial like zts_inet_ntop() or similar that has no state-change implications. */ -void on_zts_event(void *msgPtr) +void on_zts_event(void* msgPtr) { - struct zts_callback_msg *msg = (struct zts_callback_msg *)msgPtr; + struct zts_callback_msg* msg = (struct zts_callback_msg*)msgPtr; // Node events if (msg->eventCode == ZTS_EVENT_NODE_ONLINE) { @@ -115,7 +116,8 @@ void on_zts_event(void *msgPtr) myNode.online = true; } if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { - printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n"); + printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, " + "firewall, etc. What ports are you blocking?\n"); myNode.online = false; } if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { @@ -125,25 +127,34 @@ void on_zts_event(void *msgPtr) // Virtual network events if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { - printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { - printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a " + "few seconds...\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { - printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. " + "Did you authorize the node yet?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { - printf("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { - printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) { @@ -153,31 +164,41 @@ void on_zts_event(void *msgPtr) // Address events if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP4) { 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); - printf("ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) { char ipstr[ZTS_INET_ADDRSTRLEN]; - struct zts_sockaddr_in *in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); + struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } // Peer events @@ -188,34 +209,40 @@ void on_zts_event(void *msgPtr) return; } if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { - printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { - printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for " + "node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { - printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", + msg->peer->address); } } } -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 6) { printf("\nlibzt example non-blocking client\n"); - printf("nonblockingclient \n"); + printf("nonblockingclient " + "\n"); exit(0); } - uint64_t nwid = strtoull(argv[2],NULL,16); // Network ID to join - std::string remoteAddr = argv[3]; // Remote application's virtual ZT address - int remotePort = atoi(argv[4]); // Port the application will try to connect to the server on - int ztServicePort = atoi(argv[5]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) + uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join + std::string remoteAddr = argv[3]; // Remote application's virtual ZT address + int remotePort = atoi(argv[4]); // Port the application will try to connect to the server on + int ztServicePort = atoi( + argv[5]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) struct zts_sockaddr_in in4; in4.sin_port = htons(remotePort); @@ -230,33 +257,39 @@ int main(int argc, char **argv) int err = ZTS_ERR_OK; - // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node + // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take + // slightly longer to start the node zts_allow_network_caching(1); - // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer + // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take + // slightly longer to contact a remote peer zts_allow_peer_caching(1); // If disabled: Settings will NOT be read from local.conf zts_allow_local_conf(1); - if((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { + if ((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { printf("Unable to start service, error = %d. Exiting.\n", err); exit(1); } printf("Waiting for node to come online...\n"); - while (!myNode.online) { zts_delay_ms(50); } + while (! myNode.online) { + zts_delay_ms(50); + } printf("This node's identity is stored in %s\n", argv[1]); - if((err = zts_join(nwid)) != ZTS_ERR_OK) { + if ((err = zts_join(nwid)) != ZTS_ERR_OK) { printf("Unable to join network, error = %d. Exiting.\n", err); exit(1); } printf("Joining network %llx\n", nwid); printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); - while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); } + while (! myNode.joinedAtLeastOneNetwork) { + zts_delay_ms(50); + } // Socket-like API example - char *msgStr = (char*)"Welcome to the machine"; - int bytes=0, fd; + char* msgStr = (char*)"Welcome to the machine"; + int bytes = 0, fd; char recvBuf[128]; memset(recvBuf, 0, sizeof(recvBuf)); @@ -267,13 +300,19 @@ int main(int argc, char **argv) // Retries are often required since ZT uses transport-triggered links (explained above) for (;;) { printf("Connecting to remote host...\n"); - if ((err = zts_connect(fd, (const struct zts_sockaddr *)&in4, sizeof(in4))) < 0) { - printf("Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n", - fd, err, zts_errno); + if ((err = zts_connect(fd, (const struct zts_sockaddr*)&in4, sizeof(in4))) < 0) { + printf( + "Error connecting to remote host (fd=%d, ret=%d, zts_errno=%d). Trying again.\n", + fd, + err, + zts_errno); zts_close(fd); printf("Creating socket...\n"); if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { - printf("Error creating ZeroTier socket (fd=%d, zts_errno=%d). Exiting.\n", fd, zts_errno); + printf( + "Error creating ZeroTier socket (fd=%d, zts_errno=%d). Exiting.\n", + fd, + zts_errno); exit(1); } zts_delay_ms(250); @@ -286,9 +325,13 @@ int main(int argc, char **argv) // Wait random intervals to send a message to the server // The non-blocking aspect of this example is server-side - while(1) { - if((bytes = zts_send(fd, msgStr, strlen(msgStr), 0)) < 0) { - printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno); + while (1) { + if ((bytes = zts_send(fd, msgStr, strlen(msgStr), 0)) < 0) { + printf( + "Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", + fd, + bytes, + zts_errno); exit(1); } printf("zts_send()=%d\n", bytes); diff --git a/examples/cpp/nonblockingserver.cpp b/examples/cpp/nonblockingserver.cpp index e012922..9d5dd70 100644 --- a/examples/cpp/nonblockingserver.cpp +++ b/examples/cpp/nonblockingserver.cpp @@ -84,15 +84,16 @@ * */ +#include "ZeroTierSockets.h" + #include #include #include -#include "ZeroTierSockets.h" - -struct Node -{ - Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} +struct Node { + Node() : online(false), joinedAtLeastOneNetwork(false), id(0) + { + } bool online; bool joinedAtLeastOneNetwork; uint64_t id; @@ -103,9 +104,9 @@ struct Node to ensure timely receipt of future events. You should not call libzt API functions from this function unless it's something trivial like zts_inet_ntop() or similar that has no state-change implications. */ -void on_zts_event(void *msgPtr) +void on_zts_event(void* msgPtr) { - struct zts_callback_msg *msg = (struct zts_callback_msg *)msgPtr; + struct zts_callback_msg* msg = (struct zts_callback_msg*)msgPtr; // Node events if (msg->eventCode == ZTS_EVENT_NODE_ONLINE) { @@ -114,7 +115,8 @@ void on_zts_event(void *msgPtr) myNode.online = true; } if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { - printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n"); + printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, " + "firewall, etc. What ports are you blocking?\n"); myNode.online = false; } if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { @@ -124,25 +126,34 @@ void on_zts_event(void *msgPtr) // Virtual network events if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { - printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { - printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a " + "few seconds...\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { - printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. " + "Did you authorize the node yet?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { - printf("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { - printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) { @@ -152,31 +163,41 @@ void on_zts_event(void *msgPtr) // Address events if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP4) { 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); - printf("ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) { char ipstr[ZTS_INET_ADDRSTRLEN]; - struct zts_sockaddr_in *in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); + struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } // Peer events @@ -187,33 +208,38 @@ void on_zts_event(void *msgPtr) return; } if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { - printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { - printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for " + "node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { - printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", + msg->peer->address); } } } -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 5) { printf("\nlibzt example non-blocking server\n"); printf("nonblockingserver \n"); exit(0); } - uint64_t nwid = strtoull(argv[2],NULL,16); // Network ID to join - int serverBindPort = atoi(argv[3]); // Port the application should bind to - int ztServicePort = atoi(argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) + uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join + int serverBindPort = atoi(argv[3]); // Port the application should bind to + int ztServicePort = atoi( + argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) struct zts_sockaddr_in in4, acc_in4; in4.sin_port = htons(serverBindPort); @@ -229,51 +255,73 @@ int main(int argc, char **argv) int fd, accfd; int err = ZTS_ERR_OK; - // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node + // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take + // slightly longer to start the node zts_allow_network_caching(1); - // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer + // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take + // slightly longer to contact a remote peer zts_allow_peer_caching(1); // If disabled: Settings will NOT be read from local.conf zts_allow_local_conf(1); - if((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { + if ((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { printf("Unable to start service, error = %d. Exiting.\n", err); exit(1); } printf("Waiting for node to come online...\n"); - while (!myNode.online) { zts_delay_ms(50); } + while (! myNode.online) { + zts_delay_ms(50); + } printf("This node ID is %llx\n", myNode.id); printf("This node's identity is stored in %s\n", argv[1]); - if((err = zts_join(nwid)) != ZTS_ERR_OK) { + if ((err = zts_join(nwid)) != ZTS_ERR_OK) { printf("Unable to join network, error = %d. Exiting.\n", err); exit(1); } printf("Joining network %llx\n", nwid); printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); - while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); } + while (! myNode.joinedAtLeastOneNetwork) { + zts_delay_ms(50); + } // Socket-like API example printf("Creating socket...\n"); if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { - printf("Error creating ZeroTier socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",fd, err, zts_errno); + printf( + "Error creating ZeroTier socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", + fd, + err, + zts_errno); exit(1); } printf("Binding...\n"); - if ((err = zts_bind(fd, (struct zts_sockaddr *)&in4, sizeof(struct zts_sockaddr_in)) < 0)) { - printf("Error binding to interface (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno); + 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); exit(1); } printf("Listening...\n"); int backlog = 100; if ((err = zts_listen(fd, backlog)) < 0) { - printf("Error placing socket in LISTENING state (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno); + printf( + "Error placing socket in LISTENING state (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", + fd, + err, + zts_errno); exit(1); } zts_socklen_t client_addrlen = sizeof(zts_sockaddr_in); - if ((accfd = zts_accept(fd, (struct zts_sockaddr *)&acc_in4, &client_addrlen)) < 0) { - printf("Error accepting connection (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno); + 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); } zts_socklen_t peer_addrlen = sizeof(struct zts_sockaddr_storage); @@ -283,7 +331,7 @@ int main(int argc, char **argv) zts_inet_ntop(ZTS_AF_INET, &(acc_in4.sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); printf("Accepted connection from %s:%d\n", ipstr, ntohs(acc_in4.sin_port)); - int bytes=0; + int bytes = 0; char recvBuf[128]; memset(recvBuf, 0, sizeof(recvBuf)); @@ -293,7 +341,7 @@ int main(int argc, char **argv) if (false) { zts_fcntl(fd, ZTS_F_SETFL, ZTS_O_NONBLOCK); zts_fcntl(accfd, ZTS_F_SETFL, ZTS_O_NONBLOCK); - while(1) { + while (1) { bytes = zts_recv(accfd, recvBuf, sizeof(recvBuf), 0); printf("zts_recv(%d, ...)=%d\n", accfd, bytes); zts_delay_ms(100); @@ -311,21 +359,18 @@ int main(int argc, char **argv) zts_fd_set active_fd_set, read_fd_set; ZTS_FD_ZERO(&active_fd_set); ZTS_FD_SET(accfd, &active_fd_set); - while (1) - { + while (1) { read_fd_set = active_fd_set; - if ((result = zts_select(ZTS_FD_SETSIZE, &read_fd_set, NULL, NULL, &tv) < 0)) - { - //perror ("select"); - exit (1); + if ((result = zts_select(ZTS_FD_SETSIZE, &read_fd_set, NULL, NULL, &tv) < 0)) { + // perror ("select"); + exit(1); } - for (int i=0; i #include #include #include -#include "ZeroTierSockets.h" - -struct Node -{ - Node() : online(false), joinedAtLeastOneNetwork(false), id(0) {} +struct Node { + Node() : online(false), joinedAtLeastOneNetwork(false), id(0) + { + } bool online; bool joinedAtLeastOneNetwork; uint64_t id; @@ -22,9 +23,9 @@ struct Node to ensure timely receipt of future events. You should not call libzt API functions from this function unless it's something trivial like zts_inet_ntop() or similar that has no state-change implications. */ -void on_zts_event(void *msgPtr) +void on_zts_event(void* msgPtr) { - struct zts_callback_msg *msg = (struct zts_callback_msg *)msgPtr; + struct zts_callback_msg* msg = (struct zts_callback_msg*)msgPtr; // Node events if (msg->eventCode == ZTS_EVENT_NODE_ONLINE) { @@ -33,7 +34,8 @@ void on_zts_event(void *msgPtr) myNode.online = true; } if (msg->eventCode == ZTS_EVENT_NODE_OFFLINE) { - printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, firewall, etc. What ports are you blocking?\n"); + printf("ZTS_EVENT_NODE_OFFLINE --- Check your physical Internet connection, router, " + "firewall, etc. What ports are you blocking?\n"); myNode.online = false; } if (msg->eventCode == ZTS_EVENT_NODE_NORMAL_TERMINATION) { @@ -42,24 +44,34 @@ void on_zts_event(void *msgPtr) // Virtual network events if (msg->eventCode == ZTS_EVENT_NETWORK_NOT_FOUND) { - printf("ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_NOT_FOUND --- Are you sure %llx is a valid network?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_REQ_CONFIG) { - printf("ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a few seconds...\n", msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_REQ_CONFIG --- Requesting config for network %llx, please wait a " + "few seconds...\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_ACCESS_DENIED) { - printf("ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. Did you authorize the node yet?\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_ACCESS_DENIED --- Access to virtual network %llx has been denied. " + "Did you authorize the node yet?\n", + msg->network->nwid); } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP4) { - printf("ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP4 --- Network config received. IPv4 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_READY_IP6) { - printf("ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent over network %llx\n", - msg->network->nwid); + printf( + "ZTS_EVENT_NETWORK_READY_IP6 --- Network config received. IPv6 traffic can now be sent " + "over network %llx\n", + msg->network->nwid); myNode.joinedAtLeastOneNetwork = true; } if (msg->eventCode == ZTS_EVENT_NETWORK_DOWN) { @@ -69,31 +81,41 @@ void on_zts_event(void *msgPtr) // Address events if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP4) { 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); - printf("ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "ZTS_EVENT_ADDR_NEW_IP4 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_ADDED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n", - msg->addr->nwid, ipstr); + printf( + "ZTS_EVENT_ADDR_NEW_IP6 --- This node's virtual address on network %llx is %s\n", + msg->addr->nwid, + ipstr); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP4) { char ipstr[ZTS_INET_ADDRSTRLEN]; - struct zts_sockaddr_in *in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); + struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), ipstr, ZTS_INET_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "ZTS_EVENT_ADDR_REMOVED_IP4 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } if (msg->eventCode == ZTS_EVENT_ADDR_REMOVED_IP6) { char ipstr[ZTS_INET6_ADDRSTRLEN]; - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)&(msg->addr->addr); zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), ipstr, ZTS_INET6_ADDRSTRLEN); - printf("ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx has been removed.\n", - ipstr, msg->addr->nwid); + printf( + "ZTS_EVENT_ADDR_REMOVED_IP6 --- The virtual address %s for this node on network %llx " + "has been removed.\n", + ipstr, + msg->addr->nwid); } // Peer events if (msg->peer) { @@ -103,19 +125,23 @@ void on_zts_event(void *msgPtr) return; } if (msg->eventCode == ZTS_EVENT_PEER_DIRECT) { - printf("ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_DIRECT --- A direct path is known for node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_RELAY) { printf("ZTS_EVENT_PEER_RELAY --- No direct path to node=%llx\n", msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DISCOVERED) { - printf("ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DISCOVERED --- A new direct path was discovered for " + "node=%llx\n", + msg->peer->address); } if (msg->eventCode == ZTS_EVENT_PEER_PATH_DEAD) { - printf("ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", - msg->peer->address); + printf( + "ZTS_EVENT_PEER_PATH_DEAD --- A direct path has died for node=%llx\n", + msg->peer->address); } } } @@ -202,16 +228,17 @@ void on_zts_event(void *msgPtr) * */ -int main(int argc, char **argv) +int main(int argc, char** argv) { if (argc != 5) { printf("\nlibzt example server\n"); printf("server \n"); exit(0); } - uint64_t nwid = strtoull(argv[2],NULL,16); // Network ID to join - int serverBindPort = atoi(argv[3]); // Port the application should bind to - int ztServicePort = atoi(argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) + uint64_t nwid = strtoull(argv[2], NULL, 16); // Network ID to join + int serverBindPort = atoi(argv[3]); // Port the application should bind to + int ztServicePort = atoi( + argv[4]); // Port ZT uses to send encrypted UDP packets to peers (try something like 9994) struct zts_sockaddr_in in4, acc_in4; in4.sin_port = htons(serverBindPort); @@ -227,56 +254,78 @@ int main(int argc, char **argv) int fd, accfd; int err = ZTS_ERR_OK; - // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take slightly longer to start the node + // If disabled: (network) details will NOT be written to or read from (networks.d/). It may take + // slightly longer to start the node zts_allow_network_caching(1); - // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take slightly longer to contact a remote peer + // If disabled: (peer) details will NOT be written to or read from (peers.d/). It may take + // slightly longer to contact a remote peer zts_allow_peer_caching(1); // If disabled: Settings will NOT be read from local.conf zts_allow_local_conf(1); - if((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { + if ((err = zts_start(argv[1], &on_zts_event, ztServicePort)) != ZTS_ERR_OK) { printf("Unable to start service, error = %d. Exiting.\n", err); exit(1); } printf("Waiting for node to come online...\n"); - while (!myNode.online) { zts_delay_ms(50); } + while (! myNode.online) { + zts_delay_ms(50); + } printf("This node's identity is stored in %s\n", argv[1]); - if((err = zts_join(nwid)) != ZTS_ERR_OK) { + if ((err = zts_join(nwid)) != ZTS_ERR_OK) { printf("Unable to join network, error = %d. Exiting.\n", err); exit(1); } printf("Joining network %llx\n", nwid); printf("Don't forget to authorize this device in my.zerotier.com or the web API!\n"); - while (!myNode.joinedAtLeastOneNetwork) { zts_delay_ms(50); } + while (! myNode.joinedAtLeastOneNetwork) { + zts_delay_ms(50); + } // Socket-like API example printf("Creating socket...\n"); if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { - printf("Error creating ZeroTier socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n",fd, err, zts_errno); + printf( + "Error creating ZeroTier socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", + fd, + err, + zts_errno); exit(1); } printf("Binding...\n"); - if ((err = zts_bind(fd, (struct zts_sockaddr *)&in4, sizeof(struct zts_sockaddr_in)) < 0)) { - printf("Error binding to interface (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno); + 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); exit(1); } printf("Listening...\n"); int backlog = 100; if ((err = zts_listen(fd, backlog)) < 0) { - printf("Error placing socket in LISTENING state (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno); + printf( + "Error placing socket in LISTENING state (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", + fd, + err, + zts_errno); exit(1); } - int bytes=0; + int bytes = 0; char recvBuf[128]; memset(recvBuf, 0, sizeof(recvBuf)); while (true) { zts_socklen_t client_addrlen = sizeof(zts_sockaddr_in); - if ((accfd = zts_accept(fd, (struct zts_sockaddr *)&acc_in4, &client_addrlen)) < 0) { - printf("Error accepting connection (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, err, zts_errno); + 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); } zts_socklen_t peer_addrlen = sizeof(struct zts_sockaddr_storage); zts_getpeername(accfd, (struct zts_sockaddr*)&acc_in4, &peer_addrlen); @@ -287,14 +336,22 @@ int main(int argc, char **argv) printf("Accepted connection from %s:%d\n", ipstr, ntohs(acc_in4.sin_port)); printf("Reading message string from client...\n"); - if((bytes = zts_read(accfd, recvBuf, sizeof(recvBuf))) < 0) { - printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno); + 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); exit(1); } printf("Read %d bytes: %s\n", bytes, recvBuf); printf("Sending message string to client...\n"); - if((bytes = zts_write(accfd, recvBuf, bytes)) < 0) { - printf("Error writing to socket (fd=%d, ret=%d, zts_errno=%d). Exiting.\n", fd, bytes, zts_errno); + 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); exit(1); } printf("Sent %d bytes: %s\n", bytes, recvBuf); diff --git a/include/ZeroTierSockets.h b/include/ZeroTierSockets.h index 095198e..77587c3 100644 --- a/include/ZeroTierSockets.h +++ b/include/ZeroTierSockets.h @@ -29,20 +29,19 @@ extern "C" { //----------------------------------------------------------------------------// /** Common error return values */ -enum zts_error -{ +enum zts_error { /** No error */ - ZTS_ERR_OK = 0, + ZTS_ERR_OK = 0, /** Socket error, see `zts_errno` */ - ZTS_ERR_SOCKET = -1, + ZTS_ERR_SOCKET = -1, /** The node service experienced a problem. Did you start the service? */ - ZTS_ERR_SERVICE = -2, + ZTS_ERR_SERVICE = -2, /** Invalid argument */ - ZTS_ERR_ARG = -3, + ZTS_ERR_ARG = -3, /** No result (not necessarily an error) */ ZTS_ERR_NO_RESULT = -4, /** Consider filing a bug report */ - ZTS_ERR_GENERAL = -5 + ZTS_ERR_GENERAL = -5 }; //----------------------------------------------------------------------------// @@ -50,98 +49,97 @@ enum zts_error //----------------------------------------------------------------------------// /** Event codes used by the callback API */ -enum zts_event -{ +enum zts_event { /** The node service started successfully (no action needed) */ - ZTS_EVENT_NODE_UP = 200, + ZTS_EVENT_NODE_UP = 200, /** The node can reach the Internet */ - ZTS_EVENT_NODE_ONLINE = 201, + ZTS_EVENT_NODE_ONLINE = 201, /** The node cannot reach the Internet */ - ZTS_EVENT_NODE_OFFLINE = 202, + ZTS_EVENT_NODE_OFFLINE = 202, /** The node service has stopped */ - ZTS_EVENT_NODE_DOWN = 203, + ZTS_EVENT_NODE_DOWN = 203, /** Multiple identities in use (undefined behavior) */ - ZTS_EVENT_NODE_IDENTITY_COLLISION = 204, + ZTS_EVENT_NODE_IDENTITY_COLLISION = 204, /** Something went horribly wrong */ ZTS_EVENT_NODE_UNRECOVERABLE_ERROR = 205, /** The node has been terminated */ - ZTS_EVENT_NODE_NORMAL_TERMINATION = 206, + ZTS_EVENT_NODE_NORMAL_TERMINATION = 206, - ZTS_EVENT_NODE_WHAT = 207, + ZTS_EVENT_NODE_WHAT = 207, // Network events /** The network ID does not correspond to a known network */ - ZTS_EVENT_NETWORK_NOT_FOUND = 210, + ZTS_EVENT_NETWORK_NOT_FOUND = 210, /** The version of ZeroTier inside libzt is too old */ - ZTS_EVENT_NETWORK_CLIENT_TOO_OLD = 211, + ZTS_EVENT_NETWORK_CLIENT_TOO_OLD = 211, /** The configuration for a network has been requested (no action needed) */ - ZTS_EVENT_NETWORK_REQ_CONFIG = 212, + ZTS_EVENT_NETWORK_REQ_CONFIG = 212, /** The node joined the network successfully (no action needed) */ - ZTS_EVENT_NETWORK_OK = 213, + ZTS_EVENT_NETWORK_OK = 213, /** The node is not allowed to join the network (you must authorize node) */ - ZTS_EVENT_NETWORK_ACCESS_DENIED = 214, + ZTS_EVENT_NETWORK_ACCESS_DENIED = 214, /** The node has received an IPv4 address from the network controller */ - ZTS_EVENT_NETWORK_READY_IP4 = 215, + ZTS_EVENT_NETWORK_READY_IP4 = 215, /** The node has received an IPv6 address from the network controller */ - ZTS_EVENT_NETWORK_READY_IP6 = 216, + ZTS_EVENT_NETWORK_READY_IP6 = 216, /** Deprecated */ - ZTS_EVENT_NETWORK_READY_IP4_IP6 = 217, + ZTS_EVENT_NETWORK_READY_IP4_IP6 = 217, /** Network controller is unreachable */ - ZTS_EVENT_NETWORK_DOWN = 218, + ZTS_EVENT_NETWORK_DOWN = 218, /** Network change received from controller */ - ZTS_EVENT_NETWORK_UPDATE = 219, + ZTS_EVENT_NETWORK_UPDATE = 219, // Network Stack events /** TCP/IP stack (lwIP) is up */ - ZTS_EVENT_STACK_UP = 220, + ZTS_EVENT_STACK_UP = 220, /** TCP/IP stack (lwIP) id down */ - ZTS_EVENT_STACK_DOWN = 221, + ZTS_EVENT_STACK_DOWN = 221, // lwIP netif events /** lwIP netif up (for debug purposes) */ - ZTS_EVENT_NETIF_UP = 230, + ZTS_EVENT_NETIF_UP = 230, /** lwIP netif down (for debug purposes) */ - ZTS_EVENT_NETIF_DOWN = 231, + ZTS_EVENT_NETIF_DOWN = 231, /** lwIP netif removed (for debug purposes) */ - ZTS_EVENT_NETIF_REMOVED = 232, + ZTS_EVENT_NETIF_REMOVED = 232, /** lwIP netif link up (for debug purposes) */ - ZTS_EVENT_NETIF_LINK_UP = 233, + ZTS_EVENT_NETIF_LINK_UP = 233, /** lwIP netif link down (for debug purposes) */ - ZTS_EVENT_NETIF_LINK_DOWN = 234, + ZTS_EVENT_NETIF_LINK_DOWN = 234, // Peer events /** A direct P2P path to peer is known */ - ZTS_EVENT_PEER_DIRECT = 240, + ZTS_EVENT_PEER_DIRECT = 240, /** A direct P2P path to peer is NOT known. Traffic is now relayed */ - ZTS_EVENT_PEER_RELAY = 241, + ZTS_EVENT_PEER_RELAY = 241, /** A peer is unreachable. Check NAT/Firewall settings */ - ZTS_EVENT_PEER_UNREACHABLE = 242, + ZTS_EVENT_PEER_UNREACHABLE = 242, /** A new path to a peer was discovered */ - ZTS_EVENT_PEER_PATH_DISCOVERED = 243, + ZTS_EVENT_PEER_PATH_DISCOVERED = 243, /** A known path to a peer is now considered dead */ - ZTS_EVENT_PEER_PATH_DEAD = 244, + ZTS_EVENT_PEER_PATH_DEAD = 244, // Route events /** A new managed network route was added */ - ZTS_EVENT_ROUTE_ADDED = 250, + ZTS_EVENT_ROUTE_ADDED = 250, /** A managed network route was removed */ - ZTS_EVENT_ROUTE_REMOVED = 251, + ZTS_EVENT_ROUTE_REMOVED = 251, // Address events /** A new managed IPv4 address was assigned to this peer */ - ZTS_EVENT_ADDR_ADDED_IP4 = 260, + ZTS_EVENT_ADDR_ADDED_IP4 = 260, /** A managed IPv4 address assignment was removed from this peer */ - ZTS_EVENT_ADDR_REMOVED_IP4 = 261, + ZTS_EVENT_ADDR_REMOVED_IP4 = 261, /** A new managed IPv4 address was assigned to this peer */ - ZTS_EVENT_ADDR_ADDED_IP6 = 262, + ZTS_EVENT_ADDR_ADDED_IP6 = 262, /** A managed IPv6 address assignment was removed from this peer */ - ZTS_EVENT_ADDR_REMOVED_IP6 = 263 + ZTS_EVENT_ADDR_REMOVED_IP6 = 263 }; //----------------------------------------------------------------------------// @@ -151,157 +149,157 @@ enum zts_event /** Error variable set after each `zts_*` call. Provides additional information. */ extern int zts_errno; -#define ZTS_EPERM 1 /* Operation not permitted */ -#define ZTS_ENOENT 2 /* No such file or directory */ -#define ZTS_ESRCH 3 /* No such process */ -#define ZTS_EINTR 4 /* Interrupted system call */ -#define ZTS_EIO 5 /* I/O error */ -#define ZTS_ENXIO 6 /* No such device or address */ -#define ZTS_E2BIG 7 /* Arg list too long */ -#define ZTS_ENOEXEC 8 /* Exec format error */ -#define ZTS_EBADF 9 /* Bad file number */ -#define ZTS_ECHILD 10 /* No child processes */ -#define ZTS_EAGAIN 11 /* Try again */ -#define ZTS_ENOMEM 12 /* Out of memory */ -#define ZTS_EACCES 13 /* Permission denied */ -#define ZTS_EFAULT 14 /* Bad address */ -#define ZTS_ENOTBLK 15 /* Block device required */ -#define ZTS_EBUSY 16 /* Device or resource busy */ -#define ZTS_EEXIST 17 /* File exists */ -#define ZTS_EXDEV 18 /* Cross-device link */ -#define ZTS_ENODEV 19 /* No such device */ -#define ZTS_ENOTDIR 20 /* Not a directory */ -#define ZTS_EISDIR 21 /* Is a directory */ -#define ZTS_EINVAL 22 /* Invalid argument */ -#define ZTS_ENFILE 23 /* File table overflow */ -#define ZTS_EMFILE 24 /* Too many open files */ -#define ZTS_ENOTTY 25 /* Not a typewriter */ -#define ZTS_ETXTBSY 26 /* Text file busy */ -#define ZTS_EFBIG 27 /* File too large */ -#define ZTS_ENOSPC 28 /* No space left on device */ -#define ZTS_ESPIPE 29 /* Illegal seek */ -#define ZTS_EROFS 30 /* Read-only file system */ -#define ZTS_EMLINK 31 /* Too many links */ -#define ZTS_EPIPE 32 /* Broken pipe */ -#define ZTS_EDOM 33 /* Math argument out of domain of func */ -#define ZTS_ERANGE 34 /* Math result not representable */ -#define ZTS_EDEADLK 35 /* Resource deadlock would occur */ -#define ZTS_ENAMETOOLONG 36 /* File name too long */ -#define ZTS_ENOLCK 37 /* No record locks available */ -#define ZTS_ENOSYS 38 /* Function not implemented */ -#define ZTS_ENOTEMPTY 39 /* Directory not empty */ -#define ZTS_ELOOP 40 /* Too many symbolic links encountered */ -#define ZTS_EWOULDBLOCK ZTS_EAGAIN /* Operation would block */ -#define ZTS_ENOMSG 42 /* No message of desired type */ -#define ZTS_EIDRM 43 /* Identifier removed */ -#define ZTS_ECHRNG 44 /* Channel number out of range */ -#define ZTS_EL2NSYNC 45 /* Level 2 not synchronized */ -#define ZTS_EL3HLT 46 /* Level 3 halted */ -#define ZTS_EL3RST 47 /* Level 3 reset */ -#define ZTS_ELNRNG 48 /* Link number out of range */ -#define ZTS_EUNATCH 49 /* Protocol driver not attached */ -#define ZTS_ENOCSI 50 /* No CSI structure available */ -#define ZTS_EL2HLT 51 /* Level 2 halted */ -#define ZTS_EBADE 52 /* Invalid exchange */ -#define ZTS_EBADR 53 /* Invalid request descriptor */ -#define ZTS_EXFULL 54 /* Exchange full */ -#define ZTS_ENOANO 55 /* No anode */ -#define ZTS_EBADRQC 56 /* Invalid request code */ -#define ZTS_EBADSLT 57 /* Invalid slot */ -#define ZTS_EDEADLOCK ZTS_EDEADLK -#define ZTS_EBFONT 59 /* Bad font file format */ -#define ZTS_ENOSTR 60 /* Device not a stream */ -#define ZTS_ENODATA 61 /* No data available */ -#define ZTS_ETIME 62 /* Timer expired */ -#define ZTS_ENOSR 63 /* Out of streams resources */ -#define ZTS_ENONET 64 /* Machine is not on the network */ -#define ZTS_ENOPKG 65 /* Package not installed */ -#define ZTS_EREMOTE 66 /* Object is remote */ -#define ZTS_ENOLINK 67 /* Link has been severed */ -#define ZTS_EADV 68 /* Advertise error */ -#define ZTS_ESRMNT 69 /* Srmount error */ -#define ZTS_ECOMM 70 /* Communication error on send */ -#define ZTS_EPROTO 71 /* Protocol error */ -#define ZTS_EMULTIHOP 72 /* Multihop attempted */ -#define ZTS_EDOTDOT 73 /* RFS specific error */ -#define ZTS_EBADMSG 74 /* Not a data message */ -#define ZTS_EOVERFLOW 75 /* Value too large for defined data type */ -#define ZTS_ENOTUNIQ 76 /* Name not unique on network */ -#define ZTS_EBADFD 77 /* File descriptor in bad state */ -#define ZTS_EREMCHG 78 /* Remote address changed */ -#define ZTS_ELIBACC 79 /* Can not access a needed shared library */ -#define ZTS_ELIBBAD 80 /* Accessing a corrupted shared library */ -#define ZTS_ELIBSCN 81 /* .lib section in a.out corrupted */ -#define ZTS_ELIBMAX 82 /* Attempting to link in too many shared libraries */ -#define ZTS_ELIBEXEC 83 /* Cannot exec a shared library directly */ -#define ZTS_EILSEQ 84 /* Illegal byte sequence */ -#define ZTS_ERESTART 85 /* Interrupted system call should be restarted */ -#define ZTS_ESTRPIPE 86 /* Streams pipe error */ -#define ZTS_EUSERS 87 /* Too many users */ -#define ZTS_ENOTSOCK 88 /* Socket operation on non-socket */ -#define ZTS_EDESTADDRREQ 89 /* Destination address required */ -#define ZTS_EMSGSIZE 90 /* Message too long */ -#define ZTS_EPROTOTYPE 91 /* Protocol wrong type for socket */ -#define ZTS_ENOPROTOOPT 92 /* Protocol not available */ -#define ZTS_EPROTONOSUPPORT 93 /* Protocol not supported */ -#define ZTS_ESOCKTNOSUPPORT 94 /* Socket type not supported */ -#define ZTS_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ -#define ZTS_EPFNOSUPPORT 96 /* Protocol family not supported */ -#define ZTS_EAFNOSUPPORT 97 /* Address family not supported by protocol */ -#define ZTS_EADDRINUSE 98 /* Address already in use */ -#define ZTS_EADDRNOTAVAIL 99 /* Cannot assign requested address */ -#define ZTS_ENETDOWN 100 /* Network is down */ -#define ZTS_ENETUNREACH 101 /* Network is unreachable */ -#define ZTS_ENETRESET 102 /* Network dropped connection because of reset */ -#define ZTS_ECONNABORTED 103 /* Software caused connection abort */ -#define ZTS_ECONNRESET 104 /* Connection reset by peer */ -#define ZTS_ENOBUFS 105 /* No buffer space available */ -#define ZTS_EISCONN 106 /* Transport endpoint is already connected */ -#define ZTS_ENOTCONN 107 /* Transport endpoint is not connected */ -#define ZTS_ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ -#define ZTS_ETOOMANYREFS 109 /* Too many references: cannot splice */ -#define ZTS_ETIMEDOUT 110 /* Connection timed out */ -#define ZTS_ECONNREFUSED 111 /* Connection refused */ -#define ZTS_EHOSTDOWN 112 /* Host is down */ -#define ZTS_EHOSTUNREACH 113 /* No route to host */ -#define ZTS_EALREADY 114 /* Operation already in progress */ -#define ZTS_EINPROGRESS 115 /* Operation now in progress */ -#define ZTS_ESTALE 116 /* Stale NFS file handle */ -#define ZTS_EUCLEAN 117 /* Structure needs cleaning */ -#define ZTS_ENOTNAM 118 /* Not a XENIX named type file */ -#define ZTS_ENAVAIL 119 /* No XENIX semaphores available */ -#define ZTS_EISNAM 120 /* Is a named type file */ -#define ZTS_EREMOTEIO 121 /* Remote I/O error */ -#define ZTS_EDQUOT 122 /* Quota exceeded */ -#define ZTS_ENOMEDIUM 123 /* No medium found */ -#define ZTS_EMEDIUMTYPE 124 /* Wrong medium type */ +#define ZTS_EPERM 1 /* Operation not permitted */ +#define ZTS_ENOENT 2 /* No such file or directory */ +#define ZTS_ESRCH 3 /* No such process */ +#define ZTS_EINTR 4 /* Interrupted system call */ +#define ZTS_EIO 5 /* I/O error */ +#define ZTS_ENXIO 6 /* No such device or address */ +#define ZTS_E2BIG 7 /* Arg list too long */ +#define ZTS_ENOEXEC 8 /* Exec format error */ +#define ZTS_EBADF 9 /* Bad file number */ +#define ZTS_ECHILD 10 /* No child processes */ +#define ZTS_EAGAIN 11 /* Try again */ +#define ZTS_ENOMEM 12 /* Out of memory */ +#define ZTS_EACCES 13 /* Permission denied */ +#define ZTS_EFAULT 14 /* Bad address */ +#define ZTS_ENOTBLK 15 /* Block device required */ +#define ZTS_EBUSY 16 /* Device or resource busy */ +#define ZTS_EEXIST 17 /* File exists */ +#define ZTS_EXDEV 18 /* Cross-device link */ +#define ZTS_ENODEV 19 /* No such device */ +#define ZTS_ENOTDIR 20 /* Not a directory */ +#define ZTS_EISDIR 21 /* Is a directory */ +#define ZTS_EINVAL 22 /* Invalid argument */ +#define ZTS_ENFILE 23 /* File table overflow */ +#define ZTS_EMFILE 24 /* Too many open files */ +#define ZTS_ENOTTY 25 /* Not a typewriter */ +#define ZTS_ETXTBSY 26 /* Text file busy */ +#define ZTS_EFBIG 27 /* File too large */ +#define ZTS_ENOSPC 28 /* No space left on device */ +#define ZTS_ESPIPE 29 /* Illegal seek */ +#define ZTS_EROFS 30 /* Read-only file system */ +#define ZTS_EMLINK 31 /* Too many links */ +#define ZTS_EPIPE 32 /* Broken pipe */ +#define ZTS_EDOM 33 /* Math argument out of domain of func */ +#define ZTS_ERANGE 34 /* Math result not representable */ +#define ZTS_EDEADLK 35 /* Resource deadlock would occur */ +#define ZTS_ENAMETOOLONG 36 /* File name too long */ +#define ZTS_ENOLCK 37 /* No record locks available */ +#define ZTS_ENOSYS 38 /* Function not implemented */ +#define ZTS_ENOTEMPTY 39 /* Directory not empty */ +#define ZTS_ELOOP 40 /* Too many symbolic links encountered */ +#define ZTS_EWOULDBLOCK ZTS_EAGAIN /* Operation would block */ +#define ZTS_ENOMSG 42 /* No message of desired type */ +#define ZTS_EIDRM 43 /* Identifier removed */ +#define ZTS_ECHRNG 44 /* Channel number out of range */ +#define ZTS_EL2NSYNC 45 /* Level 2 not synchronized */ +#define ZTS_EL3HLT 46 /* Level 3 halted */ +#define ZTS_EL3RST 47 /* Level 3 reset */ +#define ZTS_ELNRNG 48 /* Link number out of range */ +#define ZTS_EUNATCH 49 /* Protocol driver not attached */ +#define ZTS_ENOCSI 50 /* No CSI structure available */ +#define ZTS_EL2HLT 51 /* Level 2 halted */ +#define ZTS_EBADE 52 /* Invalid exchange */ +#define ZTS_EBADR 53 /* Invalid request descriptor */ +#define ZTS_EXFULL 54 /* Exchange full */ +#define ZTS_ENOANO 55 /* No anode */ +#define ZTS_EBADRQC 56 /* Invalid request code */ +#define ZTS_EBADSLT 57 /* Invalid slot */ +#define ZTS_EDEADLOCK ZTS_EDEADLK +#define ZTS_EBFONT 59 /* Bad font file format */ +#define ZTS_ENOSTR 60 /* Device not a stream */ +#define ZTS_ENODATA 61 /* No data available */ +#define ZTS_ETIME 62 /* Timer expired */ +#define ZTS_ENOSR 63 /* Out of streams resources */ +#define ZTS_ENONET 64 /* Machine is not on the network */ +#define ZTS_ENOPKG 65 /* Package not installed */ +#define ZTS_EREMOTE 66 /* Object is remote */ +#define ZTS_ENOLINK 67 /* Link has been severed */ +#define ZTS_EADV 68 /* Advertise error */ +#define ZTS_ESRMNT 69 /* Srmount error */ +#define ZTS_ECOMM 70 /* Communication error on send */ +#define ZTS_EPROTO 71 /* Protocol error */ +#define ZTS_EMULTIHOP 72 /* Multihop attempted */ +#define ZTS_EDOTDOT 73 /* RFS specific error */ +#define ZTS_EBADMSG 74 /* Not a data message */ +#define ZTS_EOVERFLOW 75 /* Value too large for defined data type */ +#define ZTS_ENOTUNIQ 76 /* Name not unique on network */ +#define ZTS_EBADFD 77 /* File descriptor in bad state */ +#define ZTS_EREMCHG 78 /* Remote address changed */ +#define ZTS_ELIBACC 79 /* Can not access a needed shared library */ +#define ZTS_ELIBBAD 80 /* Accessing a corrupted shared library */ +#define ZTS_ELIBSCN 81 /* .lib section in a.out corrupted */ +#define ZTS_ELIBMAX 82 /* Attempting to link in too many shared libraries */ +#define ZTS_ELIBEXEC 83 /* Cannot exec a shared library directly */ +#define ZTS_EILSEQ 84 /* Illegal byte sequence */ +#define ZTS_ERESTART 85 /* Interrupted system call should be restarted */ +#define ZTS_ESTRPIPE 86 /* Streams pipe error */ +#define ZTS_EUSERS 87 /* Too many users */ +#define ZTS_ENOTSOCK 88 /* Socket operation on non-socket */ +#define ZTS_EDESTADDRREQ 89 /* Destination address required */ +#define ZTS_EMSGSIZE 90 /* Message too long */ +#define ZTS_EPROTOTYPE 91 /* Protocol wrong type for socket */ +#define ZTS_ENOPROTOOPT 92 /* Protocol not available */ +#define ZTS_EPROTONOSUPPORT 93 /* Protocol not supported */ +#define ZTS_ESOCKTNOSUPPORT 94 /* Socket type not supported */ +#define ZTS_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define ZTS_EPFNOSUPPORT 96 /* Protocol family not supported */ +#define ZTS_EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define ZTS_EADDRINUSE 98 /* Address already in use */ +#define ZTS_EADDRNOTAVAIL 99 /* Cannot assign requested address */ +#define ZTS_ENETDOWN 100 /* Network is down */ +#define ZTS_ENETUNREACH 101 /* Network is unreachable */ +#define ZTS_ENETRESET 102 /* Network dropped connection because of reset */ +#define ZTS_ECONNABORTED 103 /* Software caused connection abort */ +#define ZTS_ECONNRESET 104 /* Connection reset by peer */ +#define ZTS_ENOBUFS 105 /* No buffer space available */ +#define ZTS_EISCONN 106 /* Transport endpoint is already connected */ +#define ZTS_ENOTCONN 107 /* Transport endpoint is not connected */ +#define ZTS_ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +#define ZTS_ETOOMANYREFS 109 /* Too many references: cannot splice */ +#define ZTS_ETIMEDOUT 110 /* Connection timed out */ +#define ZTS_ECONNREFUSED 111 /* Connection refused */ +#define ZTS_EHOSTDOWN 112 /* Host is down */ +#define ZTS_EHOSTUNREACH 113 /* No route to host */ +#define ZTS_EALREADY 114 /* Operation already in progress */ +#define ZTS_EINPROGRESS 115 /* Operation now in progress */ +#define ZTS_ESTALE 116 /* Stale NFS file handle */ +#define ZTS_EUCLEAN 117 /* Structure needs cleaning */ +#define ZTS_ENOTNAM 118 /* Not a XENIX named type file */ +#define ZTS_ENAVAIL 119 /* No XENIX semaphores available */ +#define ZTS_EISNAM 120 /* Is a named type file */ +#define ZTS_EREMOTEIO 121 /* Remote I/O error */ +#define ZTS_EDQUOT 122 /* Quota exceeded */ +#define ZTS_ENOMEDIUM 123 /* No medium found */ +#define ZTS_EMEDIUMTYPE 124 /* Wrong medium type */ //----------------------------------------------------------------------------// // Misc // //----------------------------------------------------------------------------// -#if !defined(ZTS_ENABLE_PYTHON) && !defined(ZTS_ENABLE_PINVOKE) -#define ZTS_C_API_ONLY 1 +#if ! defined(ZTS_ENABLE_PYTHON) && ! defined(ZTS_ENABLE_PINVOKE) + #define ZTS_C_API_ONLY 1 #endif -#if !ZTS_NO_STDINT_H -#include +#if ! ZTS_NO_STDINT_H + #include #endif #if defined(_MSC_VER) #ifndef ssize_t - // TODO: Should be SSIZE_T, would require lwIP patch - // #include - // typedef SSIZE_T ssize_t; - typedef int ssize_t; +// TODO: Should be SSIZE_T, would require lwIP patch +// #include +// typedef SSIZE_T ssize_t; +typedef int ssize_t; #endif #else #include #endif #ifdef ZTS_ENABLE_PINVOKE - // Used by P/INVOKE wrappers - typedef void (*CppCallback)(void *msg); +// Used by P/INVOKE wrappers +typedef void (*CppCallback)(void* msg); #endif //----------------------------------------------------------------------------// @@ -350,40 +348,40 @@ extern int zts_errno; /** * Length of human-readable MAC address string */ -#define ZTS_MAC_ADDRSTRLEN 18 +#define ZTS_MAC_ADDRSTRLEN 18 -#define ZTS_INET_ADDRSTRLEN 16 -#define ZTS_INET6_ADDRSTRLEN 46 +#define ZTS_INET_ADDRSTRLEN 16 +#define ZTS_INET6_ADDRSTRLEN 46 /** 255.255.255.255 */ -#define ZTS_IPADDR_NONE ((uint32_t)0xffffffffUL) +#define ZTS_IPADDR_NONE ((uint32_t)0xffffffffUL) /** 127.0.0.1 */ -#define ZTS_IPADDR_LOOPBACK ((uint32_t)0x7f000001UL) +#define ZTS_IPADDR_LOOPBACK ((uint32_t)0x7f000001UL) /** 0.0.0.0 */ -#define ZTS_IPADDR_ANY ((uint32_t)0x00000000UL) +#define ZTS_IPADDR_ANY ((uint32_t)0x00000000UL) /** 255.255.255.255 */ -#define ZTS_IPADDR_BROADCAST ((uint32_t)0xffffffffUL) +#define ZTS_IPADDR_BROADCAST ((uint32_t)0xffffffffUL) /** 255.255.255.255 */ -#define ZTS_INADDR_NONE ZTS_IPADDR_NONE +#define ZTS_INADDR_NONE ZTS_IPADDR_NONE /** 127.0.0.1 */ -#define ZTS_INADDR_LOOPBACK ZTS_IPADDR_LOOPBACK +#define ZTS_INADDR_LOOPBACK ZTS_IPADDR_LOOPBACK /** 0.0.0.0 */ -#define ZTS_INADDR_ANY ZTS_IPADDR_ANY +#define ZTS_INADDR_ANY ZTS_IPADDR_ANY /** 255.255.255.255 */ -#define ZTS_INADDR_BROADCAST ZTS_IPADDR_BROADCAST +#define ZTS_INADDR_BROADCAST ZTS_IPADDR_BROADCAST // Socket protocol types -#define ZTS_SOCK_STREAM 0x0001 -#define ZTS_SOCK_DGRAM 0x0002 -#define ZTS_SOCK_RAW 0x0003 +#define ZTS_SOCK_STREAM 0x0001 +#define ZTS_SOCK_DGRAM 0x0002 +#define ZTS_SOCK_RAW 0x0003 // Socket family types -#define ZTS_AF_UNSPEC 0x0000 -#define ZTS_AF_INET 0x0002 -#define ZTS_AF_INET6 0x000a -#define ZTS_PF_INET ZTS_AF_INET -#define ZTS_PF_INET6 ZTS_AF_INET6 -#define ZTS_PF_UNSPEC ZTS_AF_UNSPEC +#define ZTS_AF_UNSPEC 0x0000 +#define ZTS_AF_INET 0x0002 +#define ZTS_AF_INET6 0x000a +#define ZTS_PF_INET ZTS_AF_INET +#define ZTS_PF_INET6 ZTS_AF_INET6 +#define ZTS_PF_UNSPEC ZTS_AF_UNSPEC // Protocol command types #define ZTS_IPPROTO_IP 0x0000 #define ZTS_IPPROTO_ICMP 0x0001 @@ -394,24 +392,26 @@ extern int zts_errno; #define ZTS_IPPROTO_UDPLITE 0x0088 #define ZTS_IPPROTO_RAW 0x00ff // send() and recv() flags -#define ZTS_MSG_PEEK 0x0001 -#define ZTS_MSG_WAITALL 0x0002 // NOT YET SUPPORTED -#define ZTS_MSG_OOB 0x0004 // NOT YET SUPPORTED -#define ZTS_MSG_DONTWAIT 0x0008 -#define ZTS_MSG_MORE 0x0010 +#define ZTS_MSG_PEEK 0x0001 +#define ZTS_MSG_WAITALL 0x0002 // NOT YET SUPPORTED +#define ZTS_MSG_OOB 0x0004 // NOT YET SUPPORTED +#define ZTS_MSG_DONTWAIT 0x0008 +#define ZTS_MSG_MORE 0x0010 // Macro's for defining ioctl() command values -#define ZTS_IOCPARM_MASK 0x7fU -#define ZTS_IOC_VOID 0x20000000UL -#define ZTS_IOC_OUT 0x40000000UL -#define ZTS_IOC_IN 0x80000000UL -#define ZTS_IOC_INOUT (ZTS_IOC_IN | ZTS_IOC_OUT) -#define ZTS_IO(x,y) (ZTS_IOC_VOID | ((x)<<8)|(y)) -#define ZTS_IOR(x,y,t) (ZTS_IOC_OUT | (((long)sizeof(t) & ZTS_IOCPARM_MASK)<<16) | ((x)<<8) | (y)) -#define ZTS_IOW(x,y,t) (ZTS_IOC_IN | (((long)sizeof(t) & ZTS_IOCPARM_MASK)<<16) | ((x)<<8) | (y)) +#define ZTS_IOCPARM_MASK 0x7fU +#define ZTS_IOC_VOID 0x20000000UL +#define ZTS_IOC_OUT 0x40000000UL +#define ZTS_IOC_IN 0x80000000UL +#define ZTS_IOC_INOUT (ZTS_IOC_IN | ZTS_IOC_OUT) +#define ZTS_IO(x, y) (ZTS_IOC_VOID | ((x) << 8) | (y)) +#define ZTS_IOR(x, y, t) \ + (ZTS_IOC_OUT | (((long)sizeof(t) & ZTS_IOCPARM_MASK) << 16) | ((x) << 8) | (y)) +#define ZTS_IOW(x, y, t) \ + (ZTS_IOC_IN | (((long)sizeof(t) & ZTS_IOCPARM_MASK) << 16) | ((x) << 8) | (y)) // ioctl() commands -#define ZTS_FIONREAD ZTS_IOR('f', 127, unsigned long) -#define ZTS_FIONBIO ZTS_IOW('f', 126, unsigned long) +#define ZTS_FIONREAD ZTS_IOR('f', 127, unsigned long) +#define ZTS_FIONBIO ZTS_IOW('f', 126, unsigned long) //----------------------------------------------------------------------------// // Custom but still mostly standard socket interface structures // @@ -434,41 +434,41 @@ struct zts_in_addr { struct zts_in6_addr { union un { uint32_t u32_addr[4]; - uint8_t u8_addr[16]; + uint8_t u8_addr[16]; } un; -//#define s6_addr un.u8_addr + //#define s6_addr un.u8_addr }; struct zts_sockaddr_in { - uint8_t sin_len; - zts_sa_family_t sin_family; - zts_in_port_t sin_port; + uint8_t sin_len; + zts_sa_family_t sin_family; + zts_in_port_t sin_port; struct zts_in_addr sin_addr; #define SIN_ZERO_LEN 8 char sin_zero[SIN_ZERO_LEN]; }; struct zts_sockaddr_in6 { - uint8_t sin6_len; // length of this structure - zts_sa_family_t sin6_family; // ZTS_AF_INET6 - zts_in_port_t sin6_port; // Transport layer port # - uint32_t sin6_flowinfo; // IPv6 flow information - struct zts_in6_addr sin6_addr; // IPv6 address - uint32_t sin6_scope_id; // Set of interfaces for scope + uint8_t sin6_len; // length of this structure + zts_sa_family_t sin6_family; // ZTS_AF_INET6 + zts_in_port_t sin6_port; // Transport layer port # + uint32_t sin6_flowinfo; // IPv6 flow information + struct zts_in6_addr sin6_addr; // IPv6 address + uint32_t sin6_scope_id; // Set of interfaces for scope }; struct zts_sockaddr { - uint8_t sa_len; + uint8_t sa_len; zts_sa_family_t sa_family; - char sa_data[14]; + char sa_data[14]; }; struct zts_sockaddr_storage { - uint8_t s2_len; + uint8_t s2_len; zts_sa_family_t ss_family; - char s2_data1[2]; - uint32_t s2_data2[3]; - uint32_t s2_data3[3]; + char s2_data1[2]; + uint32_t s2_data2[3]; + uint32_t s2_data3[3]; }; //----------------------------------------------------------------------------// @@ -493,19 +493,17 @@ struct zts_sockaddr_storage { /** * What trust hierarchy role does this peer have? */ -enum zts_peer_role -{ - ZTS_PEER_ROLE_LEAF = 0, // ordinary node - ZTS_PEER_ROLE_MOON = 1, // moon root - ZTS_PEER_ROLE_PLANET = 2 // planetary root +enum zts_peer_role { + ZTS_PEER_ROLE_LEAF = 0, // ordinary node + ZTS_PEER_ROLE_MOON = 1, // moon root + ZTS_PEER_ROLE_PLANET = 2 // planetary root }; /** * A structure used to convey details about the current node * to the user application */ -struct zts_node_details -{ +struct zts_node_details { /** * The node ID */ @@ -531,23 +529,21 @@ struct zts_node_details * A structure used to convey information to a user application via * a callback function. */ -struct zts_callback_msg -{ +struct zts_callback_msg { /** * Event identifier */ int16_t eventCode; - struct zts_node_details *node; - struct zts_network_details *network; - struct zts_netif_details *netif; - struct zts_virtual_network_route *route; - struct zts_peer_details *peer; - struct zts_addr_details *addr; + struct zts_node_details* node; + struct zts_network_details* network; + struct zts_netif_details* netif; + struct zts_virtual_network_route* route; + struct zts_peer_details* peer; + struct zts_addr_details* addr; }; -struct zts_addr_details -{ +struct zts_addr_details { uint64_t nwid; struct zts_sockaddr_storage addr; }; @@ -556,8 +552,7 @@ struct zts_addr_details * A structure used to convey information about a virtual network * interface (netif) to a user application. */ -struct zts_netif_details -{ +struct zts_netif_details { /** * The virtual network that this interface was commissioned for. */ @@ -577,8 +572,7 @@ struct zts_netif_details /** * A structure used to represent a virtual network route */ -struct zts_virtual_network_route -{ +struct zts_virtual_network_route { /** * Target network / netmask bits (in port field) or NULL or 0.0.0.0/0 for default */ @@ -600,7 +594,6 @@ struct zts_virtual_network_route uint16_t metric; }; - /** * Maximum length of network short name */ @@ -612,7 +605,8 @@ struct zts_virtual_network_route #define ZTS_MAX_NETWORK_ROUTES 32 /** - * Maximum number of statically assigned IP addresses per network endpoint using ZT address management (not DHCP) + * Maximum number of statically assigned IP addresses per network endpoint using ZT address + * management (not DHCP) */ #define ZTS_MAX_ZT_ASSIGNED_ADDRESSES 16 @@ -624,8 +618,7 @@ struct zts_virtual_network_route /** * Virtual network status codes */ -enum ZTS_VirtualNetworkStatus -{ +enum ZTS_VirtualNetworkStatus { /** * Waiting for network configuration (also means revision == 0) */ @@ -660,8 +653,7 @@ enum ZTS_VirtualNetworkStatus /** * Virtual network type codes */ -enum ZTS_VirtualNetworkType -{ +enum ZTS_VirtualNetworkType { /** * Private networks are authorized via certificates of membership */ @@ -676,8 +668,7 @@ enum ZTS_VirtualNetworkType /** * A route to be pushed on a virtual network */ -typedef struct -{ +typedef struct { /** * Target network / netmask bits (in port field) or NULL or 0.0.0.0/0 for default */ @@ -702,8 +693,7 @@ typedef struct /** * Virtual network configuration */ -struct zts_network_details -{ +struct zts_network_details { /** * 64-bit ZeroTier network ID */ @@ -757,7 +747,8 @@ struct zts_network_details int broadcastEnabled; /** - * If the network is in PORT_ERROR state, this is the (negative) error code most recently reported + * If the network is in PORT_ERROR state, this is the (negative) error code most recently + * reported */ int portError; @@ -803,15 +794,15 @@ struct zts_network_details */ struct { uint64_t mac; /* MAC in lower 48 bits */ - uint32_t adi; /* Additional distinguishing information, usually zero except for IPv4 ARP groups */ + uint32_t adi; /* Additional distinguishing information, usually zero except for IPv4 ARP + groups */ } multicastSubscriptions[ZTS_MAX_MULTICAST_SUBSCRIPTIONS]; }; /** * Physical network path to a peer */ -struct zts_physical_path -{ +struct zts_physical_path { /** * Address of endpoint */ @@ -846,8 +837,7 @@ struct zts_physical_path /** * Peer status result buffer */ -struct zts_peer_details -{ +struct zts_peer_details { /** * ZeroTier address (40 bits) */ @@ -892,9 +882,8 @@ struct zts_peer_details /** * List of peers */ -struct zts_peer_list -{ - struct zts_peer_details *peers; +struct zts_peer_list { + struct zts_peer_details* peers; unsigned long peerCount; }; @@ -904,35 +893,34 @@ struct zts_peer_list #ifdef ZTS_ENABLE_PYTHON -#include "Python.h" + #include "Python.h" /** * Abstract class used as a director. Pointer to an instance of this class * is provided to the Python layer. */ -class PythonDirectorCallbackClass -{ -public: +class PythonDirectorCallbackClass { + public: /** * Called by native code on event. Implemented in Python */ - virtual void on_zerotier_event(struct zts_callback_msg *msg); + virtual void on_zerotier_event(struct zts_callback_msg* msg); virtual ~PythonDirectorCallbackClass() {}; }; -extern PythonDirectorCallbackClass *_userEventCallback; +extern PythonDirectorCallbackClass* _userEventCallback; -int zts_py_bind(int fd, int family, int type, PyObject *addro); -int zts_py_connect(int fd, int family, int type, PyObject *addro); -PyObject * zts_py_accept(int fd); +int zts_py_bind(int fd, int family, int type, PyObject* addro); +int zts_py_connect(int fd, int family, int type, PyObject* addro); +PyObject* zts_py_accept(int fd); int zts_py_listen(int fd, int backlog); -PyObject * zts_py_recv(int fd, int len, int flags); -int zts_py_send(int fd, PyObject *buf, int flags); +PyObject* zts_py_recv(int fd, int len, int flags); +int zts_py_send(int fd, PyObject* buf, int flags); int zts_py_close(int fd); int zts_py_setblocking(int fd, int flag); int zts_py_getblocking(int fd); -#endif // ZTS_ENABLE_PYTHON +#endif // ZTS_ENABLE_PYTHON //----------------------------------------------------------------------------// // ZeroTier Service and Network Controls // @@ -956,20 +944,20 @@ int zts_py_getblocking(int fd); #ifdef ZTS_ENABLE_CENTRAL_API -#define ZTS_CENTRAL_DEFAULT_URL "https://my.zerotier.com" -#define ZTS_CENRTAL_MAX_URL_LEN 128 -#define ZTS_CENTRAL_TOKEN_LEN 32 -#define ZTS_CENTRAL_RESP_BUF_DEFAULT_SZ (128*1024) + #define ZTS_CENTRAL_DEFAULT_URL "https://my.zerotier.com" + #define ZTS_CENRTAL_MAX_URL_LEN 128 + #define ZTS_CENTRAL_TOKEN_LEN 32 + #define ZTS_CENTRAL_RESP_BUF_DEFAULT_SZ (128 * 1024) -#define ZTS_HTTP_GET 0 -#define ZTS_HTTP_POST 1 -#define ZTS_HTTP_DELETE 2 + #define ZTS_HTTP_GET 0 + #define ZTS_HTTP_POST 1 + #define ZTS_HTTP_DELETE 2 -#define ZTS_CENTRAL_NODE_AUTH_FALSE 0 -#define ZTS_CENTRAL_NODE_AUTH_TRUE 1 + #define ZTS_CENTRAL_NODE_AUTH_FALSE 0 + #define ZTS_CENTRAL_NODE_AUTH_TRUE 1 -#define ZTS_CENTRAL_READ 1 -#define ZTS_CENTRAL_WRITE 2 + #define ZTS_CENTRAL_READ 1 + #define ZTS_CENTRAL_WRITE 2 /** * @brief Enables read/write capability. Default before calling this is @@ -997,8 +985,8 @@ ZTS_API void ZTCALL zts_central_clear_resp_buf(); * @param buf_len Size of buffer for server response (specify `0` for default size) * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg. */ -ZTS_API int ZTCALL zts_central_init( - const char *url_str, const char *token_str, char *resp_buf, uint32_t buf_len); +ZTS_API int ZTCALL +zts_central_init(const char* url_str, const char* token_str, char* resp_buf, uint32_t buf_len); ZTS_API void ZTCALL zts_central_cleanup(); @@ -1011,30 +999,28 @@ ZTS_API void ZTCALL zts_central_cleanup(); * @return `ZTS_ERR_OK` if all contents were copied successfully. * `ZTS_ERR_ARG` if provided buffer was too small. */ -ZTS_API int ZTCALL zts_central_get_last_response_buf( - char *dest_buffer, int dest_buf_len); +ZTS_API int ZTCALL zts_central_get_last_response_buf(char* dest_buffer, int dest_buf_len); /** * @brief Get the status of the Central API server. * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_get_status(int *http_response_code); +ZTS_API int ZTCALL zts_central_get_status(int* http_response_code); /** * @brief Get the currently authenticated user’s user record. * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_get_self(int *http_response_code); +ZTS_API int ZTCALL zts_central_get_self(int* http_response_code); /** * @brief Retrieve a Network. * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_get_network( - int *http_response_code, uint64_t nwid); +ZTS_API int ZTCALL zts_central_get_network(int* http_response_code, uint64_t nwid); /** * @brief Update or create a Network. @@ -1046,8 +1032,7 @@ ZTS_API int ZTCALL zts_central_get_network( * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_update_network( - int *http_response_code, uint64_t nwid); +ZTS_API int ZTCALL zts_central_update_network(int* http_response_code, uint64_t nwid); /** * @brief Delete a Network. @@ -1057,8 +1042,7 @@ ZTS_API int ZTCALL zts_central_update_network( * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_delete_network( - int *http_response_code, uint64_t nwid); +ZTS_API int ZTCALL zts_central_delete_network(int* http_response_code, uint64_t nwid); /** * @brief Get All Viewable Networks. @@ -1067,14 +1051,13 @@ ZTS_API int ZTCALL zts_central_delete_network( * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_get_networks(int *http_response_code); +ZTS_API int ZTCALL zts_central_get_networks(int* http_response_code); /** * @brief Retrieve a Member. * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_get_member( - int *http_response_code, uint64_t nwid, uint64_t nodeid); +ZTS_API int ZTCALL zts_central_get_member(int* http_response_code, uint64_t nwid, uint64_t nodeid); /** * @brief Update or add a Member. @@ -1083,8 +1066,8 @@ ZTS_API int ZTCALL zts_central_get_member( * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_update_member( - int *http_response_code, uint64_t nwid, uint64_t nodeid, char *post_data); +ZTS_API int ZTCALL +zts_central_update_member(int* http_response_code, uint64_t nwid, uint64_t nodeid, char* post_data); /** * @brief Authorize or (De)authorize a node on a network. This operation @@ -1096,7 +1079,10 @@ ZTS_API int ZTCALL zts_central_update_member( * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg. */ ZTS_API int ZTCALL zts_central_set_node_auth( - int *http_response_code, uint64_t nwid, uint64_t nodeid, uint8_t is_authed); + int* http_response_code, + uint64_t nwid, + uint64_t nodeid, + uint8_t is_authed); /** * @brief Get All Members of a Network. @@ -1105,24 +1091,24 @@ ZTS_API int ZTCALL zts_central_set_node_auth( * * @return Standard HTTP response codes. */ -ZTS_API int ZTCALL zts_central_get_members_of_network( - int *http_response_code, uint64_t nwid); +ZTS_API int ZTCALL zts_central_get_members_of_network(int* http_response_code, uint64_t nwid); -#endif // NO_CENTRAL_API +#endif // NO_CENTRAL_API //----------------------------------------------------------------------------// // Identity Management // //----------------------------------------------------------------------------// /** - * @brief Generates a node identity (public/secret key-pair) and stores it in a user-provided buffer. + * @brief Generates a node identity (public/secret key-pair) and stores it in a user-provided + * buffer. * * @param key_pair_str User-provided destination buffer - * @param key_buf_len Length of user-provided destination buffer. Will be set to number of bytes copied. + * @param key_buf_len Length of user-provided destination buffer. Will be set to number of bytes + * copied. * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg. */ -ZTS_API int ZTCALL zts_generate_orphan_identity( - char *key_pair_str, uint16_t *key_buf_len); +ZTS_API int ZTCALL zts_generate_orphan_identity(char* key_pair_str, uint16_t* key_buf_len); /** * @brief Verifies that a key-pair is valid for use. @@ -1130,18 +1116,18 @@ ZTS_API int ZTCALL zts_generate_orphan_identity( * @param key_pair_str Buffer containing key-pair * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg. */ -ZTS_API int ZTCALL zts_verify_identity(const char *key_pair_str); +ZTS_API int ZTCALL zts_verify_identity(const char* key_pair_str); /** * @brief Copies the current node's identity into a buffer * * @param key_pair_str User-provided destination buffer - * @param key_buf_len Length of user-provided destination buffer. Will be set to number of bytes copied. + * @param key_buf_len Length of user-provided destination buffer. Will be set to number of bytes + * copied. * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. */ -ZTS_API int ZTCALL zts_get_node_identity( - char *key_pair_str, uint16_t *key_buf_len); +ZTS_API int ZTCALL zts_get_node_identity(char* key_pair_str, uint16_t* key_buf_len); /** * @brief Starts the ZeroTier service and notifies user application of events via callback. This @@ -1154,16 +1140,25 @@ ZTS_API int ZTCALL zts_get_node_identity( * experiences a problem, `ZTS_ERR_ARG` if invalid arg. */ #ifdef ZTS_ENABLE_PYTHON -int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, - PythonDirectorCallbackClass *callback, uint16_t port); +int zts_start_with_identity( + const char* key_pair_str, + uint16_t key_buf_len, + PythonDirectorCallbackClass* callback, + uint16_t port); #endif #ifdef ZTS_ENABLE_PINVOKE -int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, - CppCallback callback, uint16_t port); +int zts_start_with_identity( + const char* key_pair_str, + uint16_t key_buf_len, + CppCallback callback, + uint16_t port); #endif #ifdef ZTS_C_API_ONLY -int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, - void (*callback)(void *), uint16_t port); +int zts_start_with_identity( + const char* key_pair_str, + uint16_t key_buf_len, + void (*callback)(void*), + uint16_t port); #endif /** @@ -1201,7 +1196,8 @@ ZTS_API int ZTCALL zts_allow_network_caching(uint8_t allowed); ZTS_API int ZTCALL zts_allow_peer_caching(uint8_t allowed); /** - * @brief Enable or disable whether the service will read node configuration settings from a local.conf + * @brief Enable or disable whether the service will read node configuration settings from a + * local.conf * * Should be called before `zts_start()` if you intend on changing its state. * @@ -1231,13 +1227,14 @@ ZTS_API int ZTCALL zts_disable_local_storage(uint8_t disabled); * experiences a problem, `ZTS_ERR_ARG` if invalid arg. */ #ifdef ZTS_ENABLE_PYTHON - ZTS_API int ZTCALL zts_start(const char *path, PythonDirectorCallbackClass *callback, uint16_t port); +ZTS_API int ZTCALL +zts_start(const char* path, PythonDirectorCallbackClass* callback, uint16_t port); #endif #ifdef ZTS_ENABLE_PINVOKE - ZTS_API int ZTCALL zts_start(const char *path, CppCallback callback, uint16_t port); +ZTS_API int ZTCALL zts_start(const char* path, CppCallback callback, uint16_t port); #endif #ifdef ZTS_C_API_ONLY - ZTS_API int ZTCALL zts_start(const char *path, void (*callback)(void *), uint16_t port); +ZTS_API int ZTCALL zts_start(const char* path, void (*callback)(void*), uint16_t port); #endif /** @@ -1319,7 +1316,10 @@ ZTS_API int ZTCALL zts_deorbit(uint64_t moonWorldId); * @param nodeId Node ID * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg. */ -ZTS_API int ZTCALL zts_get_6plane_addr(struct zts_sockaddr_storage *addr, const uint64_t networkId, const uint64_t nodeId); +ZTS_API int ZTCALL zts_get_6plane_addr( + struct zts_sockaddr_storage* addr, + const uint64_t networkId, + const uint64_t nodeId); /** * @brief Compute a `RFC4193` IPv6 address for the given Network ID and Node ID @@ -1330,7 +1330,9 @@ ZTS_API int ZTCALL zts_get_6plane_addr(struct zts_sockaddr_storage *addr, const * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_ARG` if invalid arg. */ ZTS_API int ZTCALL zts_get_rfc4193_addr( - struct zts_sockaddr_storage *addr, const uint64_t networkId, const uint64_t nodeId); + struct zts_sockaddr_storage* addr, + const uint64_t networkId, + const uint64_t nodeId); /** * @brief Compute a `RFC4193` IPv6 address for the given Network ID and Node ID @@ -1350,19 +1352,19 @@ ZTS_API int ZTCALL zts_get_rfc4193_addr( * addresses. In addition an ad-hoc network ID encodes an IP port range. UDP packets and TCP SYN * (connection open) packets are only allowed to destination ports within the encoded range. * - * For example `ff00160016000000` is an ad-hoc network allowing only SSH, while `ff0000ffff000000` is an - * ad-hoc network allowing any UDP or TCP port. + * For example `ff00160016000000` is an ad-hoc network allowing only SSH, while `ff0000ffff000000` + * is an ad-hoc network allowing any UDP or TCP port. * - * Keep in mind that these networks are public and anyone in the entire world can join them. Care must - * be taken to avoid exposing vulnerable services or sharing unwanted files or other resources. + * Keep in mind that these networks are public and anyone in the entire world can join them. Care + * must be taken to avoid exposing vulnerable services or sharing unwanted files or other resources. * * * @param startPortOfRange Start of port allowed port range * @param endPortOfRange End of allowed port range * @return An Ad-hoc network ID */ -ZTS_API uint64_t ZTCALL zts_generate_adhoc_nwid_from_range( - uint16_t startPortOfRange, uint16_t endPortOfRange); +ZTS_API uint64_t ZTCALL +zts_generate_adhoc_nwid_from_range(uint16_t startPortOfRange, uint16_t endPortOfRange); /** * @brief Platform-agnostic delay (provided for convenience) @@ -1377,63 +1379,63 @@ ZTS_API void ZTCALL zts_delay_ms(long interval_ms); #ifdef ZTS_ENABLE_STATS -#define ZTS_STATS_PROTOCOL_LINK 0 -#define ZTS_STATS_PROTOCOL_ETHARP 1 -#define ZTS_STATS_PROTOCOL_IP 2 -#define ZTS_STATS_PROTOCOL_UDP 3 -#define ZTS_STATS_PROTOCOL_TCP 4 -#define ZTS_STATS_PROTOCOL_ICMP 5 -#define ZTS_STATS_PROTOCOL_IP_FRAG 6 -#define ZTS_STATS_PROTOCOL_IP6 7 -#define ZTS_STATS_PROTOCOL_ICMP6 8 -#define ZTS_STATS_PROTOCOL_IP6_FRAG 9 + #define ZTS_STATS_PROTOCOL_LINK 0 + #define ZTS_STATS_PROTOCOL_ETHARP 1 + #define ZTS_STATS_PROTOCOL_IP 2 + #define ZTS_STATS_PROTOCOL_UDP 3 + #define ZTS_STATS_PROTOCOL_TCP 4 + #define ZTS_STATS_PROTOCOL_ICMP 5 + #define ZTS_STATS_PROTOCOL_IP_FRAG 6 + #define ZTS_STATS_PROTOCOL_IP6 7 + #define ZTS_STATS_PROTOCOL_ICMP6 8 + #define ZTS_STATS_PROTOCOL_IP6_FRAG 9 /** Protocol related stats */ struct zts_stats_proto { - uint32_t xmit; /* Transmitted packets. */ - uint32_t recv; /* Received packets. */ - uint32_t fw; /* Forwarded packets. */ - uint32_t drop; /* Dropped packets. */ - uint32_t chkerr; /* Checksum error. */ - uint32_t lenerr; /* Invalid length error. */ - uint32_t memerr; /* Out of memory error. */ - uint32_t rterr; /* Routing error. */ - uint32_t proterr; /* Protocol error. */ - uint32_t opterr; /* Error in options. */ - uint32_t err; /* Misc error. */ - uint32_t cachehit; + uint32_t xmit; /* Transmitted packets. */ + uint32_t recv; /* Received packets. */ + uint32_t fw; /* Forwarded packets. */ + uint32_t drop; /* Dropped packets. */ + uint32_t chkerr; /* Checksum error. */ + uint32_t lenerr; /* Invalid length error. */ + uint32_t memerr; /* Out of memory error. */ + uint32_t rterr; /* Routing error. */ + uint32_t proterr; /* Protocol error. */ + uint32_t opterr; /* Error in options. */ + uint32_t err; /* Misc error. */ + uint32_t cachehit; }; /** IGMP stats */ struct zts_stats_igmp { - uint32_t xmit; /* Transmitted packets. */ - uint32_t recv; /* Received packets. */ - uint32_t drop; /* Dropped packets. */ - uint32_t chkerr; /* Checksum error. */ - uint32_t lenerr; /* Invalid length error. */ - uint32_t memerr; /* Out of memory error. */ - uint32_t proterr; /* Protocol error. */ - uint32_t rx_v1; /* Received v1 frames. */ - uint32_t rx_group; /* Received group-specific queries. */ - uint32_t rx_general; /* Received general queries. */ - uint32_t rx_report; /* Received reports. */ - uint32_t tx_join; /* Sent joins. */ - uint32_t tx_leave; /* Sent leaves. */ - uint32_t tx_report; /* Sent reports. */ + uint32_t xmit; /* Transmitted packets. */ + uint32_t recv; /* Received packets. */ + uint32_t drop; /* Dropped packets. */ + uint32_t chkerr; /* Checksum error. */ + uint32_t lenerr; /* Invalid length error. */ + uint32_t memerr; /* Out of memory error. */ + uint32_t proterr; /* Protocol error. */ + uint32_t rx_v1; /* Received v1 frames. */ + uint32_t rx_group; /* Received group-specific queries. */ + uint32_t rx_general; /* Received general queries. */ + uint32_t rx_report; /* Received reports. */ + uint32_t tx_join; /* Sent joins. */ + uint32_t tx_leave; /* Sent leaves. */ + uint32_t tx_report; /* Sent reports. */ }; /** System element stats */ struct zts_stats_syselem { - uint32_t used; - uint32_t max; - uint32_t err; + uint32_t used; + uint32_t max; + uint32_t err; }; /** System stats */ struct zts_stats_sys { - struct zts_stats_syselem sem; - struct zts_stats_syselem mutex; - struct zts_stats_syselem mbox; + struct zts_stats_syselem sem; + struct zts_stats_syselem mutex; + struct zts_stats_syselem mbox; }; /** lwIP stats container */ @@ -1474,7 +1476,7 @@ struct zts_stats { * This function can only be used in debug builds. * @return ZTS_ERR_OK on success. ZTS_ERR_ARG or ZTS_ERR_NO_RESULT on failure. */ -ZTS_API int ZTCALL zts_get_all_stats(struct zts_stats *statsDest); +ZTS_API int ZTCALL zts_get_all_stats(struct zts_stats* statsDest); /** * @brief Populate the given structure with the requested protocol's @@ -1483,10 +1485,9 @@ ZTS_API int ZTCALL zts_get_all_stats(struct zts_stats *statsDest); * This function can only be used in debug builds. * @return ZTS_ERR_OK on success. ZTS_ERR_ARG or ZTS_ERR_NO_RESULT on failure. */ -ZTS_API int ZTCALL zts_get_protocol_stats( - int protocolType, void *protoStatsDest); +ZTS_API int ZTCALL zts_get_protocol_stats(int protocolType, void* protoStatsDest); -#endif // ZTS_ENABLE_STATS +#endif // ZTS_ENABLE_STATS //----------------------------------------------------------------------------// // Socket API // @@ -1501,8 +1502,7 @@ ZTS_API int ZTCALL zts_get_protocol_stats( * @return Numbered file descriptor on success, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_socket( - const int socket_family, const int socket_type, const int protocol); +ZTS_API int ZTCALL zts_socket(const int socket_family, const int socket_type, const int protocol); /** * @brief Connect a socket to a remote host @@ -1513,8 +1513,7 @@ ZTS_API int ZTCALL zts_socket( * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_connect( - int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen); +ZTS_API int ZTCALL zts_connect(int fd, const struct zts_sockaddr* addr, zts_socklen_t addrlen); /** * @brief Connect a socket to a remote host @@ -1540,8 +1539,7 @@ ZTS_API int ZTCALL zts_connect( * out with no connection made, `ZTS_ERR_SERVICE` if the node experiences a * problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_connect_easy( - int fd, int family, char *ipstr, int port, int timeout_ms); +ZTS_API int ZTCALL zts_connect_easy(int fd, int family, char* ipstr, int port, int timeout_ms); /** * @brief Bind a socket to a local address @@ -1552,8 +1550,7 @@ ZTS_API int ZTCALL zts_connect_easy( * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_bind( - int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen); +ZTS_API int ZTCALL zts_bind(int fd, const struct zts_sockaddr* addr, zts_socklen_t addrlen); /** * @brief Bind a socket to a local address @@ -1565,7 +1562,7 @@ ZTS_API int ZTCALL zts_bind( * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_bind_easy(int fd, int family, char *ipstr, int port); +ZTS_API int ZTCALL zts_bind_easy(int fd, int family, char* ipstr, int port); /** * @brief Listen for incoming connections on socket @@ -1586,8 +1583,7 @@ ZTS_API int ZTCALL zts_listen(int fd, int backlog); * @return New file descriptor if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_accept( - int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen); +ZTS_API int ZTCALL zts_accept(int fd, struct zts_sockaddr* addr, zts_socklen_t* addrlen); /** * @brief Accept an incoming connection @@ -1600,35 +1596,35 @@ ZTS_API int ZTCALL zts_accept( * @return New file descriptor if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_accept_easy(int fd, char *remoteIpStr, int len, int *port); +ZTS_API int ZTCALL zts_accept_easy(int fd, char* remoteIpStr, int len, int* port); // Socket level option number -#define ZTS_SOL_SOCKET 0x0fff +#define ZTS_SOL_SOCKET 0x0fff // Socket options -#define ZTS_SO_DEBUG 0x0001 // NOT YET SUPPORTED -#define ZTS_SO_ACCEPTCONN 0x0002 -#define ZTS_SO_REUSEADDR 0x0004 -#define ZTS_SO_KEEPALIVE 0x0008 -#define ZTS_SO_DONTROUTE 0x0010 // NOT YET SUPPORTED -#define ZTS_SO_BROADCAST 0x0020 -#define ZTS_SO_USELOOPBACK 0x0040 // NOT YET SUPPORTED -#define ZTS_SO_LINGER 0x0080 +#define ZTS_SO_DEBUG 0x0001 // NOT YET SUPPORTED +#define ZTS_SO_ACCEPTCONN 0x0002 +#define ZTS_SO_REUSEADDR 0x0004 +#define ZTS_SO_KEEPALIVE 0x0008 +#define ZTS_SO_DONTROUTE 0x0010 // NOT YET SUPPORTED +#define ZTS_SO_BROADCAST 0x0020 +#define ZTS_SO_USELOOPBACK 0x0040 // NOT YET SUPPORTED +#define ZTS_SO_LINGER 0x0080 /* * Structure used for manipulating linger option. */ struct zts_linger { - int l_onoff; // option on/off - int l_linger; // linger time in seconds + int l_onoff; // option on/off + int l_linger; // linger time in seconds }; #define ZTS_SO_DONTLINGER ((int)(~ZTS_SO_LINGER)) -#define ZTS_SO_OOBINLINE 0x0100 // NOT YET SUPPORTED -#define ZTS_SO_REUSEPORT 0x0200 // NOT YET SUPPORTED -#define ZTS_SO_SNDBUF 0x1001 // NOT YET SUPPORTED +#define ZTS_SO_OOBINLINE 0x0100 // NOT YET SUPPORTED +#define ZTS_SO_REUSEPORT 0x0200 // NOT YET SUPPORTED +#define ZTS_SO_SNDBUF 0x1001 // NOT YET SUPPORTED #define ZTS_SO_RCVBUF 0x1002 -#define ZTS_SO_SNDLOWAT 0x1003 // NOT YET SUPPORTED -#define ZTS_SO_RCVLOWAT 0x1004 // NOT YET SUPPORTED +#define ZTS_SO_SNDLOWAT 0x1003 // NOT YET SUPPORTED +#define ZTS_SO_RCVLOWAT 0x1004 // NOT YET SUPPORTED #define ZTS_SO_SNDTIMEO 0x1005 #define ZTS_SO_RCVTIMEO 0x1006 #define ZTS_SO_ERROR 0x1007 @@ -1637,25 +1633,28 @@ struct zts_linger { #define ZTS_SO_NO_CHECK 0x100a #define ZTS_SO_BINDTODEVICE 0x100b // IPPROTO_IP options -#define ZTS_IP_TOS 0x0001 -#define ZTS_IP_TTL 0x0002 -#define ZTS_IP_PKTINFO 0x0008 +#define ZTS_IP_TOS 0x0001 +#define ZTS_IP_TTL 0x0002 +#define ZTS_IP_PKTINFO 0x0008 // IPPROTO_TCP options -#define ZTS_TCP_NODELAY 0x0001 -#define ZTS_TCP_KEEPALIVE 0x0002 -#define ZTS_TCP_KEEPIDLE 0x0003 -#define ZTS_TCP_KEEPINTVL 0x0004 -#define ZTS_TCP_KEEPCNT 0x0005 +#define ZTS_TCP_NODELAY 0x0001 +#define ZTS_TCP_KEEPALIVE 0x0002 +#define ZTS_TCP_KEEPIDLE 0x0003 +#define ZTS_TCP_KEEPINTVL 0x0004 +#define ZTS_TCP_KEEPCNT 0x0005 // IPPROTO_IPV6 options -#define ZTS_IPV6_CHECKSUM 0x0007 /* RFC3542: calculate and insert the ICMPv6 checksum for raw sockets. */ -#define ZTS_IPV6_V6ONLY 0x001b /* RFC3493: boolean control to restrict ZTS_AF_INET6 sockets to IPv6 communications only. */ +#define ZTS_IPV6_CHECKSUM \ + 0x0007 /* RFC3542: calculate and insert the ICMPv6 checksum for raw sockets. */ +#define ZTS_IPV6_V6ONLY \ + 0x001b /* RFC3493: boolean control to restrict ZTS_AF_INET6 sockets to IPv6 communications \ + only. */ // UDPLITE options #define ZTS_UDPLITE_SEND_CSCOV 0x01 /* sender checksum coverage */ #define ZTS_UDPLITE_RECV_CSCOV 0x02 /* minimal receiver checksum coverage */ // UDPLITE options -#define ZTS_IP_MULTICAST_TTL 5 -#define ZTS_IP_MULTICAST_IF 6 -#define ZTS_IP_MULTICAST_LOOP 7 +#define ZTS_IP_MULTICAST_TTL 5 +#define ZTS_IP_MULTICAST_IF 6 +#define ZTS_IP_MULTICAST_LOOP 7 // Multicast options #define ZTS_IP_ADD_MEMBERSHIP 3 @@ -1667,8 +1666,8 @@ typedef struct zts_ip_mreq { } zts_ip_mreq; struct zts_in_pktinfo { - unsigned int ipi_ifindex; /* Interface index */ - struct zts_in_addr ipi_addr; /* Destination (from header) address */ + unsigned int ipi_ifindex; /* Interface index */ + struct zts_in_addr ipi_addr; /* Destination (from header) address */ }; #define ZTS_IPV6_JOIN_GROUP 12 @@ -1678,7 +1677,7 @@ struct zts_in_pktinfo { typedef struct zts_ipv6_mreq { struct zts_in6_addr ipv6mr_multiaddr; /* IPv6 multicast addr */ - unsigned int ipv6mr_interface; /* interface index, or 0 */ + unsigned int ipv6mr_interface; /* interface index, or 0 */ } zts_ipv6_mreq; /* @@ -1697,13 +1696,13 @@ typedef struct zts_ipv6_mreq { * performance on another. Except for very unusual cases at most two * of these three indications should be set. */ -#define ZTS_IPTOS_TOS_MASK 0x1E -#define ZTS_IPTOS_TOS(tos) ((tos) & ZTS_IPTOS_TOS_MASK) -#define ZTS_IPTOS_LOWDELAY 0x10 -#define ZTS_IPTOS_THROUGHPUT 0x08 -#define ZTS_IPTOS_RELIABILITY 0x04 -#define ZTS_IPTOS_LOWCOST 0x02 -#define ZTS_IPTOS_MINCOST ZTS_IPTOS_LOWCOST +#define ZTS_IPTOS_TOS_MASK 0x1E +#define ZTS_IPTOS_TOS(tos) ((tos)&ZTS_IPTOS_TOS_MASK) +#define ZTS_IPTOS_LOWDELAY 0x10 +#define ZTS_IPTOS_THROUGHPUT 0x08 +#define ZTS_IPTOS_RELIABILITY 0x04 +#define ZTS_IPTOS_LOWCOST 0x02 +#define ZTS_IPTOS_MINCOST ZTS_IPTOS_LOWCOST /* * The Network Control precedence designation is intended to be used @@ -1714,16 +1713,16 @@ typedef struct zts_ipv6_mreq { * a particular network, it is the responsibility of that network to * control the access to, and use of, those precedence designations. */ -#define ZTS_IPTOS_PREC_MASK 0xe0 -#define ZTS_IPTOS_PREC(tos) ((tos) & ZTS_IPTOS_PREC_MASK) -#define ZTS_IPTOS_PREC_NETCONTROL 0xe0 -#define ZTS_IPTOS_PREC_INTERNETCONTROL 0xc0 -#define ZTS_IPTOS_PREC_CRITIC_ECP 0xa0 -#define ZTS_IPTOS_PREC_FLASHOVERRIDE 0x80 -#define ZTS_IPTOS_PREC_FLASH 0x60 -#define ZTS_IPTOS_PREC_IMMEDIATE 0x40 -#define ZTS_IPTOS_PREC_PRIORITY 0x20 -#define ZTS_IPTOS_PREC_ROUTINE 0x00 +#define ZTS_IPTOS_PREC_MASK 0xe0 +#define ZTS_IPTOS_PREC(tos) ((tos)&ZTS_IPTOS_PREC_MASK) +#define ZTS_IPTOS_PREC_NETCONTROL 0xe0 +#define ZTS_IPTOS_PREC_INTERNETCONTROL 0xc0 +#define ZTS_IPTOS_PREC_CRITIC_ECP 0xa0 +#define ZTS_IPTOS_PREC_FLASHOVERRIDE 0x80 +#define ZTS_IPTOS_PREC_FLASH 0x60 +#define ZTS_IPTOS_PREC_IMMEDIATE 0x40 +#define ZTS_IPTOS_PREC_PRIORITY 0x20 +#define ZTS_IPTOS_PREC_ROUTINE 0x00 /** * @brief Set socket options @@ -1736,8 +1735,8 @@ typedef struct zts_ipv6_mreq { * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_setsockopt( - int fd, int level, int optname, const void *optval, zts_socklen_t optlen); +ZTS_API int ZTCALL +zts_setsockopt(int fd, int level, int optname, const void* optval, zts_socklen_t optlen); /** * @brief Get socket options @@ -1750,8 +1749,8 @@ ZTS_API int ZTCALL zts_setsockopt( * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_getsockopt( - int fd, int level, int optname, void *optval, zts_socklen_t *optlen); +ZTS_API int ZTCALL +zts_getsockopt(int fd, int level, int optname, void* optval, zts_socklen_t* optlen); /** * @brief Get socket name @@ -1762,7 +1761,7 @@ ZTS_API int ZTCALL zts_getsockopt( * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_getsockname(int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen); +ZTS_API int ZTCALL zts_getsockname(int fd, struct zts_sockaddr* addr, zts_socklen_t* addrlen); /** * @brief Get the peer name for the remote end of a connected socket @@ -1773,7 +1772,7 @@ ZTS_API int ZTCALL zts_getsockname(int fd, struct zts_sockaddr *addr, zts_sockle * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_getpeername(int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen); +ZTS_API int ZTCALL zts_getpeername(int fd, struct zts_sockaddr* addr, zts_socklen_t* addrlen); /** * @brief Close a socket @@ -1790,37 +1789,47 @@ ZTS_API int ZTCALL zts_close(int fd); #define MEMP_NUM_NETCONN 1024 #ifndef ZTS_FD_SET -#undef ZTS_FD_SETSIZE -// Make FD_SETSIZE match NUM_SOCKETS in socket.c -#define ZTS_FD_SETSIZE MEMP_NUM_NETCONN -#define ZTS_FDSETSAFESET(n, code) do { \ - if (((n) - LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n) - LWIP_SOCKET_OFFSET) >= 0)) { \ - code; }} while(0) -#define ZTS_FDSETSAFEGET(n, code) \ - (((n) - LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n) - LWIP_SOCKET_OFFSET) >= 0) ? \ - (code) : 0) -#define ZTS_FD_SET(n, p) \ - ZTS_FDSETSAFESET(n, (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET)/8] |= (1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) -#define ZTS_FD_CLR(n, p) \ - ZTS_FDSETSAFESET(n, (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET)/8] &= ~(1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) -#define ZTS_FD_ISSET(n,p) \ - ZTS_FDSETSAFEGET(n, (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET)/8] & (1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) -#define ZTS_FD_ZERO(p) memset((void*)(p), 0, sizeof(*(p))) + #undef ZTS_FD_SETSIZE + // Make FD_SETSIZE match NUM_SOCKETS in socket.c + #define ZTS_FD_SETSIZE MEMP_NUM_NETCONN + #define ZTS_FDSETSAFESET(n, code) \ + do { \ + if (((n)-LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) \ + && (((int)(n)-LWIP_SOCKET_OFFSET) >= 0)) { \ + code; \ + } \ + } while (0) + #define ZTS_FDSETSAFEGET(n, code) \ + (((n)-LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n)-LWIP_SOCKET_OFFSET) >= 0) \ + ? (code) \ + : 0) + #define ZTS_FD_SET(n, p) \ + ZTS_FDSETSAFESET( \ + n, \ + (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET) / 8] |= (1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) + #define ZTS_FD_CLR(n, p) \ + ZTS_FDSETSAFESET( \ + n, \ + (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET) / 8] &= ~(1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) + #define ZTS_FD_ISSET(n, p) \ + ZTS_FDSETSAFEGET( \ + n, \ + (p)->fd_bits[((n)-LWIP_SOCKET_OFFSET) / 8] & (1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) + #define ZTS_FD_ZERO(p) memset((void*)(p), 0, sizeof(*(p))) #elif LWIP_SOCKET_OFFSET -#error LWIP_SOCKET_OFFSET does not work with external FD_SET! + #error LWIP_SOCKET_OFFSET does not work with external FD_SET! #elif ZTS_FD_SETSIZE < MEMP_NUM_NETCONN -#error "external ZTS_FD_SETSIZE too small for number of sockets" -#endif // FD_SET + #error "external ZTS_FD_SETSIZE too small for number of sockets" +#endif // FD_SET -typedef struct zts_fd_set -{ - unsigned char fd_bits [(ZTS_FD_SETSIZE+7)/8]; +typedef struct zts_fd_set { + unsigned char fd_bits[(ZTS_FD_SETSIZE + 7) / 8]; } zts_fd_set; struct zts_timeval { - long tv_sec; /* seconds */ - long tv_usec; /* and microseconds */ + long tv_sec; /* seconds */ + long tv_usec; /* and microseconds */ }; /** @@ -1834,18 +1843,22 @@ struct zts_timeval { * @return Number of ready file descriptors on success. ZTS_ERR_SOCKET, ZTS_ERR_SERVICE on failure. */ ZTS_API int ZTCALL zts_select( - int nfds, zts_fd_set *readfds, zts_fd_set *writefds, zts_fd_set *exceptfds, struct zts_timeval *timeout); + int nfds, + zts_fd_set* readfds, + zts_fd_set* writefds, + zts_fd_set* exceptfds, + struct zts_timeval* timeout); // fnctl() commands -#define ZTS_F_GETFL 0x0003 -#define ZTS_F_SETFL 0x0004 +#define ZTS_F_GETFL 0x0003 +#define ZTS_F_SETFL 0x0004 /* File status flags and file access modes for fnctl, these are bits in an int. */ -#define ZTS_O_NONBLOCK 1 -#define ZTS_O_NDELAY ZTS_O_NONBLOCK -#define ZTS_O_RDONLY 2 -#define ZTS_O_WRONLY 4 -#define ZTS_O_RDWR (ZTS_O_RDONLY|ZTS_O_WRONLY) +#define ZTS_O_NONBLOCK 1 +#define ZTS_O_NDELAY ZTS_O_NONBLOCK +#define ZTS_O_RDONLY 2 +#define ZTS_O_WRONLY 4 +#define ZTS_O_RDWR (ZTS_O_RDONLY | ZTS_O_WRONLY) /** * @brief Issue file control commands on a socket @@ -1857,10 +1870,10 @@ ZTS_API int ZTCALL zts_select( */ ZTS_API int ZTCALL zts_fcntl(int fd, int cmd, int flags); -#define ZTS_POLLIN 0x001 -#define ZTS_POLLOUT 0x002 -#define ZTS_POLLERR 0x004 -#define ZTS_POLLNVAL 0x008 +#define ZTS_POLLIN 0x001 +#define ZTS_POLLOUT 0x002 +#define ZTS_POLLERR 0x004 +#define ZTS_POLLNVAL 0x008 /* Below values are unimplemented */ #define ZTS_POLLRDNORM 0x010 #define ZTS_POLLRDBAND 0x020 @@ -1871,11 +1884,10 @@ ZTS_API int ZTCALL zts_fcntl(int fd, int cmd, int flags); typedef unsigned int zts_nfds_t; -struct zts_pollfd -{ - int fd; - short events; - short revents; +struct zts_pollfd { + int fd; + short events; + short revents; }; /** @@ -1887,7 +1899,7 @@ struct zts_pollfd * @return Number of ready file descriptors if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_poll(struct zts_pollfd *fds, zts_nfds_t nfds, int timeout); +ZTS_API int ZTCALL zts_poll(struct zts_pollfd* fds, zts_nfds_t nfds, int timeout); /** * @brief Control a device @@ -1898,7 +1910,7 @@ ZTS_API int ZTCALL zts_poll(struct zts_pollfd *fds, zts_nfds_t nfds, int timeout * @return `ZTS_ERR_OK` if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API int ZTCALL zts_ioctl(int fd, unsigned long request, void *argp); +ZTS_API int ZTCALL zts_ioctl(int fd, unsigned long request, void* argp); /** * @brief Send data to remote host @@ -1910,7 +1922,7 @@ ZTS_API int ZTCALL zts_ioctl(int fd, unsigned long request, void *argp); * @return Number of bytes sent if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API ssize_t ZTCALL zts_send(int fd, const void *buf, size_t len, int flags); +ZTS_API ssize_t ZTCALL zts_send(int fd, const void* buf, size_t len, int flags); /** * @brief Send data to remote host @@ -1925,27 +1937,32 @@ ZTS_API ssize_t ZTCALL zts_send(int fd, const void *buf, size_t len, int flags); * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ ZTS_API ssize_t ZTCALL zts_sendto( - int fd, const void *buf, size_t len, int flags, const struct zts_sockaddr *addr, zts_socklen_t addrlen); + int fd, + const void* buf, + size_t len, + int flags, + const struct zts_sockaddr* addr, + zts_socklen_t addrlen); struct zts_iovec { - void *iov_base; + void* iov_base; size_t iov_len; }; /* */ struct zts_msghdr { - void *msg_name; - zts_socklen_t msg_namelen; - struct zts_iovec *msg_iov; - int msg_iovlen; - void *msg_control; - zts_socklen_t msg_controllen; - int msg_flags; + void* msg_name; + zts_socklen_t msg_namelen; + struct zts_iovec* msg_iov; + int msg_iovlen; + void* msg_control; + zts_socklen_t msg_controllen; + int msg_flags; }; /* struct msghdr->msg_flags bit field values */ -#define ZTS_MSG_TRUNC 0x04 -#define ZTS_MSG_CTRUNC 0x08 +#define ZTS_MSG_TRUNC 0x04 +#define ZTS_MSG_CTRUNC 0x08 /** * @brief Send message to remote host @@ -1956,7 +1973,7 @@ struct zts_msghdr { * @return Number of bytes sent if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API ssize_t ZTCALL zts_sendmsg(int fd, const struct zts_msghdr *msg, int flags); +ZTS_API ssize_t ZTCALL zts_sendmsg(int fd, const struct zts_msghdr* msg, int flags); /** * @brief Receive data from remote host @@ -1968,7 +1985,7 @@ ZTS_API ssize_t ZTCALL zts_sendmsg(int fd, const struct zts_msghdr *msg, int fla * @return Number of bytes received if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API ssize_t ZTCALL zts_recv(int fd, void *buf, size_t len, int flags); +ZTS_API ssize_t ZTCALL zts_recv(int fd, void* buf, size_t len, int flags); /** * @brief Receive data from remote host @@ -1983,7 +2000,12 @@ ZTS_API ssize_t ZTCALL zts_recv(int fd, void *buf, size_t len, int flags); * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ ZTS_API ssize_t ZTCALL zts_recvfrom( - int fd, void *buf, size_t len, int flags, struct zts_sockaddr *addr, zts_socklen_t *addrlen); + int fd, + void* buf, + size_t len, + int flags, + struct zts_sockaddr* addr, + zts_socklen_t* addrlen); /** * @brief Receive a message from remote host @@ -1994,7 +2016,7 @@ ZTS_API ssize_t ZTCALL zts_recvfrom( * @return Number of bytes received if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API ssize_t ZTCALL zts_recvmsg(int fd, struct zts_msghdr *msg,int flags); +ZTS_API ssize_t ZTCALL zts_recvmsg(int fd, struct zts_msghdr* msg, int flags); /** * @brief Read bytes from socket onto buffer @@ -2005,7 +2027,7 @@ ZTS_API ssize_t ZTCALL zts_recvmsg(int fd, struct zts_msghdr *msg,int flags); * @return Number of bytes read if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API ssize_t ZTCALL zts_read(int fd, void *buf, size_t len); +ZTS_API ssize_t ZTCALL zts_read(int fd, void* buf, size_t len); /** * @brief Read bytes from socket into multiple buffers @@ -2016,7 +2038,7 @@ ZTS_API ssize_t ZTCALL zts_read(int fd, void *buf, size_t len); * @return Number of bytes read if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API ssize_t ZTCALL zts_readv(int fd, const struct zts_iovec *iov, int iovcnt); +ZTS_API ssize_t ZTCALL zts_readv(int fd, const struct zts_iovec* iov, int iovcnt); /** * @brief Write bytes from buffer to socket @@ -2027,7 +2049,7 @@ ZTS_API ssize_t ZTCALL zts_readv(int fd, const struct zts_iovec *iov, int iovcnt * @return Number of bytes written if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API ssize_t ZTCALL zts_write(int fd, const void *buf, size_t len); +ZTS_API ssize_t ZTCALL zts_write(int fd, const void* buf, size_t len); /** * @brief Write data from multiple buffers to socket. @@ -2038,7 +2060,7 @@ ZTS_API ssize_t ZTCALL zts_write(int fd, const void *buf, size_t len); * @return Number of bytes written if successful, `ZTS_ERR_SERVICE` if the node * experiences a problem, `ZTS_ERR_ARG` if invalid arg. Sets `zts_errno` */ -ZTS_API ssize_t ZTCALL zts_writev(int fd, const struct zts_iovec *iov, int iovcnt); +ZTS_API ssize_t ZTCALL zts_writev(int fd, const struct zts_iovec* iov, int iovcnt); #define ZTS_SHUT_RD 0x0 #define ZTS_SHUT_WR 0x1 @@ -2059,11 +2081,11 @@ ZTS_API int ZTCALL zts_shutdown(int fd, int how); //----------------------------------------------------------------------------// /** -* Helper functions that simplify API wrapper generation and usage in other -* non-C-like languages. Use simple integer types instead of bit flags, limit -* the number of operations each function performs, prevent the user from -* needing to manipulate the content of structures in a non-native language. -*/ + * Helper functions that simplify API wrapper generation and usage in other + * non-C-like languages. Use simple integer types instead of bit flags, limit + * the number of operations each function performs, prevent the user from + * needing to manipulate the content of structures in a non-native language. + */ /** * @brief Enable or disable `TCP_NODELAY`. Enabling this is equivalent to @@ -2272,13 +2294,13 @@ ZTS_API int ZTCALL zts_get_keepalive(int fd); //----------------------------------------------------------------------------// struct zts_hostent { - char *h_name; /* Official name of the host. */ - char **h_aliases; /* A pointer to an array of pointers to alternative host names, - terminated by a null pointer. */ - int h_addrtype; /* Address type. */ - int h_length; /* The length, in bytes, of the address. */ - char **h_addr_list; /* A pointer to an array of pointers to network addresses (in - network byte order) for the host, terminated by a null pointer. */ + char* h_name; /* Official name of the host. */ + char** h_aliases; /* A pointer to an array of pointers to alternative host names, + terminated by a null pointer. */ + int h_addrtype; /* Address type. */ + int h_length; /* The length, in bytes, of the address. */ + char** h_addr_list; /* A pointer to an array of pointers to network addresses (in + network byte order) for the host, terminated by a null pointer. */ #define h_addr h_addr_list[0] /* for backward compatibility */ }; @@ -2288,12 +2310,12 @@ struct zts_hostent { * @param name A null-terminated string representing the name of the host * @return Pointer to struct zts_hostent if successful, NULL otherwise */ -struct zts_hostent *zts_gethostbyname(const char *name); +struct zts_hostent* zts_gethostbyname(const char* name); enum zts_ip_addr_type { - ZTS_IPADDR_TYPE_V4 = 0U, - ZTS_IPADDR_TYPE_V6 = 6U, - ZTS_IPADDR_TYPE_ANY = 46U // Dual stack + ZTS_IPADDR_TYPE_V4 = 0U, + ZTS_IPADDR_TYPE_V6 = 6U, + ZTS_IPADDR_TYPE_ANY = 46U // Dual stack }; struct zts_ip4_addr { @@ -2301,7 +2323,7 @@ struct zts_ip4_addr { }; /** This is the aligned version of ip6_addr_t, - used as local variable, on the stack, etc. */ + used as local variable, on the stack, etc. */ struct zts_ip6_addr { uint32_t addr[4]; #if LWIP_IPV6_SCOPES @@ -2318,7 +2340,7 @@ typedef struct zts_ip_addr { struct zts_ip6_addr ip6; struct zts_ip4_addr ip4; } u_addr; - uint8_t type; // ZTS_IPADDR_TYPE_V4, ZTS_IPADDR_TYPE_V6 + uint8_t type; // ZTS_IPADDR_TYPE_V4, ZTS_IPADDR_TYPE_V6 } zts_ip_addr; /** @@ -2327,7 +2349,7 @@ typedef struct zts_ip_addr { * @param index the index of the DNS server to set must be < DNS_MAX_SERVERS * @param addr IP address of the DNS server to set */ -ZTS_API int ZTCALL zts_dns_set_server(uint8_t index, const zts_ip_addr *addr); +ZTS_API int ZTCALL zts_dns_set_server(uint8_t index, const zts_ip_addr* addr); /** * Obtain one of the currently configured DNS server. @@ -2336,7 +2358,7 @@ ZTS_API int ZTCALL zts_dns_set_server(uint8_t index, const zts_ip_addr *addr); * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS * server has not been configured. */ -ZTS_API const zts_ip_addr * ZTCALL zts_dns_get_server(uint8_t index); +ZTS_API const zts_ip_addr* ZTCALL zts_dns_get_server(uint8_t index); //----------------------------------------------------------------------------// // Convenience functions pulled from lwIP // @@ -2349,7 +2371,7 @@ ZTS_API const zts_ip_addr * ZTCALL zts_dns_get_server(uint8_t index); * @return pointer to a global static (!) buffer that holds the ASCII * representation of addr */ -char *zts_ipaddr_ntoa(const zts_ip_addr *addr); +char* zts_ipaddr_ntoa(const zts_ip_addr* addr); /** * Convert IP address string (both versions) to numeric. @@ -2359,7 +2381,7 @@ char *zts_ipaddr_ntoa(const zts_ip_addr *addr); * @param addr conversion result is stored here * @return `1` on success, `0` on error */ -int zts_ipaddr_aton(const char *cp, zts_ip_addr *addr); +int zts_ipaddr_aton(const char* cp, zts_ip_addr* addr); /** * Convert IPv4 and IPv6 address structures to human-readable text form. @@ -2370,8 +2392,8 @@ int zts_ipaddr_aton(const char *cp, zts_ip_addr *addr); * @param size Size of the destination buffer * @return On success, returns a non-null pointer to the destination character array */ -ZTS_API const char * ZTCALL zts_inet_ntop( - int family, const void *src, char *dst, zts_socklen_t size); +ZTS_API const char* ZTCALL +zts_inet_ntop(int family, const void* src, char* dst, zts_socklen_t size); /** * Convert C-string IPv4 and IPv6 addresses to binary form. @@ -2381,7 +2403,7 @@ ZTS_API const char * ZTCALL zts_inet_ntop( * @param dst Pointer to destination address structure * @return return `1` on success. `0` or `-1` on failure. (Does not follow `zts_*` conventions) */ -ZTS_API int ZTCALL zts_inet_pton(int family, const char *src, void *dst); +ZTS_API int ZTCALL zts_inet_pton(int family, const char* src, void* dst); /** * Convert human-friendly IP string to `zts_sockaddr_in` or `zts_sockaddr_in6`. @@ -2390,14 +2412,19 @@ ZTS_API int ZTCALL zts_inet_pton(int family, const char *src, void *dst); * @param src_ipstr Source IP string * @param port Port * @param dest_addr Pointer to destination structure `zts_sockaddr_in` or `zts_sockaddr_in6` - * @param addrlen Size of destination structure. Value-result: Will be set to actual size of data available + * @param addrlen Size of destination structure. Value-result: Will be set to actual size of data + * available * @return return `ZTS_ERR_OK` on success, `ZTS_ERR_ARG` if invalid argument */ int ipstr2sockaddr( - int family, char *src_ipstr, int port, struct zts_sockaddr *dest_addr, zts_socklen_t *addrlen); + int family, + char* src_ipstr, + int port, + struct zts_sockaddr* dest_addr, + zts_socklen_t* addrlen); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // _H +#endif // _H diff --git a/src/Central.cpp b/src/Central.cpp index 37df497..bbe71a0 100644 --- a/src/Central.cpp +++ b/src/Central.cpp @@ -16,20 +16,20 @@ #ifdef ZTS_ENABLE_CENTRAL_API -#include -#include -#include -#include -#include + #include "Debug.hpp" + #include "Mutex.hpp" + #include "ZeroTierSockets.h" -#include "Mutex.hpp" -#include "Debug.hpp" -#include "ZeroTierSockets.h" + #include + #include + #include + #include + #include char api_url[ZTS_CENRTAL_MAX_URL_LEN]; -char api_token[ZTS_CENTRAL_TOKEN_LEN+1]; +char api_token[ZTS_CENTRAL_TOKEN_LEN + 1]; -char *_resp_buf; +char* _resp_buf; int _resp_buf_len; int _resp_buf_offset; @@ -41,19 +41,19 @@ using namespace ZeroTier; Mutex _responseBuffer_m; -#ifdef __cplusplus + #ifdef __cplusplus extern "C" { -#endif + #endif -size_t on_data(void *buffer, size_t size, size_t nmemb, void *userp) +size_t on_data(void* buffer, size_t size, size_t nmemb, void* userp) { DEBUG_INFO("buf=%p,size=%zu,nmemb=%zu,userp=%p", buffer, size, nmemb, userp); int byte_count = (size * nmemb); if (_resp_buf_offset + byte_count >= _resp_buf_len) { DEBUG_ERROR("Out of buffer space. Cannot store response from server"); - return 0; // Signal to libcurl that our buffer is full (triggers a write error.) + return 0; // Signal to libcurl that our buffer is full (triggers a write error.) } - memcpy(_resp_buf+_resp_buf_offset, buffer, byte_count); + memcpy(_resp_buf + _resp_buf_offset, buffer, byte_count); _resp_buf_offset += byte_count; return byte_count; } @@ -76,10 +76,13 @@ void zts_central_clear_resp_buf() } int zts_central_init( - const char *url_str, const char *token_str, char *resp_buf, uint32_t resp_buf_len) + const char* url_str, + const char* token_str, + char* resp_buf, + uint32_t resp_buf_len) { - _access_modes = ZTS_CENTRAL_READ; // Defauly read-only - _bIsVerbose = 0; // Default disable libcurl verbose output + _access_modes = ZTS_CENTRAL_READ; // Defauly read-only + _bIsVerbose = 0; // Default disable libcurl verbose output Mutex::Lock _l(_responseBuffer_m); if (resp_buf_len == 0) { return ZTS_ERR_ARG; @@ -93,14 +96,16 @@ int zts_central_init( int url_len = strlen(url_str); if (url_len < 3 || url_len > ZTS_CENRTAL_MAX_URL_LEN) { return ZTS_ERR_ARG; - } else { + } + else { memset(api_url, 0, ZTS_CENRTAL_MAX_URL_LEN); memcpy(api_url, url_str, url_len); } int token_len = strlen(token_str); if (token_len != ZTS_CENTRAL_TOKEN_LEN) { return ZTS_ERR_ARG; - } else { + } + else { memset(api_token, 0, ZTS_CENTRAL_TOKEN_LEN); memcpy(api_token, token_str, token_len); } @@ -113,19 +118,24 @@ void zts_central_cleanup() curl_global_cleanup(); } -int _central_req(int request_type, char *central_str, - char *api_route_str, char *token_str, int *response_code, char *post_data) +int _central_req( + int request_type, + char* central_str, + char* api_route_str, + char* token_str, + int* response_code, + char* post_data) { int err = ZTS_ERR_OK; - if (!_bInit) { + if (! _bInit) { DEBUG_ERROR("Error: Central API must be initialized first. Call zts_central_init()"); return ZTS_ERR_SERVICE; } - if (request_type == ZTS_HTTP_GET && !(_access_modes & ZTS_CENTRAL_READ)) { + if (request_type == ZTS_HTTP_GET && ! (_access_modes & ZTS_CENTRAL_READ)) { DEBUG_ERROR("Error: Incorrect access mode. Need (ZTS_CENTRAL_READ) permission"); return ZTS_ERR_SERVICE; } - if (request_type == ZTS_HTTP_POST && !(_access_modes & ZTS_CENTRAL_WRITE)) { + if (request_type == ZTS_HTTP_POST && ! (_access_modes & ZTS_CENTRAL_WRITE)) { DEBUG_ERROR("Error: Incorrect access mode. Need (ZTS_CENTRAL_WRITE) permission"); return ZTS_ERR_SERVICE; } @@ -144,14 +154,14 @@ int _central_req(int request_type, char *central_str, strcpy(req_url, central_str); strcat(req_url, api_route_str); - CURL *curl; + CURL* curl; CURLcode res; curl = curl_easy_init(); - if (!curl) { + if (! curl) { return ZTS_ERR_GENERAL; } - struct curl_slist *hs=NULL; + struct curl_slist* hs = NULL; char auth_str[ZTS_CENTRAL_TOKEN_LEN + 32]; if (token_strlen == ZTS_CENTRAL_TOKEN_LEN) { memset(auth_str, 0, ZTS_CENTRAL_TOKEN_LEN + 32); @@ -184,19 +194,20 @@ int _central_req(int request_type, char *central_str, if (request_type == ZTS_HTTP_DELETE) { curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); } - //curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); // Consider 400-500 series code as failures + // curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); // Consider 400-500 series code as failures // Perform request res = curl_easy_perform(curl); - if(res == CURLE_OK) { - //char* url; + if (res == CURLE_OK) { + // char* url; double elapsed_time = 0.0; long hrc = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &hrc); curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed_time); DEBUG_INFO("Req. took %f second(s). HTTP code (%ld)", elapsed_time, hrc); *response_code = hrc; - //curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url); - } else { + // curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url); + } + else { DEBUG_ERROR("%s", curl_easy_strerror(res)); err = ZTS_ERR_SERVICE; } @@ -204,7 +215,7 @@ int _central_req(int request_type, char *central_str, return err; } -int zts_get_last_resp_buf(char *dest_buffer, int dest_buf_len) +int zts_get_last_resp_buf(char* dest_buffer, int dest_buf_len) { if (dest_buf_len <= _resp_buf_offset) { return ZTS_ERR_ARG; @@ -214,73 +225,63 @@ int zts_get_last_resp_buf(char *dest_buffer, int dest_buf_len) return ZTS_ERR_OK; } -int zts_central_get_status(int *resp_code) +int zts_central_get_status(int* resp_code) { - return _central_req( - ZTS_HTTP_GET, api_url, (char*)"/api/status", api_token, resp_code, NULL); + return _central_req(ZTS_HTTP_GET, api_url, (char*)"/api/status", api_token, resp_code, NULL); } -int zts_central_get_self(int *resp_code) +int zts_central_get_self(int* resp_code) { - return _central_req( - ZTS_HTTP_GET, api_url, (char*)"/api/self", api_token, resp_code, NULL); + return _central_req(ZTS_HTTP_GET, api_url, (char*)"/api/self", api_token, resp_code, NULL); } -int zts_central_get_network(int *resp_code, uint64_t nwid) +int zts_central_get_network(int* resp_code, uint64_t nwid) { char req[64]; sprintf(req, "/api/network/%llx", nwid); - return _central_req( - ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL); + return _central_req(ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL); } -int zts_central_update_network(int *resp_code, uint64_t nwid) +int zts_central_update_network(int* resp_code, uint64_t nwid) { char req[64]; sprintf(req, "/api/network/%llx", nwid); - return _central_req( - ZTS_HTTP_POST, api_url, req, api_token, resp_code, NULL); + return _central_req(ZTS_HTTP_POST, api_url, req, api_token, resp_code, NULL); } -int zts_central_delete_network(int *resp_code, uint64_t nwid) +int zts_central_delete_network(int* resp_code, uint64_t nwid) { char req[64]; sprintf(req, "/api/network/%llx", nwid); - return _central_req( - ZTS_HTTP_DELETE, api_url, req, api_token, resp_code, NULL); + return _central_req(ZTS_HTTP_DELETE, api_url, req, api_token, resp_code, NULL); } -int zts_central_get_networks(int *resp_code) +int zts_central_get_networks(int* resp_code) { - return _central_req( - ZTS_HTTP_GET, api_url, (char*)"/api/network", api_token, resp_code, NULL); + return _central_req(ZTS_HTTP_GET, api_url, (char*)"/api/network", api_token, resp_code, NULL); } -int zts_central_get_member(int *resp_code, uint64_t nwid, uint64_t nodeid) +int zts_central_get_member(int* resp_code, uint64_t nwid, uint64_t nodeid) { if (nwid == 0 || nodeid == 0) { return ZTS_ERR_ARG; } char req[64]; sprintf(req, "/api/network/%llx/member/%llx", nwid, nodeid); - return _central_req( - ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL); + return _central_req(ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL); } -int zts_central_update_member( - int *resp_code, uint64_t nwid, uint64_t nodeid, char *post_data) +int zts_central_update_member(int* resp_code, uint64_t nwid, uint64_t nodeid, char* post_data) { if (nwid == 0 || nodeid == 0 || post_data == NULL) { return ZTS_ERR_ARG; } char req[64]; sprintf(req, "/api/network/%llx/member/%llx", nwid, nodeid); - return _central_req( - ZTS_HTTP_POST, api_url, req, api_token, resp_code, post_data); + return _central_req(ZTS_HTTP_POST, api_url, req, api_token, resp_code, post_data); } -int zts_central_set_node_auth( - int *resp_code, uint64_t nwid, uint64_t nodeid, uint8_t is_authed) +int zts_central_set_node_auth(int* resp_code, uint64_t nwid, uint64_t nodeid, uint8_t is_authed) { if (is_authed != 0 && is_authed != 1) { return ZTS_ERR_ARG; @@ -295,17 +296,16 @@ int zts_central_set_node_auth( return zts_central_update_member(resp_code, nwid, nodeid, config_data); } -int zts_central_get_members_of_network(int *resp_code, uint64_t nwid) +int zts_central_get_members_of_network(int* resp_code, uint64_t nwid) { char req[64]; sprintf(req, "/api/network/%llx/member", nwid); - return _central_req( - ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL); + return _central_req(ZTS_HTTP_GET, api_url, req, api_token, resp_code, NULL); } -#ifdef __cplusplus -} // extern "C" -#endif + #ifdef __cplusplus +} // extern "C" + #endif -#endif // ZTS_ENABLE_CENTRAL_API -#endif // _H +#endif // ZTS_ENABLE_CENTRAL_API +#endif // _H diff --git a/src/Controls.cpp b/src/Controls.cpp index 689af6c..f487577 100644 --- a/src/Controls.cpp +++ b/src/Controls.cpp @@ -17,21 +17,20 @@ * Node / Network control interface */ +#include "Constants.hpp" +#include "Debug.hpp" +#include "Events.hpp" +#include "Mutex.hpp" +#include "Node.hpp" +#include "NodeService.hpp" +#include "OSUtils.hpp" +#include "Signals.hpp" +#include "VirtualTap.hpp" +#include "ZeroTierSockets.h" + #include #include -#include "Constants.hpp" -#include "Node.hpp" -#include "Mutex.hpp" -#include "OSUtils.hpp" - -#include "ZeroTierSockets.h" -#include "Debug.hpp" -#include "NodeService.hpp" -#include "VirtualTap.hpp" -#include "Events.hpp" -#include "Signals.hpp" - using namespace ZeroTier; #ifdef ZTS_ENABLE_JAVA @@ -39,7 +38,7 @@ using namespace ZeroTier; #endif #ifdef __WINDOWS__ -#include + #include WSADATA wsaData; #endif @@ -47,37 +46,36 @@ WSADATA wsaData; #define ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS 1 #endif -namespace ZeroTier -{ - extern NodeService *service; - extern Mutex serviceLock; +namespace ZeroTier { +extern NodeService* service; +extern Mutex serviceLock; #ifdef ZTS_ENABLE_PYTHON #endif #ifdef ZTS_ENABLE_PINVOKE - extern void (*_userEventCallback)(void *); +extern void (*_userEventCallback)(void*); #endif #ifdef ZTS_C_API_ONLY - extern void (*_userEventCallback)(void *); +extern void (*_userEventCallback)(void*); #endif - extern uint8_t allowNetworkCaching; - extern uint8_t allowPeerCaching; - extern uint8_t allowLocalConf; - extern uint8_t disableLocalStorage; // Off by default +extern uint8_t allowNetworkCaching; +extern uint8_t allowPeerCaching; +extern uint8_t allowLocalConf; +extern uint8_t disableLocalStorage; // Off by default #ifdef ZTS_ENABLE_JAVA - // References to JNI objects and VM kept for future callbacks - JavaVM *jvm = NULL; - jobject objRef = NULL; - jmethodID _userCallbackMethodRef = NULL; +// References to JNI objects and VM kept for future callbacks +JavaVM* jvm = NULL; +jobject objRef = NULL; +jmethodID _userCallbackMethodRef = NULL; #endif - extern uint8_t _serviceStateFlags; -} +extern uint8_t _serviceStateFlags; +} // namespace ZeroTier #ifdef __cplusplus extern "C" { #endif -int zts_generate_orphan_identity(char *key_pair_str, uint16_t *key_buf_len) +int zts_generate_orphan_identity(char* key_pair_str, uint16_t* key_buf_len) { if (*key_buf_len < ZT_IDENTITY_STRING_BUFFER_LENGTH || key_pair_str == NULL) { return ZTS_ERR_ARG; @@ -85,7 +83,7 @@ int zts_generate_orphan_identity(char *key_pair_str, uint16_t *key_buf_len) Identity id; id.generate(); char idtmp[1024]; - std::string idser = id.toString(true,idtmp); + std::string idser = id.toString(true, idtmp); uint16_t key_pair_len = idser.length(); if (key_pair_len > *key_buf_len) { return ZTS_ERR_ARG; @@ -95,7 +93,7 @@ int zts_generate_orphan_identity(char *key_pair_str, uint16_t *key_buf_len) return ZTS_ERR_OK; } -int zts_verify_identity(const char *key_pair_str) +int zts_verify_identity(const char* key_pair_str) { if (key_pair_str == NULL || strlen(key_pair_str) > ZT_IDENTITY_STRING_BUFFER_LENGTH) { return false; @@ -109,13 +107,13 @@ int zts_verify_identity(const char *key_pair_str) return false; } -int zts_get_node_identity(char *key_pair_str, uint16_t *key_buf_len) +int zts_get_node_identity(char* key_pair_str, uint16_t* key_buf_len) { Mutex::Lock _l(serviceLock); if (*key_buf_len == 0 || key_pair_str == NULL) { return ZTS_ERR_ARG; } - if (!service) { + if (! service) { return ZTS_ERR_SERVICE; } service->getIdentity(key_pair_str, key_buf_len); @@ -124,25 +122,34 @@ int zts_get_node_identity(char *key_pair_str, uint16_t *key_buf_len) // TODO: This logic should be further generalized in the next API redesign #ifdef ZTS_ENABLE_PYTHON -int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, - PythonDirectorCallbackClass *callback, uint16_t port) +int zts_start_with_identity( + const char* key_pair_str, + uint16_t key_buf_len, + PythonDirectorCallbackClass* callback, + uint16_t port) #endif #ifdef ZTS_ENABLE_PINVOKE -int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, - CppCallback callback, uint16_t port) + int zts_start_with_identity( + const char* key_pair_str, + uint16_t key_buf_len, + CppCallback callback, + uint16_t port) #endif #ifdef ZTS_C_API_ONLY -int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, - void (*callback)(void *), uint16_t port) + int zts_start_with_identity( + const char* key_pair_str, + uint16_t key_buf_len, + void (*callback)(void*), + uint16_t port) #endif { - if (!zts_verify_identity(key_pair_str)) { + if (! zts_verify_identity(key_pair_str)) { return ZTS_ERR_ARG; } Mutex::Lock _l(serviceLock); #ifdef ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS _install_signal_handlers(); -#endif // ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS +#endif // ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS _lwip_driver_init(); if (service || _getState(ZTS_STATE_NODE_RUNNING)) { // Service is already initialized @@ -154,12 +161,12 @@ int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, return ZTS_ERR_SERVICE; } _userEventCallback = callback; - if (!_isCallbackRegistered()) { + if (! _isCallbackRegistered()) { // Must have a callback return ZTS_ERR_ARG; } - serviceParameters *params = new serviceParameters(); + serviceParameters* params = new serviceParameters(); params->port = port; params->path.clear(); @@ -170,7 +177,7 @@ int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, id.toString(true, params->secretIdentityStr); } } - if (!id) { + if (! id) { delete params; return ZTS_ERR_ARG; } @@ -203,7 +210,7 @@ int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, _clrState(ZTS_STATE_CALLBACKS_RUNNING); _clrState(ZTS_STATE_NODE_RUNNING); _clearRegisteredCallback(); - //delete params; + // delete params; } return retval; } @@ -211,7 +218,7 @@ int zts_start_with_identity(const char *key_pair_str, uint16_t key_buf_len, int zts_allow_network_caching(uint8_t allowed = 1) { Mutex::Lock _l(serviceLock); - if(!service) { + if (! service) { allowNetworkCaching = allowed; return ZTS_ERR_OK; } @@ -221,7 +228,7 @@ int zts_allow_network_caching(uint8_t allowed = 1) int zts_allow_peer_caching(uint8_t allowed = 1) { Mutex::Lock _l(serviceLock); - if(!service) { + if (! service) { allowPeerCaching = allowed; return ZTS_ERR_OK; } @@ -231,7 +238,7 @@ int zts_allow_peer_caching(uint8_t allowed = 1) int zts_allow_local_conf(uint8_t allowed = 1) { Mutex::Lock _l(serviceLock); - if(!service) { + if (! service) { allowLocalConf = allowed; return ZTS_ERR_OK; } @@ -241,7 +248,7 @@ int zts_allow_local_conf(uint8_t allowed = 1) int zts_disable_local_storage(uint8_t disabled) { Mutex::Lock _l(serviceLock); - if(!service) { + if (! service) { disableLocalStorage = disabled; return ZTS_ERR_OK; } @@ -249,19 +256,19 @@ int zts_disable_local_storage(uint8_t disabled) } #ifdef ZTS_ENABLE_PYTHON -int zts_start(const char *path, PythonDirectorCallbackClass *callback, uint16_t port) +int zts_start(const char* path, PythonDirectorCallbackClass* callback, uint16_t port) #endif #ifdef ZTS_ENABLE_PINVOKE -int zts_start(const char *path, CppCallback callback, uint16_t port) + int zts_start(const char* path, CppCallback callback, uint16_t port) #endif #ifdef ZTS_C_API_ONLY -int zts_start(const char *path, void (*callback)(void *), uint16_t port) + int zts_start(const char* path, void (*callback)(void*), uint16_t port) #endif { Mutex::Lock _l(serviceLock); #ifdef ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS _install_signal_handlers(); -#endif // ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS +#endif // ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS _lwip_driver_init(); if (service || _getState(ZTS_STATE_NODE_RUNNING)) { // Service is already initialized @@ -273,14 +280,14 @@ int zts_start(const char *path, void (*callback)(void *), uint16_t port) return ZTS_ERR_SERVICE; } _userEventCallback = callback; - if (!_isCallbackRegistered()) { + if (! _isCallbackRegistered()) { // Must have a callback return ZTS_ERR_ARG; } - if (!path) { + if (! path) { return ZTS_ERR_ARG; } - serviceParameters *params = new serviceParameters(); + serviceParameters* params = new serviceParameters(); params->port = port; params->path = std::string(path); @@ -316,25 +323,30 @@ int zts_start(const char *path, void (*callback)(void *), uint16_t port) _clrState(ZTS_STATE_CALLBACKS_RUNNING); _clrState(ZTS_STATE_NODE_RUNNING); _clearRegisteredCallback(); - //delete params; + // delete params; } return retval; } #ifdef ZTS_ENABLE_JAVA JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_start( - JNIEnv *env, jobject thisObj, jstring path, jobject callback, jint port) + JNIEnv* env, + jobject thisObj, + jstring path, + jobject callback, + jint port) { - if (!path) { + if (! path) { return ZTS_ERR_ARG; } jclass eventListenerClass = env->GetObjectClass(callback); - if(eventListenerClass == NULL) { + if (eventListenerClass == NULL) { DEBUG_ERROR("Couldn't find class for ZeroTierEventListener instance"); return ZTS_ERR_ARG; } - jmethodID eventListenerCallbackMethod = env->GetMethodID(eventListenerClass, "onZeroTierEvent", "(JI)V"); - if(eventListenerCallbackMethod == NULL) { + jmethodID eventListenerCallbackMethod = + env->GetMethodID(eventListenerClass, "onZeroTierEvent", "(JI)V"); + if (eventListenerCallbackMethod == NULL) { DEBUG_ERROR("Couldn't find onZeroTierEvent method"); return ZTS_ERR_ARG; } @@ -342,7 +354,7 @@ JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_start( objRef = env->NewGlobalRef(callback); _userCallbackMethodRef = eventListenerCallbackMethod; const char* utf_string = env->GetStringUTFChars(path, NULL); - if (!utf_string) { + if (! utf_string) { return ZTS_ERR_GENERAL; } // using _userCallbackMethodRef @@ -366,8 +378,7 @@ int zts_stop() return ZTS_ERR_SERVICE; } #ifdef ZTS_ENABLE_JAVA -JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_stop( - JNIEnv *env, jobject thisObj) +JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_stop(JNIEnv* env, jobject thisObj) { zts_stop(); } @@ -414,8 +425,7 @@ int zts_restart() #endif } #ifdef ZTS_ENABLE_JAVA -JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_restart( - JNIEnv *env, jobject thisObj) +JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_restart(JNIEnv* env, jobject thisObj) { zts_restart(); } @@ -423,7 +433,7 @@ JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_restart( int zts_free() { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (_getState(ZTS_STATE_FREE_CALLED)) { @@ -436,8 +446,7 @@ int zts_free() return err; } #ifdef ZTS_ENABLE_JAVA -JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_free( - JNIEnv *env, jobject thisObj) +JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_free(JNIEnv* env, jobject thisObj) { zts_free(); } @@ -448,8 +457,7 @@ JNIEXPORT void JNICALL Java_com_zerotier_libzt_ZeroTier_free( * Called from Java, saves a static reference to the VM so it can be used * later to call a user-specified callback method from C. */ -JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_init( - JNIEnv *env, jobject thisObj) +JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_init(JNIEnv* env, jobject thisObj) { jint rs = env->GetJavaVM(&jvm); return rs != JNI_OK ? ZTS_ERR_GENERAL : ZTS_ERR_OK; @@ -459,7 +467,7 @@ JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_init( int zts_join(const uint64_t networkId) { Mutex::Lock _l(serviceLock); - if (!_canPerformServiceOperation()) { + if (! _canPerformServiceOperation()) { return ZTS_ERR_SERVICE; } else { @@ -468,8 +476,8 @@ int zts_join(const uint64_t networkId) return ZTS_ERR_OK; } #ifdef ZTS_ENABLE_JAVA -JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_join( - JNIEnv *env, jobject thisObj, jlong networkId) +JNIEXPORT jint JNICALL +Java_com_zerotier_libzt_ZeroTier_join(JNIEnv* env, jobject thisObj, jlong networkId) { return zts_join((uint64_t)networkId); } @@ -478,7 +486,7 @@ JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_join( int zts_leave(const uint64_t networkId) { Mutex::Lock _l(serviceLock); - if (!_canPerformServiceOperation()) { + if (! _canPerformServiceOperation()) { return ZTS_ERR_SERVICE; } else { @@ -487,8 +495,8 @@ int zts_leave(const uint64_t networkId) return ZTS_ERR_OK; } #ifdef ZTS_ENABLE_JAVA -JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_leave( - JNIEnv *env, jobject thisObj, jlong networkId) +JNIEXPORT jint JNICALL +Java_com_zerotier_libzt_ZeroTier_leave(JNIEnv* env, jobject thisObj, jlong networkId) { return zts_leave((uint64_t)networkId); } @@ -497,10 +505,11 @@ JNIEXPORT jint JNICALL Java_com_zerotier_libzt_ZeroTier_leave( int zts_orbit(uint64_t moonWorldId, uint64_t moonSeed) { Mutex::Lock _l(serviceLock); - void *tptr = NULL; - if (!_canPerformServiceOperation()) { + void* tptr = NULL; + if (! _canPerformServiceOperation()) { return ZTS_ERR_SERVICE; - } else { + } + else { service->getNode()->orbit(tptr, moonWorldId, moonSeed); } return ZTS_ERR_OK; @@ -511,10 +520,11 @@ int zts_orbit(uint64_t moonWorldId, uint64_t moonSeed) int zts_deorbit(uint64_t moonWorldId) { Mutex::Lock _l(serviceLock); - void *tptr = NULL; - if (!_canPerformServiceOperation()) { + void* tptr = NULL; + if (! _canPerformServiceOperation()) { return ZTS_ERR_SERVICE; - } else { + } + else { service->getNode()->deorbit(tptr, moonWorldId); } return ZTS_ERR_OK; @@ -522,24 +532,30 @@ int zts_deorbit(uint64_t moonWorldId) #ifdef ZTS_ENABLE_JAVA #endif -int zts_get_6plane_addr(struct zts_sockaddr_storage *addr, const uint64_t networkId, const uint64_t nodeId) +int zts_get_6plane_addr( + struct zts_sockaddr_storage* addr, + const uint64_t networkId, + const uint64_t nodeId) { - if (!addr || !networkId || !nodeId) { + if (! addr || ! networkId || ! nodeId) { return ZTS_ERR_ARG; } - InetAddress _6planeAddr = InetAddress::makeIpv66plane(networkId,nodeId); - struct sockaddr_in6 *in6 = (struct sockaddr_in6*)addr; + InetAddress _6planeAddr = InetAddress::makeIpv66plane(networkId, nodeId); + struct sockaddr_in6* in6 = (struct sockaddr_in6*)addr; memcpy(in6->sin6_addr.s6_addr, _6planeAddr.rawIpData(), sizeof(struct in6_addr)); 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; } - InetAddress _rfc4193Addr = InetAddress::makeIpv6rfc4193(networkId,nodeId); - struct sockaddr_in6 *in6 = (struct sockaddr_in6*)addr; + InetAddress _rfc4193Addr = InetAddress::makeIpv6rfc4193(networkId, nodeId); + struct sockaddr_in6* in6 = (struct sockaddr_in6*)addr; memcpy(in6->sin6_addr.s6_addr, _rfc4193Addr.rawIpData(), sizeof(struct in6_addr)); return ZTS_ERR_OK; } @@ -552,11 +568,11 @@ uint64_t zts_generate_adhoc_nwid_from_range(uint16_t startPortOfRange, uint16_t } #ifdef __WINDOWS__ -#include + #include #elif _POSIX_C_SOURCE >= 199309L -#include // for nanosleep + #include // for nanosleep #else -#include // for usleep + #include // for usleep #endif void zts_delay_ms(long milliseconds) diff --git a/src/Debug.hpp b/src/Debug.hpp index 3a1a769..73e4617 100644 --- a/src/Debug.hpp +++ b/src/Debug.hpp @@ -25,24 +25,26 @@ ////////////////////////////////////////////////////////////////////////////// #if defined(__linux__) || defined(__APPLE__) -#include -#include -#include + #include + #include + #include #endif #include -#define ZT_MSG_ERROR true // Errors -#define ZT_MSG_INFO true // Information which is generally useful to any developer -#define ZT_MSG_TEST true // For use in selftest -#define ZT_MSG_TRANSFER true // RX/TX specific statements +#define ZT_MSG_ERROR true // Errors +#define ZT_MSG_INFO true // Information which is generally useful to any developer +#define ZT_MSG_TEST true // For use in selftest +#define ZT_MSG_TRANSFER true // RX/TX specific statements -#define ZT_COLOR true +#define ZT_COLOR true // Debug output colors #if defined(__APPLE__) - #include "TargetConditionals.h" + #include "TargetConditionals.h" #endif -#if defined(ZT_COLOR) && !defined(_WIN32) && !defined(__ANDROID__) && !defined(TARGET_OS_IPHONE) && !defined(TARGET_IPHONE_SIMULATOR) && !defined(__APP_FRAMEWORK__) +#if defined(ZT_COLOR) && ! defined(_WIN32) && ! defined(__ANDROID__) \ + && ! defined(TARGET_OS_IPHONE) && ! defined(TARGET_IPHONE_SIMULATOR) \ + && ! defined(__APP_FRAMEWORK__) #define ZT_RED "\x1B[31m" #define ZT_GRN "\x1B[32m" #define ZT_YEL "\x1B[33m" @@ -62,28 +64,47 @@ #define ZT_RESET #endif -#define ZT_FILENAME (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) // short +#define ZT_FILENAME (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) // short #if defined(__JNI_LIB__) - #include + #include #endif #if defined(__ANDROID__) - #include - #define ZT_LOG_TAG "ZTSDK" + #include + #define ZT_LOG_TAG "ZTSDK" #endif #if defined(LIBZT_DEBUG) || defined(LIBZT_TRACE) || defined(__NATIVETEST__) // #if ZT_MSG_ERROR == true #if defined(__ANDROID__) - #define DEBUG_ERROR(fmt, args...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, ZT_LOG_TAG, \ - "%17s:%5d:%20s: " fmt "\n", ZT_FILENAME, __LINE__, __FUNCTION__, ##args)) + #define DEBUG_ERROR(fmt, args...) \ + ((void)__android_log_print( \ + ANDROID_LOG_VERBOSE, \ + ZT_LOG_TAG, \ + "%17s:%5d:%20s: " fmt "\n", \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + ##args)) #elif defined(_WIN32) - #define DEBUG_ERROR(fmt, ...) fprintf(stderr, ZT_RED "%17s:%5d:%25s: " fmt "\n" \ - ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, __VA_ARGS__) + #define DEBUG_ERROR(fmt, ...) \ + fprintf( \ + stderr, \ + ZT_RED "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + __VA_ARGS__) #else - #define DEBUG_ERROR(fmt, args ...) fprintf(stderr, ZT_RED "%17s:%5d:%25s: " fmt "\n" \ - ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args) + #define DEBUG_ERROR(fmt, args...) \ + fprintf( \ + stderr, \ + ZT_RED "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + ##args) #endif #else #define DEBUG_ERROR(fmt, args...) @@ -92,14 +113,33 @@ // #if ZT_MSG_TEST == true #if defined(__ANDROID__) - #define DEBUG_TEST(fmt, args...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, ZT_LOG_TAG, \ - "%17s:%5d:%25s: " fmt "\n", ZT_FILENAME, __LINE__, __FUNCTION__, ##args)) + #define DEBUG_TEST(fmt, args...) \ + ((void)__android_log_print( \ + ANDROID_LOG_VERBOSE, \ + ZT_LOG_TAG, \ + "%17s:%5d:%25s: " fmt "\n", \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + ##args)) #elif defined(_WIN32) - #define DEBUG_TEST(fmt, ...) fprintf(stderr, ZT_CYN "%17s:%5d:%25s: " fmt "\n" \ - ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, __VA_ARGS__) + #define DEBUG_TEST(fmt, ...) \ + fprintf( \ + stderr, \ + ZT_CYN "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + __VA_ARGS__) #else - #define DEBUG_TEST(fmt, args ...) fprintf(stderr, ZT_CYN "%17s:%5d:%25s: " fmt "\n" \ - ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args) + #define DEBUG_TEST(fmt, args...) \ + fprintf( \ + stderr, \ + ZT_CYN "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + ##args) #endif #else #define DEBUG_TEST(fmt, args...) @@ -108,14 +148,33 @@ // #if ZT_MSG_INFO == true #if defined(__ANDROID__) - #define DEBUG_INFO(fmt, args...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, ZT_LOG_TAG, \ - "%17s:%5d:%20s: " fmt "\n", ZT_FILENAME, __LINE__, __FUNCTION__, ##args)) + #define DEBUG_INFO(fmt, args...) \ + ((void)__android_log_print( \ + ANDROID_LOG_VERBOSE, \ + ZT_LOG_TAG, \ + "%17s:%5d:%20s: " fmt "\n", \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + ##args)) #elif defined(_WIN32) - #define DEBUG_INFO(fmt, ...) fprintf(stderr, ZT_WHT "%17s:%5d:%25s: " fmt "\n" \ - ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, __VA_ARGS__) + #define DEBUG_INFO(fmt, ...) \ + fprintf( \ + stderr, \ + ZT_WHT "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + __VA_ARGS__) #else - #define DEBUG_INFO(fmt, args ...) fprintf(stderr, ZT_WHT "%17s:%5d:%25s: " fmt "\n" \ - ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args) + #define DEBUG_INFO(fmt, args...) \ + fprintf( \ + stderr, \ + ZT_WHT "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + ##args) #endif #else #define DEBUG_INFO(fmt, args...) @@ -124,19 +183,38 @@ // #if ZT_MSG_TRANSFER == true #if defined(__ANDROID__) - #define DEBUG_TRANS(fmt, args...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, ZT_LOG_TAG, \ - "%17s:%5d:%25s: " fmt "\n", ZT_FILENAME, __LINE__, __FUNCTION__, ##args)) + #define DEBUG_TRANS(fmt, args...) \ + ((void)__android_log_print( \ + ANDROID_LOG_VERBOSE, \ + ZT_LOG_TAG, \ + "%17s:%5d:%25s: " fmt "\n", \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + ##args)) #elif defined(_WIN32) - #define DEBUG_TRANS(fmt, ...) fprintf(stderr, ZT_GRN "%17s:%5d:%25s: " fmt "\n" \ - ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, __VA_ARGS__) + #define DEBUG_TRANS(fmt, ...) \ + fprintf( \ + stderr, \ + ZT_GRN "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + __VA_ARGS__) #else - #define DEBUG_TRANS(fmt, args ...) fprintf(stderr, ZT_GRN "%17s:%5d:%25s: " fmt "\n" \ - ZT_RESET, ZT_FILENAME, __LINE__, __FUNCTION__, ##args) + #define DEBUG_TRANS(fmt, args...) \ + fprintf( \ + stderr, \ + ZT_GRN "%17s:%5d:%25s: " fmt "\n" ZT_RESET, \ + ZT_FILENAME, \ + __LINE__, \ + __FUNCTION__, \ + ##args) #endif #else #define DEBUG_TRANS(fmt, args...) #endif -#else // !LIBZT_DEBUG || !__NATIVE_TEST__ +#else // !LIBZT_DEBUG || !__NATIVE_TEST__ #if defined(_WIN32) #define DEBUG_ERROR(...) #define DEBUG_TEST(...) @@ -150,4 +228,4 @@ #endif #endif -#endif // _H \ No newline at end of file +#endif // _H \ No newline at end of file diff --git a/src/Events.cpp b/src/Events.cpp index 6d1dd50..b7bd132 100644 --- a/src/Events.cpp +++ b/src/Events.cpp @@ -24,31 +24,33 @@ #endif #include "Constants.hpp" -#include "Node.hpp" -#include "OSUtils.hpp" - #include "Debug.hpp" #include "Events.hpp" -#include "ZeroTierSockets.h" +#include "Node.hpp" #include "NodeService.hpp" +#include "OSUtils.hpp" +#include "ZeroTierSockets.h" -#define NODE_EVENT_TYPE(code) code >= ZTS_EVENT_NODE_UP && code <= ZTS_EVENT_NODE_NORMAL_TERMINATION -#define NETWORK_EVENT_TYPE(code) code >= ZTS_EVENT_NETWORK_NOT_FOUND && code <= ZTS_EVENT_NETWORK_UPDATE -#define STACK_EVENT_TYPE(code) code >= ZTS_EVENT_STACK_UP && code <= ZTS_EVENT_STACK_DOWN -#define NETIF_EVENT_TYPE(code) code >= ZTS_EVENT_NETIF_UP && code <= ZTS_EVENT_NETIF_LINK_DOWN -#define PEER_EVENT_TYPE(code) code >= ZTS_EVENT_PEER_DIRECT && code <= ZTS_EVENT_PEER_PATH_DEAD -#define ROUTE_EVENT_TYPE(code) code >= ZTS_EVENT_ROUTE_ADDED && code <= ZTS_EVENT_ROUTE_REMOVED -#define ADDR_EVENT_TYPE(code) code >= ZTS_EVENT_ADDR_ADDED_IP4 && code <= ZTS_EVENT_ADDR_REMOVED_IP6 +#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 STACK_EVENT_TYPE(code) code >= ZTS_EVENT_STACK_UP&& code <= ZTS_EVENT_STACK_DOWN +#define NETIF_EVENT_TYPE(code) code >= ZTS_EVENT_NETIF_UP&& code <= ZTS_EVENT_NETIF_LINK_DOWN +#define PEER_EVENT_TYPE(code) code >= ZTS_EVENT_PEER_DIRECT&& code <= ZTS_EVENT_PEER_PATH_DEAD +#define ROUTE_EVENT_TYPE(code) code >= ZTS_EVENT_ROUTE_ADDED&& code <= ZTS_EVENT_ROUTE_REMOVED +#define ADDR_EVENT_TYPE(code) code >= ZTS_EVENT_ADDR_ADDED_IP4&& code <= ZTS_EVENT_ADDR_REMOVED_IP6 #ifdef ZTS_ENABLE_PYTHON #include "Python.h" - PythonDirectorCallbackClass *_userEventCallback = NULL; - void PythonDirectorCallbackClass::on_zerotier_event(struct zts_callback_msg *msg) { } +PythonDirectorCallbackClass* _userEventCallback = NULL; +void PythonDirectorCallbackClass::on_zerotier_event(struct zts_callback_msg* msg) +{ +} #endif namespace ZeroTier { -extern NodeService *service; +extern NodeService* service; // Global state variable shared between Socket, Control, Event and NodeService logic. uint8_t _serviceStateFlags; @@ -57,32 +59,38 @@ uint8_t _serviceStateFlags; Mutex _callbackLock; #ifdef ZTS_ENABLE_PINVOKE - void (*_userEventCallback)(void *); +void (*_userEventCallback)(void*); #endif #ifdef ZTS_C_API_ONLY - void (*_userEventCallback)(void *); +void (*_userEventCallback)(void*); #endif moodycamel::ConcurrentQueue _callbackMsgQueue; -void _enqueueEvent(int16_t eventCode, void *arg) +void _enqueueEvent(int16_t eventCode, void* arg) { - struct zts_callback_msg *msg = new zts_callback_msg(); + struct zts_callback_msg* msg = new zts_callback_msg(); msg->eventCode = eventCode; if (NODE_EVENT_TYPE(eventCode)) { msg->node = (struct zts_node_details*)arg; - } if (NETWORK_EVENT_TYPE(eventCode)) { + } + if (NETWORK_EVENT_TYPE(eventCode)) { msg->network = (struct zts_network_details*)arg; - } if (STACK_EVENT_TYPE(eventCode)) { + } + if (STACK_EVENT_TYPE(eventCode)) { /* nothing to convey to user */ - } if (NETIF_EVENT_TYPE(eventCode)) { + } + if (NETIF_EVENT_TYPE(eventCode)) { msg->netif = (struct zts_netif_details*)arg; - } if (ROUTE_EVENT_TYPE(eventCode)) { + } + if (ROUTE_EVENT_TYPE(eventCode)) { msg->route = (struct zts_virtual_network_route*)arg; - } if (PEER_EVENT_TYPE(eventCode)) { + } + if (PEER_EVENT_TYPE(eventCode)) { msg->peer = (struct zts_peer_details*)arg; - } if (ADDR_EVENT_TYPE(eventCode)) { + } + if (ADDR_EVENT_TYPE(eventCode)) { msg->addr = (struct zts_addr_details*)arg; } @@ -95,20 +103,32 @@ void _enqueueEvent(int16_t eventCode, void *arg) } } -void _freeEvent(struct zts_callback_msg *msg) +void _freeEvent(struct zts_callback_msg* msg) { - if (!msg) { + if (! msg) { return; } - if (msg->node) { delete msg->node; } - if (msg->network) { delete msg->network; } - if (msg->netif) { delete msg->netif; } - if (msg->route) { delete msg->route; } - if (msg->peer) { delete msg->peer; } - if (msg->addr) { delete msg->addr; } + if (msg->node) { + delete msg->node; + } + if (msg->network) { + delete msg->network; + } + if (msg->netif) { + delete msg->netif; + } + if (msg->route) { + delete msg->route; + } + if (msg->peer) { + delete msg->peer; + } + if (msg->addr) { + delete msg->addr; + } } -void _passDequeuedEventToUser(struct zts_callback_msg *msg) +void _passDequeuedEventToUser(struct zts_callback_msg* msg) { bool bShouldStopCallbackThread = (msg->eventCode == ZTS_EVENT_STACK_DOWN); #ifdef ZTS_ENABLE_PYTHON @@ -117,14 +137,14 @@ void _passDequeuedEventToUser(struct zts_callback_msg *msg) PyGILState_Release(state); #endif #ifdef ZTS_ENABLE_JAVA - if(_userCallbackMethodRef) { - JNIEnv *env; + if (_userCallbackMethodRef) { + JNIEnv* env; #if defined(__ANDROID__) jint rs = jvm->AttachCurrentThread(&env, NULL); #else - jint rs = jvm->AttachCurrentThread((void **)&env, NULL); + jint rs = jvm->AttachCurrentThread((void**)&env, NULL); #endif - assert (rs == JNI_OK); + assert(rs == JNI_OK); uint64_t arg = 0; uint64_t id = 0; if (NODE_EVENT_TYPE(msg->eventCode)) { @@ -138,7 +158,7 @@ void _passDequeuedEventToUser(struct zts_callback_msg *msg) } env->CallVoidMethod(objRef, _userCallbackMethodRef, id, msg->eventCode); } -#endif // ZTS_ENABLE_JAVA +#endif // ZTS_ENABLE_JAVA #ifdef ZTS_ENABLE_PINVOKE if (_userEventCallback) { _userEventCallback(msg); @@ -175,7 +195,7 @@ void _clearRegisteredCallback() _callbackLock.lock(); #ifdef ZTS_ENABLE_JAVA objRef = NULL; - _userCallbackMethodRef = NULL; + _userCallbackMethodRef = NULL; #else _userEventCallback = NULL; #endif @@ -184,28 +204,23 @@ void _clearRegisteredCallback() int _canPerformServiceOperation() { - return service - && service->isRunning() - && service->getNode() - && service->getNode()->online() - && !_getState(ZTS_STATE_FREE_CALLED); + return service && service->isRunning() && service->getNode() && service->getNode()->online() + && ! _getState(ZTS_STATE_FREE_CALLED); } -#define RESET_FLAGS( ) _serviceStateFlags = 0; -#define SET_FLAGS(f) _serviceStateFlags |= f; -#define CLR_FLAGS(f) _serviceStateFlags &= ~f; -#define GET_FLAGS(f) ((_serviceStateFlags & f) > 0) +#define RESET_FLAGS() _serviceStateFlags = 0; +#define SET_FLAGS(f) _serviceStateFlags |= f; +#define CLR_FLAGS(f) _serviceStateFlags &= ~f; +#define GET_FLAGS(f) ((_serviceStateFlags & f) > 0) void _setState(uint8_t newFlags) { if ((newFlags ^ _serviceStateFlags) & ZTS_STATE_NET_SERVICE_RUNNING) { - return; // No effect. Not allowed to set this flag manually + return; // No effect. Not allowed to set this flag manually } SET_FLAGS(newFlags); - if ( GET_FLAGS(ZTS_STATE_NODE_RUNNING) - && GET_FLAGS(ZTS_STATE_STACK_RUNNING) - && !(GET_FLAGS(ZTS_STATE_FREE_CALLED))) - { + if (GET_FLAGS(ZTS_STATE_NODE_RUNNING) && GET_FLAGS(ZTS_STATE_STACK_RUNNING) + && ! (GET_FLAGS(ZTS_STATE_FREE_CALLED))) { SET_FLAGS(ZTS_STATE_NET_SERVICE_RUNNING); } else { @@ -216,13 +231,11 @@ void _setState(uint8_t newFlags) void _clrState(uint8_t newFlags) { if (newFlags & ZTS_STATE_NET_SERVICE_RUNNING) { - return; // No effect. Not allowed to set this flag manually + return; // No effect. Not allowed to set this flag manually } CLR_FLAGS(newFlags); - if ( GET_FLAGS(ZTS_STATE_NODE_RUNNING) - && GET_FLAGS(ZTS_STATE_STACK_RUNNING) - && !(GET_FLAGS(ZTS_STATE_FREE_CALLED))) - { + if (GET_FLAGS(ZTS_STATE_NODE_RUNNING) && GET_FLAGS(ZTS_STATE_STACK_RUNNING) + && ! (GET_FLAGS(ZTS_STATE_FREE_CALLED))) { SET_FLAGS(ZTS_STATE_NET_SERVICE_RUNNING); } else { @@ -238,15 +251,14 @@ bool _getState(uint8_t testFlags) #if defined(__WINDOWS__) DWORD WINAPI _runCallbacks(LPVOID thread_id) #else -void *_runCallbacks(void *thread_id) +void* _runCallbacks(void* thread_id) #endif { #if defined(__APPLE__) pthread_setname_np(ZTS_EVENT_CALLBACK_THREAD_NAME); #endif - while (_getState(ZTS_STATE_CALLBACKS_RUNNING) || _callbackMsgQueue.size_approx() > 0) - { - struct zts_callback_msg *msg; + while (_getState(ZTS_STATE_CALLBACKS_RUNNING) || _callbackMsgQueue.size_approx() > 0) { + struct zts_callback_msg* msg; size_t sz = _callbackMsgQueue.size_approx(); for (size_t j = 0; j < sz; j++) { if (_callbackMsgQueue.try_dequeue(msg)) { @@ -256,14 +268,14 @@ void *_runCallbacks(void *thread_id) delete msg; } } - zts_delay_ms(ZTS_CALLBACK_PROCESSING_INTERVAL); - } + zts_delay_ms(ZTS_CALLBACK_PROCESSING_INTERVAL); + } #if ZTS_ENABLE_JAVA - JNIEnv *env; + JNIEnv* env; jint rs = jvm->DetachCurrentThread(); - pthread_exit(0); + pthread_exit(0); #endif return NULL; } -} // namespace ZeroTier +} // namespace ZeroTier diff --git a/src/Events.hpp b/src/Events.hpp index a0c07ad..ac6f18f 100644 --- a/src/Events.hpp +++ b/src/Events.hpp @@ -20,13 +20,13 @@ #ifndef ZT_EVENTS_HPP #define ZT_EVENTS_HPP -#include - #include "Constants.hpp" #include "ZeroTierSockets.h" +#include + #ifdef __WINDOWS__ -#include + #include #endif #ifdef ZTS_ENABLE_JAVA @@ -34,17 +34,17 @@ #endif namespace ZeroTier { -#define ZTS_STATE_NODE_RUNNING 0x01 -#define ZTS_STATE_STACK_RUNNING 0x02 -#define ZTS_STATE_NET_SERVICE_RUNNING 0x04 -#define ZTS_STATE_CALLBACKS_RUNNING 0x08 -#define ZTS_STATE_FREE_CALLED 0x10 +#define ZTS_STATE_NODE_RUNNING 0x01 +#define ZTS_STATE_STACK_RUNNING 0x02 +#define ZTS_STATE_NET_SERVICE_RUNNING 0x04 +#define ZTS_STATE_CALLBACKS_RUNNING 0x08 +#define ZTS_STATE_FREE_CALLED 0x10 #ifdef ZTS_ENABLE_JAVA - // References to JNI objects and VM kept for future callbacks - extern JavaVM *jvm; - extern jobject objRef; - extern jmethodID _userCallbackMethodRef; +// References to JNI objects and VM kept for future callbacks +extern JavaVM* jvm; +extern jobject objRef; +extern jmethodID _userCallbackMethodRef; #endif /** @@ -55,17 +55,17 @@ namespace ZeroTier { /** * Enqueue an event to be sent to the user application */ -void _enqueueEvent(int16_t eventCode, void *arg); +void _enqueueEvent(int16_t eventCode, void* arg); /** * Send callback message to user application */ -void _passDequeuedEventToUser(struct ::zts_callback_msg *msg); +void _passDequeuedEventToUser(struct ::zts_callback_msg* msg); /** * Free memory occupied by callback structures */ -void _freeEvent(struct ::zts_callback_msg *msg); +void _freeEvent(struct ::zts_callback_msg* msg); /** * Return whether a callback method has been set @@ -103,9 +103,9 @@ DWORD WINAPI _runCallbacks(LPVOID thread_id); /** * Event callback thread */ -void *_runCallbacks(void *thread_id); +void* _runCallbacks(void* thread_id); #endif -} // namespace ZeroTier +} // namespace ZeroTier -#endif // _H \ No newline at end of file +#endif // _H \ No newline at end of file diff --git a/src/NodeService.cpp b/src/NodeService.cpp index 8a9dfde..debcd76 100644 --- a/src/NodeService.cpp +++ b/src/NodeService.cpp @@ -17,42 +17,41 @@ * ZeroTier Node Service (a distant relative of OneService) */ -#include -#include +#include "NodeService.hpp" #include "../version.h" - +#include "Binder.hpp" +#include "BlockingQueue.hpp" +#include "Constants.hpp" #include "Debug.hpp" #include "Events.hpp" -#include "NodeService.hpp" -#include "ZeroTierSockets.h" -#include "VirtualTap.hpp" - -#include "Constants.hpp" -#include "Node.hpp" -#include "Utils.hpp" -#include "MAC.hpp" -#include "Phy.hpp" -#include "Thread.hpp" -#include "OSUtils.hpp" -#include "PortMapper.hpp" -#include "Binder.hpp" -#include "ManagedRoute.hpp" #include "InetAddress.hpp" -#include "BlockingQueue.hpp" +#include "MAC.hpp" +#include "ManagedRoute.hpp" +#include "Node.hpp" +#include "OSUtils.hpp" +#include "Phy.hpp" +#include "PortMapper.hpp" +#include "Thread.hpp" +#include "Utils.hpp" +#include "VirtualTap.hpp" +#include "ZeroTierSockets.h" + +#include +#include #if defined(__WINDOWS__) -//WSADATA wsaData; -#include -#include -#include -#include -#include -#define stat _stat + // WSADATA wsaData; + #include + #include + #include + #include + #include + #define stat _stat #endif #ifdef ZTS_ENABLE_JAVA -#include + #include #endif // Custom errno-like reporting variable @@ -63,24 +62,89 @@ namespace ZeroTier { uint8_t allowNetworkCaching; uint8_t allowPeerCaching; uint8_t allowLocalConf; -uint8_t disableLocalStorage; // Off by default +uint8_t disableLocalStorage; // Off by default typedef VirtualTap EthernetTap; class NodeServiceImpl; -static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf); -static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData); -static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len); -static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen); -static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl); -static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len); -static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket,const struct sockaddr_storage *remoteAddr); -static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result); -static void StapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len); +static int SnodeVirtualNetworkConfigFunction( + ZT_Node* node, + void* uptr, + void* tptr, + uint64_t nwid, + void** nuptr, + enum ZT_VirtualNetworkConfigOperation op, + const ZT_VirtualNetworkConfig* nwconf); +static void SnodeEventCallback( + ZT_Node* node, + void* uptr, + void* tptr, + enum ZT_Event event, + const void* metaData); +static void SnodeStatePutFunction( + ZT_Node* node, + void* uptr, + void* tptr, + enum ZT_StateObjectType type, + const uint64_t id[2], + const void* data, + int len); +static int SnodeStateGetFunction( + ZT_Node* node, + void* uptr, + void* tptr, + enum ZT_StateObjectType type, + const uint64_t id[2], + void* data, + unsigned int maxlen); +static int SnodeWirePacketSendFunction( + ZT_Node* node, + void* uptr, + void* tptr, + int64_t localSocket, + const struct sockaddr_storage* addr, + const void* data, + unsigned int len, + unsigned int ttl); +static void SnodeVirtualNetworkFrameFunction( + ZT_Node* node, + void* uptr, + void* tptr, + uint64_t nwid, + void** nuptr, + uint64_t sourceMac, + uint64_t destMac, + unsigned int etherType, + unsigned int vlanId, + const void* data, + unsigned int len); +static int SnodePathCheckFunction( + ZT_Node* node, + void* uptr, + void* tptr, + uint64_t ztaddr, + int64_t localSocket, + const struct sockaddr_storage* remoteAddr); +static int SnodePathLookupFunction( + ZT_Node* node, + void* uptr, + void* tptr, + uint64_t ztaddr, + int family, + struct sockaddr_storage* result); +static void StapFrameHandler( + void* uptr, + void* tptr, + uint64_t nwid, + const MAC& from, + const MAC& to, + unsigned int etherType, + unsigned int vlanId, + const void* data, + unsigned int len); -struct NodeServiceIncomingPacket -{ +struct NodeServiceIncomingPacket { uint64_t now; int64_t sock; struct sockaddr_storage from; @@ -88,17 +152,16 @@ struct NodeServiceIncomingPacket uint8_t data[ZT_MAX_MTU]; }; -class NodeServiceImpl : public NodeService -{ -public: +class NodeServiceImpl : public NodeService { + public: // begin member variables -------------------------------------------------- const std::string _homePath; const std::string _networksPath; const std::string _moonsPath; - Phy _phy; - Node *_node; + Phy _phy; + Node* _node; bool _updateAutoApply; unsigned int _multipathMode = 0; unsigned int _primaryPort = 0; @@ -111,20 +174,20 @@ public: // unsigned long _incomingPacketConcurrency; - std::vector _incomingPacketMemoryPool; - BlockingQueue _incomingPacketQueue; + std::vector _incomingPacketMemoryPool; + BlockingQueue _incomingPacketQueue; std::vector _incomingPacketThreads; - Mutex _incomingPacketMemoryPoolLock,_incomingPacketThreadsLock; + Mutex _incomingPacketMemoryPoolLock, _incomingPacketThreadsLock; // Local configuration and memo-ized information from it - Hashtable< uint64_t,std::vector > _v4Hints; - Hashtable< uint64_t,std::vector > _v6Hints; - Hashtable< uint64_t,std::vector > _v4Blacklists; - Hashtable< uint64_t,std::vector > _v6Blacklists; - std::vector< InetAddress > _globalV4Blacklist; - std::vector< InetAddress > _globalV6Blacklist; - std::vector< InetAddress > _allowManagementFrom; - std::vector< std::string > _interfacePrefixBlacklist; + Hashtable > _v4Hints; + Hashtable > _v6Hints; + Hashtable > _v4Blacklists; + Hashtable > _v6Blacklists; + std::vector _globalV4Blacklist; + std::vector _globalV6Blacklist; + std::vector _allowManagementFrom; + std::vector _interfacePrefixBlacklist; Mutex _localConfig_m; std::vector explicitBind; @@ -153,10 +216,8 @@ public: volatile int64_t _nextBackgroundTaskDeadline; // Configured networks - struct NetworkState - { - NetworkState() : - tap((EthernetTap *)0) + struct NetworkState { + NetworkState() : tap((EthernetTap*)0) { // Real defaults are in network 'up' code in network event handler settings.allowManaged = true; @@ -164,13 +225,13 @@ public: settings.allowDefault = false; } - EthernetTap *tap; - ZT_VirtualNetworkConfig config; // memcpy() of raw config from core + EthernetTap* tap; + ZT_VirtualNetworkConfig config; // memcpy() of raw config from core std::vector managedIps; - std::list< SharedPtr > managedRoutes; + std::list > managedRoutes; NetworkSettings settings; }; - std::map _nets; + std::map _nets; Mutex _nets_m; // Termination status information @@ -179,9 +240,9 @@ public: Mutex _termReason_m; // uPnP/NAT-PMP port mapper if enabled - bool _portMappingEnabled; // local.conf settings + bool _portMappingEnabled; // local.conf settings #ifdef ZT_USE_MINIUPNPC - PortMapper *_portMapper; + PortMapper* _portMapper; #endif // Set to false to force service to stop @@ -190,22 +251,22 @@ public: // end member variables ---------------------------------------------------- - NodeServiceImpl(const char *hp,unsigned int port) : - _homePath((hp) ? hp : ".") - ,_phy(this,false,true) - ,_node((Node *)0) - ,_updateAutoApply(false) - ,_primaryPort(port) - ,_udpPortPickerCounter(0) - ,_lastDirectReceiveFromGlobal(0) - ,_lastRestart(0) - ,_nextBackgroundTaskDeadline(0) - ,_termReason(ONE_STILL_RUNNING) - ,_portMappingEnabled(true) + NodeServiceImpl(const char* hp, unsigned int port) + : _homePath((hp) ? hp : ".") + , _phy(this, false, true) + , _node((Node*)0) + , _updateAutoApply(false) + , _primaryPort(port) + , _udpPortPickerCounter(0) + , _lastDirectReceiveFromGlobal(0) + , _lastRestart(0) + , _nextBackgroundTaskDeadline(0) + , _termReason(ONE_STILL_RUNNING) + , _portMappingEnabled(true) #ifdef ZT_USE_MINIUPNPC - ,_portMapper((PortMapper *)0) + , _portMapper((PortMapper*)0) #endif - ,_run(true) + , _run(true) { _ports[0] = 0; _ports[1] = 0; @@ -216,14 +277,14 @@ public: { _incomingPacketQueue.stop(); _incomingPacketThreadsLock.lock(); - for(auto t=_incomingPacketThreads.begin();t!=_incomingPacketThreads.end();++t) + for (auto t = _incomingPacketThreads.begin(); t != _incomingPacketThreads.end(); ++t) t->join(); _incomingPacketThreadsLock.unlock(); _binder.closeAll(_phy); _incomingPacketMemoryPoolLock.lock(); - while (!_incomingPacketMemoryPool.empty()) { + while (! _incomingPacketMemoryPool.empty()) { delete _incomingPacketMemoryPool.back(); _incomingPacketMemoryPool.pop_back(); } @@ -248,20 +309,21 @@ public: cb.eventCallback = SnodeEventCallback; cb.pathCheckFunction = SnodePathCheckFunction; cb.pathLookupFunction = SnodePathLookupFunction; - _node = new Node(this,(void *)0,&cb,OSUtils::now()); + _node = new Node(this, (void*)0, &cb, OSUtils::now()); } // Make sure we can use the primary port, and hunt for one if configured to do so - const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random - for(int k=0;kaddress() % 45500) : _secondaryPort; - for(int i=0;;++i) { + _ports[1] = (_secondaryPort == 0) ? 20000 + ((unsigned int)_node->address() % 45500) + : _secondaryPort; + for (int i = 0;; ++i) { if (i > 1000) { _ports[1] = 0; break; - } else if (++_ports[1] >= 65536) { + } + else if (++_ports[1] >= 65536) { _ports[1] = 20000; } if (_trialBind(_ports[1])) @@ -295,11 +359,12 @@ public: // stuff with ports that are explicitly mapped that breaks things. if (_ports[1]) { _ports[2] = (_tertiaryPort == 0) ? _ports[1] : _tertiaryPort; - for(int i=0;;++i) { + for (int i = 0;; ++i) { if (i > 1000) { _ports[2] = 0; break; - } else if (++_ports[2] >= 65536) { + } + else if (++_ports[2] >= 65536) { _ports[2] = 20000; } if (_trialBind(_ports[2])) @@ -307,19 +372,30 @@ public: } if (_ports[2]) { char uniqueName[64]; - OSUtils::ztsnprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]); - _portMapper = new PortMapper(_ports[2],uniqueName); + OSUtils::ztsnprintf( + uniqueName, + sizeof(uniqueName), + "ZeroTier/%.10llx@%u", + _node->address(), + _ports[2]); + _portMapper = new PortMapper(_ports[2], uniqueName); } } } #endif // Join existing networks in networks.d if (allowNetworkCaching) { - std::vector networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str())); - for(std::vector::iterator f(networksDotD.begin());f!=networksDotD.end();++f) { + std::vector networksDotD( + OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str())); + for (std::vector::iterator f(networksDotD.begin()); + f != networksDotD.end(); + ++f) { std::size_t dot = f->find_last_of('.'); - if ((dot == 16)&&(f->substr(16) == ".conf")) - _node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0,(void *)0); + if ((dot == 16) && (f->substr(16) == ".conf")) + _node->join( + Utils::hexStrToU64(f->substr(0, dot).c_str()), + (void*)0, + (void*)0); } } // Main I/O loop @@ -330,16 +406,20 @@ public: int64_t lastBindRefresh = 0; int64_t lastMultipathModeUpdate = 0; int64_t lastCleanedPeersDb = 0; - int64_t lastLocalInterfaceAddressCheck = (clockShouldBe - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle - for(;;) { + int64_t lastLocalInterfaceAddressCheck = + (clockShouldBe - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + + 15000; // do this in 15s to give portmapper time to configure and other things + // time to settle + for (;;) { _run_m.lock(); - if (!_run) { + if (! _run) { _run_m.unlock(); _termReason_m.lock(); _termReason = ONE_NORMAL_TERMINATION; _termReason_m.unlock(); break; - } else { + } + else { _run_m.unlock(); } @@ -347,24 +427,28 @@ public: // Attempt to detect sleep/wake events by detecting delay overruns bool restarted = false; - if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) { + if ((now > clockShouldBe) && ((now - clockShouldBe) > 10000)) { _lastRestart = now; restarted = true; } - // Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default) - if (((now - lastBindRefresh) >= (_multipathMode ? ZT_BINDER_REFRESH_PERIOD / 8 : ZT_BINDER_REFRESH_PERIOD))||(restarted)) { + // Refresh bindings in case device's interfaces have changed, and also sync routes + // to update any shadow routes (e.g. shadow default) + if (((now - lastBindRefresh) + >= (_multipathMode ? ZT_BINDER_REFRESH_PERIOD / 8 : ZT_BINDER_REFRESH_PERIOD)) + || (restarted)) { lastBindRefresh = now; unsigned int p[3]; unsigned int pc = 0; - for(int i=0;i<3;++i) { + for (int i = 0; i < 3; ++i) { if (_ports[i]) p[pc++] = _ports[i]; } - _binder.refresh(_phy,p,pc,explicitBind,*this); + _binder.refresh(_phy, p, pc, explicitBind, *this); } // Update multipath mode (if needed) - if (((now - lastMultipathModeUpdate) >= ZT_BINDER_REFRESH_PERIOD / 8)||(restarted)) { + if (((now - lastMultipathModeUpdate) >= ZT_BINDER_REFRESH_PERIOD / 8) + || (restarted)) { lastMultipathModeUpdate = now; _node->setMultipathMode(_multipathMode); } @@ -375,35 +459,66 @@ public: // Run background task processor in core if it's time to do so int64_t dl = _nextBackgroundTaskDeadline; if (dl <= now) { - _node->processBackgroundTasks((void *)0,now,&_nextBackgroundTaskDeadline); + _node->processBackgroundTasks((void*)0, now, &_nextBackgroundTaskDeadline); dl = _nextBackgroundTaskDeadline; } // Sync multicast group memberships if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) { lastTapMulticastGroupCheck = now; - std::vector< std::pair< uint64_t,std::pair< std::vector,std::vector > > > mgChanges; + std::vector, std::vector > > > + mgChanges; { Mutex::Lock _l(_nets_m); mgChanges.reserve(_nets.size() + 1); - for(std::map::const_iterator n(_nets.begin());n!=_nets.end();++n) { + for (std::map::const_iterator n(_nets.begin()); + n != _nets.end(); + ++n) { if (n->second.tap) { - mgChanges.push_back(std::pair< uint64_t,std::pair< std::vector,std::vector > >(n->first,std::pair< std::vector,std::vector >())); - n->second.tap->scanMulticastGroups(mgChanges.back().second.first,mgChanges.back().second.second); + mgChanges.push_back(std::pair< + uint64_t, + std::pair< + std::vector, + std::vector > >( + n->first, + std::pair< + std::vector, + std::vector >())); + n->second.tap->scanMulticastGroups( + mgChanges.back().second.first, + mgChanges.back().second.second); } } } - for(std::vector< std::pair< uint64_t,std::pair< std::vector,std::vector > > >::iterator c(mgChanges.begin());c!=mgChanges.end();++c) { + for (std::vector, + std::vector > > >::iterator c(mgChanges.begin()); + c != mgChanges.end(); + ++c) { auto mgpair = c->second; - for(std::vector::iterator m(mgpair.first.begin());m!= mgpair.first.end();++m) - _node->multicastSubscribe((void *)0,c->first,m->mac().toInt(),m->adi()); - for(std::vector::iterator m(mgpair.second.begin());m!= mgpair.second.end();++m) - _node->multicastUnsubscribe(c->first,m->mac().toInt(),m->adi()); + for (std::vector::iterator m(mgpair.first.begin()); + m != mgpair.first.end(); + ++m) + _node->multicastSubscribe( + (void*)0, + c->first, + m->mac().toInt(), + m->adi()); + for (std::vector::iterator m(mgpair.second.begin()); + m != mgpair.second.end(); + ++m) + _node->multicastUnsubscribe(c->first, m->mac().toInt(), m->adi()); } } // Sync information about physical network interfaces - if ((now - lastLocalInterfaceAddressCheck) >= (_multipathMode ? ZT_LOCAL_INTERFACE_CHECK_INTERVAL / 8 : ZT_LOCAL_INTERFACE_CHECK_INTERVAL)) { + if ((now - lastLocalInterfaceAddressCheck) + >= (_multipathMode ? ZT_LOCAL_INTERFACE_CHECK_INTERVAL / 8 + : ZT_LOCAL_INTERFACE_CHECK_INTERVAL)) { lastLocalInterfaceAddressCheck = now; _node->clearLocalInterfaceAddresses(); @@ -411,31 +526,41 @@ public: #ifdef ZT_USE_MINIUPNPC if (_portMapper) { std::vector mappedAddresses(_portMapper->get()); - for(std::vector::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext) - _node->addLocalInterfaceAddress(reinterpret_cast(&(*ext))); + for (std::vector::const_iterator ext(mappedAddresses.begin()); + ext != mappedAddresses.end(); + ++ext) + _node->addLocalInterfaceAddress( + reinterpret_cast(&(*ext))); } #endif std::vector boundAddrs(_binder.allBoundLocalInterfaceAddresses()); - for(std::vector::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i) - _node->addLocalInterfaceAddress(reinterpret_cast(&(*i))); + for (std::vector::const_iterator i(boundAddrs.begin()); + i != boundAddrs.end(); + ++i) + _node->addLocalInterfaceAddress( + reinterpret_cast(&(*i))); } // Clean peers.d periodically if ((now - lastCleanedPeersDb) >= 3600000) { lastCleanedPeersDb = now; - OSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S "peers.d").c_str(),now - 2592000000LL); // delete older than 30 days + OSUtils::cleanDirectory( + (_homePath + ZT_PATH_SEPARATOR_S "peers.d").c_str(), + now - 2592000000LL); // delete older than 30 days } const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100; clockShouldBe = now + (uint64_t)delay; _phy.poll(delay); } - } catch (std::exception &e) { + } + catch (std::exception& e) { Mutex::Lock _l(_termReason_m); _termReason = ONE_UNRECOVERABLE_ERROR; - _fatalErrorMessage = std::string("unexpected exception in main thread: ")+e.what(); - } catch ( ... ) { + _fatalErrorMessage = std::string("unexpected exception in main thread: ") + e.what(); + } + catch (...) { Mutex::Lock _l(_termReason_m); _termReason = ONE_UNRECOVERABLE_ERROR; _fatalErrorMessage = "unexpected exception in main thread: unknown exception"; @@ -443,13 +568,13 @@ public: { Mutex::Lock _l(_nets_m); - for(std::map::iterator n(_nets.begin());n!=_nets.end();++n) + for (std::map::iterator n(_nets.begin()); n != _nets.end(); ++n) delete n->second.tap; _nets.clear(); } delete _node; - _node = (Node *)0; + _node = (Node*)0; return _termReason; } @@ -469,10 +594,11 @@ public: virtual std::string portDeviceName(uint64_t nwid) const override { Mutex::Lock _l(_nets_m); - std::map::const_iterator n(_nets.find(nwid)); - if ((n != _nets.end())&&(n->second.tap)) + std::map::const_iterator n(_nets.find(nwid)); + if ((n != _nets.end()) && (n->second.tap)) return n->second.tap->deviceName(); - else return std::string(); + else + return std::string(); } virtual std::string givenHomePath() @@ -480,18 +606,18 @@ public: return _homePath; } - void getRoutes(uint64_t nwid, void *routeArray, unsigned int *numRoutes) override + void getRoutes(uint64_t nwid, void* routeArray, unsigned int* numRoutes) override { Mutex::Lock _l(_nets_m); - NetworkState &n = _nets[nwid]; + NetworkState& n = _nets[nwid]; *numRoutes = *numRoutes < n.config.routeCount ? *numRoutes : n.config.routeCount; - for(unsigned int i=0; i<*numRoutes; i++) { - ZT_VirtualNetworkRoute *vnr = (ZT_VirtualNetworkRoute*)routeArray; + for (unsigned int i = 0; i < *numRoutes; i++) { + ZT_VirtualNetworkRoute* vnr = (ZT_VirtualNetworkRoute*)routeArray; memcpy(&vnr[i], &(n.config.routes[i]), sizeof(ZT_VirtualNetworkRoute)); } } - virtual Node *getNode() override + virtual Node* getNode() override { return _node; } @@ -504,10 +630,10 @@ public: _phy.whack(); } - virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const override + virtual bool getNetworkSettings(const uint64_t nwid, NetworkSettings& settings) const override { Mutex::Lock _l(_nets_m); - std::map::const_iterator n(_nets.find(nwid)); + std::map::const_iterator n(_nets.find(nwid)); if (n == _nets.end()) return false; settings = n->second.settings; @@ -519,9 +645,9 @@ public: // ========================================================================= // Checks if a managed IP or route target is allowed - bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target) + bool checkIfManagedIsAllowed(const NetworkState& n, const InetAddress& target) { - if (!n.settings.allowManaged) + if (! n.settings.allowManaged) return false; if (n.settings.allowManagedWhitelist.size() > 0) { @@ -532,72 +658,84 @@ public: break; } } - if (!allowed) return false; + if (! allowed) + return false; } if (target.isDefaultRoute()) return n.settings.allowDefault; - switch(target.ipScope()) { + switch (target.ipScope()) { case InetAddress::IP_SCOPE_NONE: case InetAddress::IP_SCOPE_MULTICAST: case InetAddress::IP_SCOPE_LOOPBACK: - case InetAddress::IP_SCOPE_LINK_LOCAL: - return false; - case InetAddress::IP_SCOPE_GLOBAL: - return n.settings.allowGlobal; - default: - return true; + case InetAddress::IP_SCOPE_LINK_LOCAL: return false; + case InetAddress::IP_SCOPE_GLOBAL: return n.settings.allowGlobal; + default: return true; } } // Apply or update managed IPs for a configured network (be sure n.tap exists) - void syncManagedStuff(NetworkState &n) + void syncManagedStuff(NetworkState& n) { char ipbuf[64]; // assumes _nets_m is locked std::vector newManagedIps; newManagedIps.reserve(n.config.assignedAddressCount); - for(unsigned int i=0;i(&(n.config.assignedAddresses[i])); - if (checkIfManagedIsAllowed(n,*ii)) + for (unsigned int i = 0; i < n.config.assignedAddressCount; ++i) { + const InetAddress* ii = + reinterpret_cast(&(n.config.assignedAddresses[i])); + if (checkIfManagedIsAllowed(n, *ii)) newManagedIps.push_back(*ii); } - std::sort(newManagedIps.begin(),newManagedIps.end()); - newManagedIps.erase(std::unique(newManagedIps.begin(),newManagedIps.end()),newManagedIps.end()); - for(std::vector::iterator ip(n.managedIps.begin());ip!=n.managedIps.end();++ip) { - if (std::find(newManagedIps.begin(),newManagedIps.end(),*ip) == newManagedIps.end()) { - if (!n.tap->removeIp(*ip)) { - fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString(ipbuf)); - } else { - struct zts_addr_details *ad = new zts_addr_details(); + std::sort(newManagedIps.begin(), newManagedIps.end()); + newManagedIps.erase( + std::unique(newManagedIps.begin(), newManagedIps.end()), + newManagedIps.end()); + for (std::vector::iterator ip(n.managedIps.begin()); ip != n.managedIps.end(); + ++ip) { + if (std::find(newManagedIps.begin(), newManagedIps.end(), *ip) == newManagedIps.end()) { + if (! n.tap->removeIp(*ip)) { + fprintf( + stderr, + "ERROR: unable to remove ip address %s" ZT_EOL_S, + ip->toString(ipbuf)); + } + else { + struct zts_addr_details* ad = new zts_addr_details(); ad->nwid = n.tap->_nwid; if ((*ip).isV4()) { - struct sockaddr_in *in4 = (struct sockaddr_in*)&(ad->addr); + struct sockaddr_in* in4 = (struct sockaddr_in*)&(ad->addr); memcpy(&(in4->sin_addr.s_addr), (*ip).rawIpData(), 4); _enqueueEvent(ZTS_EVENT_ADDR_REMOVED_IP4, (void*)ad); } if ((*ip).isV6()) { - struct sockaddr_in6 *in6 = (struct sockaddr_in6*)&(ad->addr); + struct sockaddr_in6* in6 = (struct sockaddr_in6*)&(ad->addr); memcpy(&(in6->sin6_addr.s6_addr), (*ip).rawIpData(), 16); _enqueueEvent(ZTS_EVENT_ADDR_REMOVED_IP6, (void*)ad); } } } } - for(std::vector::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) { - if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) { - if (!n.tap->addIp(*ip)) { - fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString(ipbuf)); - } else { - struct zts_addr_details *ad = new zts_addr_details(); + for (std::vector::iterator ip(newManagedIps.begin()); + ip != newManagedIps.end(); + ++ip) { + if (std::find(n.managedIps.begin(), n.managedIps.end(), *ip) == n.managedIps.end()) { + if (! n.tap->addIp(*ip)) { + fprintf( + stderr, + "ERROR: unable to add ip address %s" ZT_EOL_S, + ip->toString(ipbuf)); + } + else { + struct zts_addr_details* ad = new zts_addr_details(); ad->nwid = n.tap->_nwid; if ((*ip).isV4()) { - struct sockaddr_in *in4 = (struct sockaddr_in*)&(ad->addr); + struct sockaddr_in* in4 = (struct sockaddr_in*)&(ad->addr); memcpy(&(in4->sin_addr.s_addr), (*ip).rawIpData(), 4); _enqueueEvent(ZTS_EVENT_ADDR_ADDED_IP4, (void*)ad); } if ((*ip).isV6()) { - struct sockaddr_in6 *in6 = (struct sockaddr_in6*)&(ad->addr); + struct sockaddr_in6* in6 = (struct sockaddr_in6*)&(ad->addr); memcpy(&(in6->sin6_addr.s6_addr), (*ip).rawIpData(), 16); _enqueueEvent(ZTS_EVENT_ADDR_ADDED_IP6, (void*)ad); } @@ -605,28 +743,40 @@ public: } } n.managedIps.swap(newManagedIps); - } // ========================================================================= // Handlers for Node and Phy<> callbacks // ========================================================================= - inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len) + inline void phyOnDatagram( + PhySocket* sock, + void** uptr, + const struct sockaddr* localAddr, + const struct sockaddr* from, + void* data, + unsigned long len) { - if ((len >= 16)&&(reinterpret_cast(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) + if ((len >= 16) + && (reinterpret_cast(from)->ipScope() + == InetAddress::IP_SCOPE_GLOBAL)) _lastDirectReceiveFromGlobal = OSUtils::now(); const ZT_ResultCode rc = _node->processWirePacket( - (void *)0, - OSUtils::now(), - reinterpret_cast(sock), - reinterpret_cast(from), // Phy<> uses sockaddr_storage, so it'll always be that big - data, - len, - &_nextBackgroundTaskDeadline); + (void*)0, + OSUtils::now(), + reinterpret_cast(sock), + reinterpret_cast( + from), // Phy<> uses sockaddr_storage, so it'll always be that big + data, + len, + &_nextBackgroundTaskDeadline); if (ZT_ResultCode_isFatal(rc)) { char tmp[256]; - OSUtils::ztsnprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc); + OSUtils::ztsnprintf( + tmp, + sizeof(tmp), + "fatal error code from processWirePacket: %d", + (int)rc); Mutex::Lock _l(_termReason_m); _termReason = ONE_UNRECOVERABLE_ERROR; _fatalErrorMessage = tmp; @@ -634,70 +784,114 @@ public: } } - inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {} - inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {} - void phyOnTcpClose(PhySocket *sock,void **uptr) {} - void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {} - inline void phyOnTcpWritable(PhySocket *sock,void **uptr) {} - inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {} - inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {} - inline void phyOnUnixClose(PhySocket *sock,void **uptr) {} - inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {} - inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {} + inline void phyOnTcpConnect(PhySocket* sock, void** uptr, bool success) + { + } + inline void phyOnTcpAccept( + PhySocket* sockL, + PhySocket* sockN, + void** uptrL, + void** uptrN, + const struct sockaddr* from) + { + } + void phyOnTcpClose(PhySocket* sock, void** uptr) + { + } + void phyOnTcpData(PhySocket* sock, void** uptr, void* data, unsigned long len) + { + } + inline void phyOnTcpWritable(PhySocket* sock, void** uptr) + { + } + inline void + phyOnFileDescriptorActivity(PhySocket* sock, void** uptr, bool readable, bool writable) + { + } + inline void phyOnUnixAccept(PhySocket* sockL, PhySocket* sockN, void** uptrL, void** uptrN) + { + } + inline void phyOnUnixClose(PhySocket* sock, void** uptr) + { + } + inline void phyOnUnixData(PhySocket* sock, void** uptr, void* data, unsigned long len) + { + } + inline void phyOnUnixWritable(PhySocket* sock, void** uptr) + { + } - inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc) + inline int nodeVirtualNetworkConfigFunction( + uint64_t nwid, + void** nuptr, + enum ZT_VirtualNetworkConfigOperation op, + const ZT_VirtualNetworkConfig* nwc) { Mutex::Lock _l(_nets_m); - NetworkState &n = _nets[nwid]; - - switch(op) { + NetworkState& n = _nets[nwid]; + switch (op) { case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP: - if (!n.tap) { + if (! n.tap) { char friendlyName[128]; - OSUtils::ztsnprintf(friendlyName,sizeof(friendlyName),"ZeroTier One [%.16llx]",nwid); + OSUtils::ztsnprintf( + friendlyName, + sizeof(friendlyName), + "ZeroTier One [%.16llx]", + nwid); n.tap = new EthernetTap( - _homePath.c_str(), - MAC(nwc->mac), - nwc->mtu, - (unsigned int)ZT_IF_METRIC, - nwid, - friendlyName, - StapFrameHandler, - (void *)this); - *nuptr = (void *)&n; + _homePath.c_str(), + MAC(nwc->mac), + nwc->mtu, + (unsigned int)ZT_IF_METRIC, + nwid, + friendlyName, + StapFrameHandler, + (void*)this); + *nuptr = (void*)&n; } - // After setting up tap, fall through to CONFIG_UPDATE since we also want to do this... + // After setting up tap, fall through to CONFIG_UPDATE since we also want to do + // this... case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE: - memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig)); - if (n.tap) { // sanity check + memcpy(&(n.config), nwc, sizeof(ZT_VirtualNetworkConfig)); + if (n.tap) { // sanity check syncManagedStuff(n); n.tap->setMtu(nwc->mtu); - } else { - _nets.erase(nwid); - return -999; // tap init failed } - if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE) { // Prevent junk from ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP + else { + _nets.erase(nwid); + return -999; // tap init failed + } + if (op + == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE) { // Prevent junk from + // ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP _enqueueEvent(ZTS_EVENT_NETWORK_UPDATE, (void*)prepare_network_details_msg(n)); } break; case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY: - if (n.tap) { // sanity check - *nuptr = (void *)0; + if (n.tap) { // sanity check + *nuptr = (void*)0; delete n.tap; _nets.erase(nwid); if (allowNetworkCaching) { if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY) { char nlcpath[256]; - OSUtils::ztsnprintf(nlcpath,sizeof(nlcpath),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.local.conf",_homePath.c_str(),nwid); + OSUtils::ztsnprintf( + nlcpath, + sizeof(nlcpath), + "%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S + "%.16llx.local.conf", + _homePath.c_str(), + nwid); OSUtils::rm(nlcpath); } } - } else { + } + else { _nets.erase(nwid); } break; @@ -705,15 +899,15 @@ public: return 0; } - inline void nodeEventCallback(enum ZT_Event event,const void *metaData) + inline void nodeEventCallback(enum ZT_Event event, const void* metaData) { // Feed node events into lock-free queue for later dequeuing by the callback thread - switch(event) { + switch (event) { case ZT_EVENT_UP: { _enqueueEvent(ZTS_EVENT_NODE_UP, NULL); - } break; + } break; case ZT_EVENT_ONLINE: { - struct zts_node_details *nd = new zts_node_details; + struct zts_node_details* nd = new zts_node_details; nd->address = _node->address(); nd->versionMajor = ZEROTIER_ONE_VERSION_MAJOR; nd->versionMinor = ZEROTIER_ONE_VERSION_MINOR; @@ -722,53 +916,53 @@ public: nd->secondaryPort = _secondaryPort; nd->tertiaryPort = _tertiaryPort; _enqueueEvent(ZTS_EVENT_NODE_ONLINE, (void*)nd); - } break; + } break; case ZT_EVENT_OFFLINE: { - struct zts_node_details *nd = new zts_node_details; + struct zts_node_details* nd = new zts_node_details; nd->address = _node->address(); _enqueueEvent(ZTS_EVENT_NODE_OFFLINE, (void*)nd); - } break; + } break; case ZT_EVENT_DOWN: { - struct zts_node_details *nd = new zts_node_details; + struct zts_node_details* nd = new zts_node_details; nd->address = _node->address(); _enqueueEvent(ZTS_EVENT_NODE_DOWN, (void*)nd); - } break; + } break; case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: { Mutex::Lock _l(_termReason_m); _termReason = ONE_IDENTITY_COLLISION; _fatalErrorMessage = "identity/address collision"; this->terminate(); - } break; + } break; case ZT_EVENT_TRACE: { if (metaData) { - ::fprintf(stderr,"%s" ZT_EOL_S,(const char *)metaData); + ::fprintf(stderr, "%s" ZT_EOL_S, (const char*)metaData); ::fflush(stderr); } - } break; + } break; - default: - break; + default: break; } } - void native_ss_to_zts_ss(struct zts_sockaddr_storage *ss_out, const struct sockaddr_storage *ss_in) + void + native_ss_to_zts_ss(struct zts_sockaddr_storage* ss_out, const struct sockaddr_storage* ss_in) { if (ss_in->ss_family == AF_INET) { - struct sockaddr_in *s_in4 = (struct sockaddr_in *)ss_in; - struct zts_sockaddr_in *d_in4 = (struct zts_sockaddr_in *)ss_out; + struct sockaddr_in* s_in4 = (struct sockaddr_in*)ss_in; + struct zts_sockaddr_in* d_in4 = (struct zts_sockaddr_in*)ss_out; #ifndef __WINDOWS__ - d_in4->sin_len = 0; // s_in4->sin_len; + d_in4->sin_len = 0; // s_in4->sin_len; #endif d_in4->sin_family = ZTS_AF_INET; d_in4->sin_port = s_in4->sin_port; memcpy(&(d_in4->sin_addr), &(s_in4->sin_addr), sizeof(s_in4->sin_addr)); } if (ss_in->ss_family == AF_INET6) { - struct sockaddr_in6 *s_in6 = (struct sockaddr_in6 *)ss_in; - struct zts_sockaddr_in6 *d_in6 = (struct zts_sockaddr_in6 *)ss_out; + struct sockaddr_in6* s_in6 = (struct sockaddr_in6*)ss_in; + struct zts_sockaddr_in6* d_in6 = (struct zts_sockaddr_in6*)ss_out; #ifndef __WINDOWS__ - d_in6->sin6_len = 0; // s_in6->sin6_len; + d_in6->sin6_len = 0; // s_in6->sin6_len; #endif d_in6->sin6_family = ZTS_AF_INET6; d_in6->sin6_port = s_in6->sin6_port; @@ -778,9 +972,9 @@ public: } } - struct zts_network_details *prepare_network_details_msg(const NetworkState &n) + struct zts_network_details* prepare_network_details_msg(const NetworkState& n) { - struct zts_network_details *nd = new zts_network_details(); + struct zts_network_details* nd = new zts_network_details(); nd->nwid = n.config.nwid; nd->mac = n.config.mac; @@ -796,20 +990,23 @@ public: // Copy and convert address structures nd->assignedAddressCount = n.config.assignedAddressCount; - for (unsigned int i=0; iassignedAddresses[i]), &(n.config.assignedAddresses[i])); } nd->routeCount = n.config.routeCount; - for (unsigned int i=0; iroutes[i].target), &(n.config.routes[i].target)); - native_ss_to_zts_ss(&(nd->routes[i].via), &(n.config.routes[i].via)); - nd->routes[i].flags = n.config.routes[i].flags; - nd->routes[i].metric = n.config.routes[i].metric; + for (unsigned int i = 0; i < n.config.routeCount; i++) { + native_ss_to_zts_ss(&(nd->routes[i].target), &(n.config.routes[i].target)); + native_ss_to_zts_ss(&(nd->routes[i].via), &(n.config.routes[i].via)); + nd->routes[i].flags = n.config.routes[i].flags; + nd->routes[i].metric = n.config.routes[i].metric; } nd->multicastSubscriptionCount = n.config.multicastSubscriptionCount; - memcpy(nd->multicastSubscriptions, &(n.config.multicastSubscriptions), sizeof(n.config.multicastSubscriptions)); + memcpy( + nd->multicastSubscriptions, + &(n.config.multicastSubscriptions), + sizeof(n.config.multicastSubscriptions)); return nd; } @@ -818,88 +1015,103 @@ public: { // Force the ordering of callback messages, these messages are // only useful if the node and stack are both up and running - if (!_node->online() || !_lwip_is_up()) { + if (! _node->online() || ! _lwip_is_up()) { return; } // Generate messages to be dequeued by the callback message thread Mutex::Lock _l(_nets_m); - for(std::map::iterator n(_nets.begin());n!=_nets.end();++n) { + for (std::map::iterator n(_nets.begin()); n != _nets.end(); ++n) { auto netState = n->second; int mostRecentStatus = netState.config.status; - VirtualTap *tap = netState.tap; + VirtualTap* tap = netState.tap; // uint64_t nwid = n->first; if (netState.tap->_networkStatus == mostRecentStatus) { - continue; // No state change + continue; // No state change } switch (mostRecentStatus) { case ZT_NETWORK_STATUS_NOT_FOUND: - _enqueueEvent(ZTS_EVENT_NETWORK_NOT_FOUND, (void*)prepare_network_details_msg(netState)); + _enqueueEvent( + ZTS_EVENT_NETWORK_NOT_FOUND, + (void*)prepare_network_details_msg(netState)); break; case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: - _enqueueEvent(ZTS_EVENT_NETWORK_CLIENT_TOO_OLD, (void*)prepare_network_details_msg(netState)); + _enqueueEvent( + ZTS_EVENT_NETWORK_CLIENT_TOO_OLD, + (void*)prepare_network_details_msg(netState)); break; case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: - _enqueueEvent(ZTS_EVENT_NETWORK_REQ_CONFIG, (void*)prepare_network_details_msg(netState)); + _enqueueEvent( + ZTS_EVENT_NETWORK_REQ_CONFIG, + (void*)prepare_network_details_msg(netState)); break; case ZT_NETWORK_STATUS_OK: if (tap->hasIpv4Addr() && _lwip_is_netif_up(tap->netif4)) { - _enqueueEvent(ZTS_EVENT_NETWORK_READY_IP4, (void*)prepare_network_details_msg(netState)); + _enqueueEvent( + ZTS_EVENT_NETWORK_READY_IP4, + (void*)prepare_network_details_msg(netState)); } if (tap->hasIpv6Addr() && _lwip_is_netif_up(tap->netif6)) { - _enqueueEvent(ZTS_EVENT_NETWORK_READY_IP6, (void*)prepare_network_details_msg(netState)); + _enqueueEvent( + ZTS_EVENT_NETWORK_READY_IP6, + (void*)prepare_network_details_msg(netState)); } // In addition to the READY messages, send one OK message - _enqueueEvent(ZTS_EVENT_NETWORK_OK, (void*)prepare_network_details_msg(netState)); + _enqueueEvent( + ZTS_EVENT_NETWORK_OK, + (void*)prepare_network_details_msg(netState)); break; case ZT_NETWORK_STATUS_ACCESS_DENIED: - _enqueueEvent(ZTS_EVENT_NETWORK_ACCESS_DENIED, (void*)prepare_network_details_msg(netState)); - break; - default: + _enqueueEvent( + ZTS_EVENT_NETWORK_ACCESS_DENIED, + (void*)prepare_network_details_msg(netState)); break; + default: break; } netState.tap->_networkStatus = mostRecentStatus; } bool bShouldCopyPeerInfo = false; int eventCode = 0; - ZT_PeerList *pl = _node->peers(); - struct zts_peer_details *pd; + ZT_PeerList* pl = _node->peers(); + struct zts_peer_details* pd; if (pl) { - for(unsigned long i=0;ipeerCount;++i) { - if (!peerCache.count(pl->peers[i].address)) { + for (unsigned long i = 0; i < pl->peerCount; ++i) { + if (! peerCache.count(pl->peers[i].address)) { // New peer, add status if (pl->peers[i].pathCount > 0) { - bShouldCopyPeerInfo=true; + bShouldCopyPeerInfo = true; eventCode = ZTS_EVENT_PEER_DIRECT; } if (pl->peers[i].pathCount == 0) { - bShouldCopyPeerInfo=true; + bShouldCopyPeerInfo = true; eventCode = ZTS_EVENT_PEER_RELAY; } } // Previously known peer, update status else { if (peerCache[pl->peers[i].address] < pl->peers[i].pathCount) { - bShouldCopyPeerInfo=true; + bShouldCopyPeerInfo = true; eventCode = ZTS_EVENT_PEER_PATH_DISCOVERED; } if (peerCache[pl->peers[i].address] > pl->peers[i].pathCount) { - bShouldCopyPeerInfo=true; + bShouldCopyPeerInfo = true; eventCode = ZTS_EVENT_PEER_PATH_DEAD; } if (peerCache[pl->peers[i].address] == 0 && pl->peers[i].pathCount > 0) { - bShouldCopyPeerInfo=true; + bShouldCopyPeerInfo = true; eventCode = ZTS_EVENT_PEER_DIRECT; } if (peerCache[pl->peers[i].address] > 0 && pl->peers[i].pathCount == 0) { - bShouldCopyPeerInfo=true; + bShouldCopyPeerInfo = true; eventCode = ZTS_EVENT_PEER_RELAY; } } if (bShouldCopyPeerInfo) { pd = new zts_peer_details(); memcpy(pd, &(pl->peers[i]), sizeof(struct zts_peer_details)); - for (unsigned int j=0; jpeers[i].pathCount; j++) { - native_ss_to_zts_ss(&(pd->paths[j].address), &(pl->peers[i].paths[j].address)); + for (unsigned int j = 0; j < pl->peers[i].pathCount; j++) { + native_ss_to_zts_ss( + &(pd->paths[j].address), + &(pl->peers[i].paths[j].address)); } _enqueueEvent(eventCode, (void*)pd); bShouldCopyPeerInfo = false; @@ -908,7 +1120,7 @@ public: peerCache[pl->peers[i].address] = pl->peers[i].pathCount; } } - _node->freeQueryResult((void *)pl); + _node->freeQueryResult((void*)pl); } inline void join(uint64_t nwid) override @@ -921,7 +1133,7 @@ public: _node->leave(nwid, NULL, NULL); } - inline void getIdentity(char *key_pair_str, uint16_t *key_buf_len) override + inline void getIdentity(char* key_pair_str, uint16_t* key_buf_len) override { if (key_pair_str == NULL || *key_buf_len < ZT_IDENTITY_STRING_BUFFER_LENGTH) { return; @@ -936,48 +1148,78 @@ public: } // TODO: This logic should be further generalized in the next API redesign - inline void nodeStatePutFunction(enum ZT_StateObjectType type,const uint64_t id[2],const void *data,int len) + inline void nodeStatePutFunction( + enum ZT_StateObjectType type, + const uint64_t id[2], + const void* data, + int len) { char p[1024]; - FILE *f; + FILE* f; bool secure = false; char dirname[1024]; dirname[0] = 0; - switch(type) { + switch (type) { case ZT_STATE_OBJECT_IDENTITY_PUBLIC: memcpy(_userProvidedPublicIdentity, data, len); if (disableLocalStorage) { return; - } else { - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str()); + } + else { + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "identity.public", + _homePath.c_str()); } break; case ZT_STATE_OBJECT_IDENTITY_SECRET: memcpy(_userProvidedSecretIdentity, data, len); if (disableLocalStorage) { return; - } else { - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str()); + } + else { + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "identity.secret", + _homePath.c_str()); } secure = true; break; case ZT_STATE_OBJECT_PLANET: if (disableLocalStorage) { return; - } else { - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str()); + } + else { + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "planet", + _homePath.c_str()); } break; case ZT_STATE_OBJECT_NETWORK_CONFIG: if (disableLocalStorage) { return; - } else { + } + else { if (allowNetworkCaching) { - OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "networks.d",_homePath.c_str()); - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.conf",dirname,(unsigned long long)id[0]); + OSUtils::ztsnprintf( + dirname, + sizeof(dirname), + "%s" ZT_PATH_SEPARATOR_S "networks.d", + _homePath.c_str()); + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "%.16llx.conf", + dirname, + (unsigned long long)id[0]); secure = true; - } else { + } + else { return; } } @@ -985,57 +1227,76 @@ public: case ZT_STATE_OBJECT_PEER: if (disableLocalStorage) { return; - } else { + } + else { if (allowPeerCaching) { - OSUtils::ztsnprintf(dirname,sizeof(dirname),"%s" ZT_PATH_SEPARATOR_S "peers.d",_homePath.c_str()); - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.10llx.peer",dirname,(unsigned long long)id[0]); - } else { - return; // Do nothing + OSUtils::ztsnprintf( + dirname, + sizeof(dirname), + "%s" ZT_PATH_SEPARATOR_S "peers.d", + _homePath.c_str()); + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "%.10llx.peer", + dirname, + (unsigned long long)id[0]); + } + else { + return; // Do nothing } } break; - default: - return; + default: return; } if (len >= 0) { // Check to see if we've already written this first. This reduces // redundant writes and I/O overhead on most platforms and has // little effect on others. - f = fopen(p,"rb"); + f = fopen(p, "rb"); if (f) { char buf[65535]; - long l = (long)fread(buf,1,sizeof(buf),f); + long l = (long)fread(buf, 1, sizeof(buf), f); fclose(f); - if ((l == (long)len)&&(memcmp(data,buf,l) == 0)) + if ((l == (long)len) && (memcmp(data, buf, l) == 0)) return; } - f = fopen(p,"wb"); - if ((!f)&&(dirname[0])) { // create subdirectory if it does not exist + f = fopen(p, "wb"); + if ((! f) && (dirname[0])) { // create subdirectory if it does not exist OSUtils::mkdir(dirname); - f = fopen(p,"wb"); + f = fopen(p, "wb"); } if (f) { - if (fwrite(data,len,1,f) != 1) - fprintf(stderr,"WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S,p); + if (fwrite(data, len, 1, f) != 1) + fprintf(stderr, "WARNING: unable to write to file: %s (I/O error)" ZT_EOL_S, p); fclose(f); if (secure) - OSUtils::lockDownFile(p,false); - } else { - fprintf(stderr,"WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S,p); + OSUtils::lockDownFile(p, false); } - } else { + else { + fprintf( + stderr, + "WARNING: unable to write to file: %s (unable to open)" ZT_EOL_S, + p); + } + } + else { OSUtils::rm(p); } } // TODO: This logic should be further generalized in the next API redesign - inline int nodeStateGetFunction(enum ZT_StateObjectType type,const uint64_t id[2],void *data,unsigned int maxlen) + inline int nodeStateGetFunction( + enum ZT_StateObjectType type, + const uint64_t id[2], + void* data, + unsigned int maxlen) { char p[4096]; unsigned int keylen = 0; - switch(type) { + switch (type) { case ZT_STATE_OBJECT_IDENTITY_PUBLIC: if (disableLocalStorage) { keylen = strlen(_userProvidedPublicIdentity); @@ -1046,8 +1307,13 @@ public: memcpy(data, _userProvidedPublicIdentity, keylen); return keylen; } - } else { - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.public",_homePath.c_str()); + } + else { + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "identity.public", + _homePath.c_str()); } break; case ZT_STATE_OBJECT_IDENTITY_SECRET: @@ -1060,23 +1326,40 @@ public: memcpy(data, _userProvidedSecretIdentity, keylen); return keylen; } - } else { - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "identity.secret",_homePath.c_str()); + } + else { + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "identity.secret", + _homePath.c_str()); } break; case ZT_STATE_OBJECT_PLANET: if (disableLocalStorage) { return -1; - } else { - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "planet",_homePath.c_str()); + } + else { + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "planet", + _homePath.c_str()); } break; case ZT_STATE_OBJECT_NETWORK_CONFIG: if (disableLocalStorage) { return -1; - } else { + } + else { if (allowNetworkCaching) { - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S "%.16llx.conf",_homePath.c_str(),(unsigned long long)id[0]); + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "networks.d" ZT_PATH_SEPARATOR_S + "%.16llx.conf", + _homePath.c_str(), + (unsigned long long)id[0]); } else { return -1; @@ -1085,15 +1368,19 @@ public: break; case ZT_STATE_OBJECT_PEER: if (allowPeerCaching) { - OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "peers.d" ZT_PATH_SEPARATOR_S "%.10llx.peer",_homePath.c_str(),(unsigned long long)id[0]); + OSUtils::ztsnprintf( + p, + sizeof(p), + "%s" ZT_PATH_SEPARATOR_S "peers.d" ZT_PATH_SEPARATOR_S "%.10llx.peer", + _homePath.c_str(), + (unsigned long long)id[0]); } break; - default: - return -1; + default: return -1; } - FILE *f = fopen(p,"rb"); + FILE* f = fopen(p, "rb"); if (f) { - int n = (int)fread(data,1,maxlen,f); + int n = (int)fread(data, 1, maxlen, f); fclose(f); if (n >= 0) return n; @@ -1101,40 +1388,68 @@ public: return -1; } - inline int nodeWirePacketSendFunction(const int64_t localSocket,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl) + inline int nodeWirePacketSendFunction( + const int64_t localSocket, + const struct sockaddr_storage* addr, + const void* data, + unsigned int len, + unsigned int ttl) { // Even when relaying we still send via UDP. This way if UDP starts // working we can instantly "fail forward" to it and stop using TCP // proxy fallback, which is slow. - if ((localSocket != -1)&&(localSocket != 0)&&(_binder.isUdpSocketValid((PhySocket *)((uintptr_t)localSocket)))) { - if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),ttl); - const bool r = _phy.udpSend((PhySocket *)((uintptr_t)localSocket),(const struct sockaddr *)addr,data,len); - if ((ttl)&&(addr->ss_family == AF_INET)) _phy.setIp4UdpTtl((PhySocket *)((uintptr_t)localSocket),255); + if ((localSocket != -1) && (localSocket != 0) + && (_binder.isUdpSocketValid((PhySocket*)((uintptr_t)localSocket)))) { + if ((ttl) && (addr->ss_family == AF_INET)) + _phy.setIp4UdpTtl((PhySocket*)((uintptr_t)localSocket), ttl); + const bool r = _phy.udpSend( + (PhySocket*)((uintptr_t)localSocket), + (const struct sockaddr*)addr, + data, + len); + if ((ttl) && (addr->ss_family == AF_INET)) + _phy.setIp4UdpTtl((PhySocket*)((uintptr_t)localSocket), 255); return ((r) ? 0 : -1); - } else { - return ((_binder.udpSendAll(_phy,addr,data,len,ttl)) ? 0 : -1); + } + else { + return ((_binder.udpSendAll(_phy, addr, data, len, ttl)) ? 0 : -1); } } - inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len) + inline void nodeVirtualNetworkFrameFunction( + uint64_t nwid, + void** nuptr, + uint64_t sourceMac, + uint64_t destMac, + unsigned int etherType, + unsigned int vlanId, + const void* data, + unsigned int len) { - NetworkState *n = reinterpret_cast(*nuptr); - if ((!n)||(!n->tap)) + NetworkState* n = reinterpret_cast(*nuptr); + if ((! n) || (! n->tap)) return; - n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len); + n->tap->put(MAC(sourceMac), MAC(destMac), etherType, data, len); } - inline int nodePathCheckFunction(uint64_t ztaddr,const int64_t localSocket,const struct sockaddr_storage *remoteAddr) + inline int nodePathCheckFunction( + uint64_t ztaddr, + const int64_t localSocket, + const struct sockaddr_storage* remoteAddr) { // Make sure we're not trying to do ZeroTier-over-ZeroTier { Mutex::Lock _l(_nets_m); - for(std::map::const_iterator n(_nets.begin());n!=_nets.end();++n) { + for (std::map::const_iterator n(_nets.begin()); + n != _nets.end(); + ++n) { if (n->second.tap) { std::vector ips(n->second.tap->ips()); - for(std::vector::const_iterator i(ips.begin());i!=ips.end();++i) { - if (i->containsAddress(*(reinterpret_cast(remoteAddr)))) { + for (std::vector::const_iterator i(ips.begin()); i != ips.end(); + ++i) { + if (i->containsAddress( + *(reinterpret_cast(remoteAddr)))) { return 0; } } @@ -1149,92 +1464,132 @@ public: * revisit if we see recursion problems. */ // Check blacklists - const Hashtable< uint64_t,std::vector > *blh = (const Hashtable< uint64_t,std::vector > *)0; - const std::vector *gbl = (const std::vector *)0; + const Hashtable >* blh = + (const Hashtable >*)0; + const std::vector* gbl = (const std::vector*)0; if (remoteAddr->ss_family == AF_INET) { blh = &_v4Blacklists; gbl = &_globalV4Blacklist; - } else if (remoteAddr->ss_family == AF_INET6) { + } + else if (remoteAddr->ss_family == AF_INET6) { blh = &_v6Blacklists; gbl = &_globalV6Blacklist; } if (blh) { Mutex::Lock _l(_localConfig_m); - const std::vector *l = blh->get(ztaddr); + const std::vector* l = blh->get(ztaddr); if (l) { - for(std::vector::const_iterator a(l->begin());a!=l->end();++a) { - if (a->containsAddress(*reinterpret_cast(remoteAddr))) + for (std::vector::const_iterator a(l->begin()); a != l->end(); ++a) { + if (a->containsAddress(*reinterpret_cast(remoteAddr))) return 0; } } } if (gbl) { - for(std::vector::const_iterator a(gbl->begin());a!=gbl->end();++a) { - if (a->containsAddress(*reinterpret_cast(remoteAddr))) + for (std::vector::const_iterator a(gbl->begin()); a != gbl->end(); ++a) { + if (a->containsAddress(*reinterpret_cast(remoteAddr))) return 0; } } return 1; } - inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result) + inline int nodePathLookupFunction(uint64_t ztaddr, int family, struct sockaddr_storage* result) { - const Hashtable< uint64_t,std::vector > *lh = (const Hashtable< uint64_t,std::vector > *)0; + const Hashtable >* lh = + (const Hashtable >*)0; if (family < 0) lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints; else if (family == AF_INET) lh = &_v4Hints; else if (family == AF_INET6) lh = &_v6Hints; - else return 0; - const std::vector *l = lh->get(ztaddr); - if ((l)&&(l->size() > 0)) { - memcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage)); + else + return 0; + const std::vector* l = lh->get(ztaddr); + if ((l) && (l->size() > 0)) { + memcpy( + result, + &((*l)[(unsigned long)_node->prng() % l->size()]), + sizeof(struct sockaddr_storage)); return 1; - } else return 0; + } + else + return 0; } - inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len) + inline void tapFrameHandler( + uint64_t nwid, + const MAC& from, + const MAC& to, + unsigned int etherType, + unsigned int vlanId, + const void* data, + unsigned int len) { - _node->processVirtualNetworkFrame((void *)0,OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline); + _node->processVirtualNetworkFrame( + (void*)0, + OSUtils::now(), + nwid, + from.toInt(), + to.toInt(), + etherType, + vlanId, + data, + len, + &_nextBackgroundTaskDeadline); } - bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr) + bool shouldBindInterface(const char* ifname, const InetAddress& ifaddr) { #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux) - if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback - if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt# - if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar - if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar + if ((ifname[0] == 'l') && (ifname[1] == 'o')) + return false; // loopback + if ((ifname[0] == 'z') && (ifname[1] == 't')) + return false; // sanity check: zt# + if ((ifname[0] == 't') && (ifname[1] == 'u') && (ifname[2] == 'n')) + return false; // tun# is probably an OpenVPN tunnel or similar + if ((ifname[0] == 't') && (ifname[1] == 'a') && (ifname[2] == 'p')) + return false; // tap# is probably an OpenVPN tunnel or similar #endif #ifdef __APPLE__ - if ((ifname[0] == 'f')&&(ifname[1] == 'e')&&(ifname[2] == 't')&&(ifname[3] == 'h')) return false; // ... as is feth# - if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback - if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt# - if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar - if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar - if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun# + if ((ifname[0] == 'f') && (ifname[1] == 'e') && (ifname[2] == 't') && (ifname[3] == 'h')) + return false; // ... as is feth# + if ((ifname[0] == 'l') && (ifname[1] == 'o')) + return false; // loopback + if ((ifname[0] == 'z') && (ifname[1] == 't')) + return false; // sanity check: zt# + if ((ifname[0] == 't') && (ifname[1] == 'u') && (ifname[2] == 'n')) + return false; // tun# is probably an OpenVPN tunnel or similar + if ((ifname[0] == 't') && (ifname[1] == 'a') && (ifname[2] == 'p')) + return false; // tap# is probably an OpenVPN tunnel or similar + if ((ifname[0] == 'u') && (ifname[1] == 't') && (ifname[2] == 'u') && (ifname[3] == 'n')) + return false; // ... as is utun# #endif { Mutex::Lock _l(_localConfig_m); - for(std::vector::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) { - if (!strncmp(p->c_str(),ifname,p->length())) + for (std::vector::const_iterator p(_interfacePrefixBlacklist.begin()); + p != _interfacePrefixBlacklist.end(); + ++p) { + if (! strncmp(p->c_str(), ifname, p->length())) return false; } } { // Check global blacklists - const std::vector *gbl = (const std::vector *)0; + const std::vector* gbl = (const std::vector*)0; if (ifaddr.ss_family == AF_INET) { gbl = &_globalV4Blacklist; - } else if (ifaddr.ss_family == AF_INET6) { + } + else if (ifaddr.ss_family == AF_INET6) { gbl = &_globalV6Blacklist; } if (gbl) { Mutex::Lock _l(_localConfig_m); - for(std::vector::const_iterator a(gbl->begin());a!=gbl->end();++a) { + for (std::vector::const_iterator a(gbl->begin()); a != gbl->end(); + ++a) { if (a->containsAddress(ifaddr)) return false; } @@ -1242,10 +1597,13 @@ public: } { Mutex::Lock _l(_nets_m); - for(std::map::const_iterator n(_nets.begin());n!=_nets.end();++n) { + for (std::map::const_iterator n(_nets.begin()); + n != _nets.end(); + ++n) { if (n->second.tap) { std::vector ips(n->second.tap->ips()); - for(std::vector::const_iterator i(ips.begin());i!=ips.end();++i) { + for (std::vector::const_iterator i(ips.begin()); i != ips.end(); + ++i) { if (i->ipsEqual(ifaddr)) return false; } @@ -1260,30 +1618,30 @@ public: { struct sockaddr_in in4; struct sockaddr_in6 in6; - PhySocket *tb; + PhySocket* tb; - memset(&in4,0,sizeof(in4)); + memset(&in4, 0, sizeof(in4)); in4.sin_family = AF_INET; in4.sin_port = Utils::hton((uint16_t)port); - tb = _phy.udpBind(reinterpret_cast(&in4),(void *)0,0); + tb = _phy.udpBind(reinterpret_cast(&in4), (void*)0, 0); if (tb) { - _phy.close(tb,false); - tb = _phy.tcpListen(reinterpret_cast(&in4),(void *)0); + _phy.close(tb, false); + tb = _phy.tcpListen(reinterpret_cast(&in4), (void*)0); if (tb) { - _phy.close(tb,false); + _phy.close(tb, false); return true; } } - memset(&in6,0,sizeof(in6)); + memset(&in6, 0, sizeof(in6)); in6.sin6_family = AF_INET6; in6.sin6_port = Utils::hton((uint16_t)port); - tb = _phy.udpBind(reinterpret_cast(&in6),(void *)0,0); + tb = _phy.udpBind(reinterpret_cast(&in6), (void*)0, 0); if (tb) { - _phy.close(tb,false); - tb = _phy.tcpListen(reinterpret_cast(&in6),(void *)0); + _phy.close(tb, false); + tb = _phy.tcpListen(reinterpret_cast(&in6), (void*)0); if (tb) { - _phy.close(tb,false); + _phy.close(tb, false); return true; } } @@ -1292,56 +1650,125 @@ public: } }; -static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid, - void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf) +static int SnodeVirtualNetworkConfigFunction( + ZT_Node* node, + void* uptr, + void* tptr, + uint64_t nwid, + void** nuptr, + enum ZT_VirtualNetworkConfigOperation op, + const ZT_VirtualNetworkConfig* nwconf) { - return reinterpret_cast(uptr)->nodeVirtualNetworkConfigFunction(nwid,nuptr,op,nwconf); + return reinterpret_cast(uptr) + ->nodeVirtualNetworkConfigFunction(nwid, nuptr, op, nwconf); } -static void SnodeEventCallback(ZT_Node *node,void *uptr,void *tptr,enum ZT_Event event,const void *metaData) +static void +SnodeEventCallback(ZT_Node* node, void* uptr, void* tptr, enum ZT_Event event, const void* metaData) { - reinterpret_cast(uptr)->nodeEventCallback(event,metaData); + reinterpret_cast(uptr)->nodeEventCallback(event, metaData); } -static void SnodeStatePutFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type, - const uint64_t id[2],const void *data,int len) +static void SnodeStatePutFunction( + ZT_Node* node, + void* uptr, + void* tptr, + enum ZT_StateObjectType type, + const uint64_t id[2], + const void* data, + int len) { - reinterpret_cast(uptr)->nodeStatePutFunction(type,id,data,len); + reinterpret_cast(uptr)->nodeStatePutFunction(type, id, data, len); } -static int SnodeStateGetFunction(ZT_Node *node,void *uptr,void *tptr,enum ZT_StateObjectType type, - const uint64_t id[2],void *data,unsigned int maxlen) +static int SnodeStateGetFunction( + ZT_Node* node, + void* uptr, + void* tptr, + enum ZT_StateObjectType type, + const uint64_t id[2], + void* data, + unsigned int maxlen) { - return reinterpret_cast(uptr)->nodeStateGetFunction(type,id,data,maxlen); + return reinterpret_cast(uptr)->nodeStateGetFunction(type, id, data, maxlen); } -static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,void *tptr,int64_t localSocket, - const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl) +static int SnodeWirePacketSendFunction( + ZT_Node* node, + void* uptr, + void* tptr, + int64_t localSocket, + const struct sockaddr_storage* addr, + const void* data, + unsigned int len, + unsigned int ttl) { - return reinterpret_cast(uptr)->nodeWirePacketSendFunction(localSocket,addr,data,len,ttl); + return reinterpret_cast(uptr) + ->nodeWirePacketSendFunction(localSocket, addr, data, len, ttl); } -static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t nwid, - void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len) +static void SnodeVirtualNetworkFrameFunction( + ZT_Node* node, + void* uptr, + void* tptr, + uint64_t nwid, + void** nuptr, + uint64_t sourceMac, + uint64_t destMac, + unsigned int etherType, + unsigned int vlanId, + const void* data, + unsigned int len) { - reinterpret_cast(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); + reinterpret_cast(uptr)->nodeVirtualNetworkFrameFunction( + nwid, + nuptr, + sourceMac, + destMac, + etherType, + vlanId, + data, + len); } -static int SnodePathCheckFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int64_t localSocket, - const struct sockaddr_storage *remoteAddr) +static int SnodePathCheckFunction( + ZT_Node* node, + void* uptr, + void* tptr, + uint64_t ztaddr, + int64_t localSocket, + const struct sockaddr_storage* remoteAddr) { - return reinterpret_cast(uptr)->nodePathCheckFunction(ztaddr,localSocket,remoteAddr); + return reinterpret_cast(uptr)->nodePathCheckFunction( + ztaddr, + localSocket, + remoteAddr); } -static int SnodePathLookupFunction(ZT_Node *node,void *uptr,void *tptr,uint64_t ztaddr,int family,struct sockaddr_storage *result) +static int SnodePathLookupFunction( + ZT_Node* node, + void* uptr, + void* tptr, + uint64_t ztaddr, + int family, + struct sockaddr_storage* result) { - return reinterpret_cast(uptr)->nodePathLookupFunction(ztaddr,family,result); + return reinterpret_cast(uptr)->nodePathLookupFunction(ztaddr, family, result); } -static void StapFrameHandler(void *uptr,void *tptr,uint64_t nwid,const MAC &from,const MAC &to, - unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len) +static void StapFrameHandler( + void* uptr, + void* tptr, + uint64_t nwid, + const MAC& from, + const MAC& to, + unsigned int etherType, + unsigned int vlanId, + const void* data, + unsigned int len) { - reinterpret_cast(uptr)->tapFrameHandler(nwid,from,to,etherType,vlanId,data,len); + reinterpret_cast(uptr) + ->tapFrameHandler(nwid, from, to, etherType, vlanId, data, len); } std::string NodeService::platformDefaultHomePath() @@ -1349,14 +1776,19 @@ std::string NodeService::platformDefaultHomePath() return OSUtils::platformDefaultHomePath(); } -NodeService *NodeService::newInstance(const char *hp,unsigned int port) { return new NodeServiceImpl(hp,port); } -NodeService::~NodeService() {} +NodeService* NodeService::newInstance(const char* hp, unsigned int port) +{ + return new NodeServiceImpl(hp, port); +} +NodeService::~NodeService() +{ +} ////////////////////////////////////////////////////////////////////////////// // Service // ////////////////////////////////////////////////////////////////////////////// -NodeService *service; +NodeService* service; // Lock to guard access to ZeroTier core service Mutex serviceLock; @@ -1365,26 +1797,27 @@ Mutex serviceLock; #if defined(__WINDOWS__) DWORD WINAPI _runNodeService(LPVOID arg) #else -void *_runNodeService(void *arg) +void* _runNodeService(void* arg) #endif { #if defined(__APPLE__) pthread_setname_np(ZTS_SERVICE_THREAD_NAME); #endif - struct serviceParameters *params = (struct serviceParameters *)arg; + struct serviceParameters* params = (struct serviceParameters*)arg; int err; try { - std::vector hpsp(OSUtils::split(params->path.c_str(), ZT_PATH_SEPARATOR_S,"","")); + std::vector hpsp( + OSUtils::split(params->path.c_str(), ZT_PATH_SEPARATOR_S, "", "")); std::string ptmp; if (params->path[0] == ZT_PATH_SEPARATOR) { ptmp.push_back(ZT_PATH_SEPARATOR); } - for (std::vector::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) { + for (std::vector::iterator pi(hpsp.begin()); pi != hpsp.end(); ++pi) { if (ptmp.length() > 0) { ptmp.push_back(ZT_PATH_SEPARATOR); } ptmp.append(*pi); - if ((*pi != ".")&&(*pi != "..")) { + if ((*pi != ".") && (*pi != "..")) { if (OSUtils::mkdir(ptmp) == false) { DEBUG_ERROR("home path does not exist, and could not create"); err = true; @@ -1392,59 +1825,75 @@ void *_runNodeService(void *arg) } } } - for(;;) { + for (;;) { serviceLock.lock(); - service = NodeService::newInstance(params->path.c_str(),params->port); + service = NodeService::newInstance(params->path.c_str(), params->port); service->_userProvidedPort = params->port; service->_userProvidedPath = params->path; - if (params->publicIdentityStr[0] != '\0' && params->secretIdentityStr[0] != '\0' && params->path.length() == 0) { - memcpy(service->_userProvidedPublicIdentity, params->publicIdentityStr, strlen(params->publicIdentityStr)); - memcpy(service->_userProvidedSecretIdentity, params->secretIdentityStr, strlen(params->secretIdentityStr)); + if (params->publicIdentityStr[0] != '\0' && params->secretIdentityStr[0] != '\0' + && params->path.length() == 0) { + memcpy( + service->_userProvidedPublicIdentity, + params->publicIdentityStr, + strlen(params->publicIdentityStr)); + memcpy( + service->_userProvidedSecretIdentity, + params->secretIdentityStr, + strlen(params->secretIdentityStr)); } serviceLock.unlock(); - switch(service->run()) { + switch (service->run()) { case NodeService::ONE_STILL_RUNNING: case NodeService::ONE_NORMAL_TERMINATION: - _enqueueEvent(ZTS_EVENT_NODE_NORMAL_TERMINATION,NULL); + _enqueueEvent(ZTS_EVENT_NODE_NORMAL_TERMINATION, NULL); break; case NodeService::ONE_UNRECOVERABLE_ERROR: DEBUG_ERROR("fatal error: %s", service->fatalErrorMessage().c_str()); err = true; - _enqueueEvent(ZTS_EVENT_NODE_UNRECOVERABLE_ERROR,NULL); + _enqueueEvent(ZTS_EVENT_NODE_UNRECOVERABLE_ERROR, NULL); break; case NodeService::ONE_IDENTITY_COLLISION: { err = true; delete service; - service = (NodeService *)0; + service = (NodeService*)0; std::string oldid; - OSUtils::readFile((params->path + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid); + OSUtils::readFile( + (params->path + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(), + oldid); if (oldid.length()) { - OSUtils::writeFile((params->path + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid); - OSUtils::rm((params->path + ZT_PATH_SEPARATOR_S + "identity.secret").c_str()); - OSUtils::rm((params->path + ZT_PATH_SEPARATOR_S + "identity.public").c_str()); + OSUtils::writeFile( + (params->path + ZT_PATH_SEPARATOR_S + + "identity.secret.saved_after_collision") + .c_str(), + oldid); + OSUtils::rm( + (params->path + ZT_PATH_SEPARATOR_S + "identity.secret").c_str()); + OSUtils::rm( + (params->path + ZT_PATH_SEPARATOR_S + "identity.public").c_str()); } - _enqueueEvent(ZTS_EVENT_NODE_IDENTITY_COLLISION,NULL); - } continue; // restart! + _enqueueEvent(ZTS_EVENT_NODE_IDENTITY_COLLISION, NULL); + } + continue; // restart! } - break; // terminate loop -- normally we don't keep restarting + break; // terminate loop -- normally we don't keep restarting } serviceLock.lock(); _clrState(ZTS_STATE_NODE_RUNNING); delete service; - service = (NodeService *)0; + service = (NodeService*)0; serviceLock.unlock(); - _enqueueEvent(ZTS_EVENT_NODE_DOWN,NULL); + _enqueueEvent(ZTS_EVENT_NODE_DOWN, NULL); } - catch ( ... ) { + catch (...) { DEBUG_ERROR("unexpected exception starting ZeroTier instance"); } delete params; - zts_delay_ms(ZTS_CALLBACK_PROCESSING_INTERVAL*2); + zts_delay_ms(ZTS_CALLBACK_PROCESSING_INTERVAL * 2); #ifndef __WINDOWS__ pthread_exit(0); #endif return NULL; } -} // namespace ZeroTier +} // namespace ZeroTier diff --git a/src/NodeService.hpp b/src/NodeService.hpp index 813567c..c9b0068 100644 --- a/src/NodeService.hpp +++ b/src/NodeService.hpp @@ -20,27 +20,27 @@ #ifndef ZT_NODE_SERVICE_HPP #define ZT_NODE_SERVICE_HPP +#include "Constants.hpp" +#include "InetAddress.hpp" +#include "Mutex.hpp" +#include "Node.hpp" +#include "ZeroTierSockets.h" + #include #include -#include "Constants.hpp" -#include "Node.hpp" -#include "InetAddress.hpp" -#include "Mutex.hpp" -#include "ZeroTierSockets.h" - -#define ZTS_SERVICE_THREAD_NAME "ZTServiceThread" -#define ZTS_EVENT_CALLBACK_THREAD_NAME "ZTEventCallbackThread" +#define ZTS_SERVICE_THREAD_NAME "ZTServiceThread" +#define ZTS_EVENT_CALLBACK_THREAD_NAME "ZTEventCallbackThread" // Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also // bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi. -#define ZT_IF_METRIC 5000 +#define ZT_IF_METRIC 5000 // How often to check for new multicast subscriptions on a tap device -#define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000 +#define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000 // How often to check for local interface addresses #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000 #ifdef __WINDOWS__ -#include + #include #endif namespace ZeroTier { @@ -48,10 +48,8 @@ namespace ZeroTier { /** * Local service for ZeroTier One as system VPN/NFV provider */ -class NodeService -{ -public: - +class NodeService { + public: uint16_t _userProvidedPort; std::string _userProvidedPath; char _userProvidedPublicIdentity[ZT_IDENTITY_STRING_BUFFER_LENGTH]; @@ -60,8 +58,7 @@ public: /** * Returned by node main if/when it terminates */ - enum ReasonForTermination - { + enum ReasonForTermination { /** * Instance is still running */ @@ -86,8 +83,7 @@ public: /** * Local settings for each network */ - struct NetworkSettings - { + struct NetworkSettings { /** * Allow this network to configure IP addresses and routes? */ @@ -128,7 +124,7 @@ public: * @param hp Home path * @param port TCP and UDP port for packets and HTTP control (if 0, pick random port) */ - static NodeService *newInstance(const char *hp,unsigned int port); + static NodeService* newInstance(const char* hp, unsigned int port); virtual ~NodeService(); @@ -152,7 +148,8 @@ public: virtual std::string fatalErrorMessage() const = 0; /** - * @return System device name corresponding with a given ZeroTier network ID or empty string if not opened yet or network ID not found + * @return System device name corresponding with a given ZeroTier network ID or empty string if + * not opened yet or network ID not found */ virtual std::string portDeviceName(uint64_t nwid) const = 0; @@ -164,16 +161,16 @@ public: /** * @return Reference to the Node */ - virtual Node * getNode() = 0; + virtual Node* getNode() = 0; /** * Fills out a structure with network-specific route information */ - virtual void getRoutes(uint64_t nwid, void *routeArray, unsigned int *numRoutes) = 0; + virtual void getRoutes(uint64_t nwid, void* routeArray, unsigned int* numRoutes) = 0; virtual void join(uint64_t nwid) = 0; virtual void leave(uint64_t nwid) = 0; - virtual void getIdentity(char *key_pair_str, uint16_t *key_buf_len) = 0; + virtual void getIdentity(char* key_pair_str, uint16_t* key_buf_len) = 0; /** * Terminate background service (can be called from other threads) @@ -187,23 +184,32 @@ public: * @param settings Buffer to fill with local network settings * @return True if network was found and settings is filled */ - virtual bool getNetworkSettings(const uint64_t nwid,NetworkSettings &settings) const = 0; + virtual bool getNetworkSettings(const uint64_t nwid, NetworkSettings& settings) const = 0; /** * @return True if service is still running */ - inline bool isRunning() const { return (this->reasonForTermination() == ONE_STILL_RUNNING); } + inline bool isRunning() const + { + return (this->reasonForTermination() == ONE_STILL_RUNNING); + } -protected: - NodeService() {} + protected: + NodeService() + { + } -private: - NodeService(const NodeService &one) {} - inline NodeService &operator=(const NodeService &one) { return *this; } + private: + NodeService(const NodeService& one) + { + } + inline NodeService& operator=(const NodeService& one) + { + return *this; + } }; -struct serviceParameters -{ +struct serviceParameters { int port; std::string path; char publicIdentityStr[ZT_IDENTITY_STRING_BUFFER_LENGTH]; @@ -216,9 +222,9 @@ DWORD WINAPI _runNodeService(LPVOID arg); /** * NodeService thread */ -void *_runNodeService(void *arg); +void* _runNodeService(void* arg); #endif -} // namespace ZeroTier +} // namespace ZeroTier #endif diff --git a/src/Signals.cpp b/src/Signals.cpp index e604230..0341e66 100644 --- a/src/Signals.cpp +++ b/src/Signals.cpp @@ -18,22 +18,23 @@ */ #ifdef ZTS_ENABLE_PYTHON - /** - * In some situations (Python comes to mind) a signal may not make its - * way to libzt, for this reason we make sure to define a custom signal - * handler that can at least process SIGTERMs - */ + /** + * In some situations (Python comes to mind) a signal may not make its + * way to libzt, for this reason we make sure to define a custom signal + * handler that can at least process SIGTERMs + */ #define ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS 1 #endif #ifdef ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS -#include "ZeroTierSockets.h" -#include "Signals.hpp" + #include "Signals.hpp" -#include -#include -#include + #include "ZeroTierSockets.h" + + #include + #include + #include void _signal_handler(int signal) { @@ -41,24 +42,24 @@ void _signal_handler(int signal) switch(signal) { case SIGINT: - fprintf(stderr, "SIGINT\n"); - break; + fprintf(stderr, "SIGINT\n"); + break; case SIGABRT: - fprintf(stderr, "SIGABRT\n"); - break; + fprintf(stderr, "SIGABRT\n"); + break; case SIGILL: - fprintf(stderr, "SIGILL\n"); - break; + fprintf(stderr, "SIGILL\n"); + break; case SIGSEGV: - fprintf(stderr, "SIGSEGV\n"); - break; + fprintf(stderr, "SIGSEGV\n"); + break; case SIGFPE: - fprintf(stderr, "SIGFPE\n"); - break; + fprintf(stderr, "SIGFPE\n"); + break; case SIGTERM: default: - fprintf(stderr, "SIGTERM\n"); - break; + fprintf(stderr, "SIGTERM\n"); + break; } */ exit(signal); diff --git a/src/Signals.hpp b/src/Signals.hpp index 1d360d5..b022ceb 100644 --- a/src/Signals.hpp +++ b/src/Signals.hpp @@ -36,6 +36,6 @@ void _signal_handler(int signal); */ void _install_signal_handlers(); -#endif // ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS +#endif // ZTS_ENABLE_CUSTOM_SIGNAL_HANDLERS -#endif // _H +#endif // _H diff --git a/src/Sockets.cpp b/src/Sockets.cpp index 6c0c3ab..568b51a 100644 --- a/src/Sockets.cpp +++ b/src/Sockets.cpp @@ -18,14 +18,14 @@ */ #include "lwip/sockets.h" -#include "lwip/def.h" -#include "lwip/inet.h" -#include "lwip/stats.h" -#include "lwip/netdb.h" -#include "lwip/dns.h" -#include "lwip/ip_addr.h" #include "ZeroTierSockets.h" +#include "lwip/def.h" +#include "lwip/dns.h" +#include "lwip/inet.h" +#include "lwip/ip_addr.h" +#include "lwip/netdb.h" +#include "lwip/stats.h" #define ZTS_STATE_NODE_RUNNING 0x01 #define ZTS_STATE_STACK_RUNNING 0x02 @@ -45,54 +45,53 @@ extern "C" { int zts_socket(const int socket_family, const int socket_type, const int protocol) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_socket(socket_family, socket_type, protocol); } -int zts_connect(int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen) +int zts_connect(int fd, 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; } - if (!addr) { + if (! addr) { return ZTS_ERR_ARG; } if (addrlen > (int)sizeof(struct zts_sockaddr_storage) - || addrlen < (int)sizeof(struct zts_sockaddr_in)) { + || addrlen < (int)sizeof(struct zts_sockaddr_in)) { return ZTS_ERR_ARG; } return lwip_connect(fd, (sockaddr*)addr, addrlen); } -int zts_connect_easy(int fd, int family, char *ipstr, int port, int timeout_ms) { +int zts_connect_easy(int fd, int family, char* ipstr, int port, int timeout_ms) +{ if (timeout_ms < 0) { return ZTS_ERR_ARG; } if (timeout_ms == 0) { - timeout_ms = 30000; // Default + timeout_ms = 30000; // Default } - int div = 4; // Must be > 0, Four connection attempts per second + int div = 4; // Must be > 0, Four connection attempts per second int n_tries = (timeout_ms / 1000) * div; int connect_delay = 1000 / div; int err = ZTS_ERR_SOCKET; zts_socklen_t addrlen = 0; struct zts_sockaddr_storage ss; - struct zts_sockaddr *sa = NULL; + struct zts_sockaddr* sa = NULL; if (family == ZTS_AF_INET) { addrlen = sizeof(ss); - ipstr2sockaddr( - family, ipstr, port, (struct zts_sockaddr *)&ss, &addrlen); - sa = (struct zts_sockaddr *)&ss; + ipstr2sockaddr(family, ipstr, port, (struct zts_sockaddr*)&ss, &addrlen); + sa = (struct zts_sockaddr*)&ss; } if (family == ZTS_AF_INET6) { addrlen = sizeof(ss); - ipstr2sockaddr( - family, ipstr, port, (struct zts_sockaddr *)&ss, &addrlen); - sa = (struct zts_sockaddr *)&ss; + ipstr2sockaddr(family, ipstr, port, (struct zts_sockaddr*)&ss, &addrlen); + sa = (struct zts_sockaddr*)&ss; } if (addrlen > 0 && sa != NULL) { if (zts_get_blocking(fd)) { @@ -100,44 +99,42 @@ int zts_connect_easy(int fd, int family, char *ipstr, int port, int timeout_ms) err = zts_connect(fd, sa, addrlen); zts_delay_ms(connect_delay); n_tries--; - } - while ((err < 0) && (zts_errno != 0) && (n_tries > 0)); + } while ((err < 0) && (zts_errno != 0) && (n_tries > 0)); } return err; } return ZTS_ERR_ARG; } -int zts_bind(int fd, const struct zts_sockaddr *addr, zts_socklen_t addrlen) +int zts_bind(int fd, 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; } - if (!addr) { + if (! addr) { return ZTS_ERR_ARG; } if (addrlen > (int)sizeof(struct zts_sockaddr_storage) - || addrlen < (int)sizeof(struct zts_sockaddr_in)) { + || addrlen < (int)sizeof(struct zts_sockaddr_in)) { return ZTS_ERR_ARG; } return lwip_bind(fd, (sockaddr*)addr, addrlen); } -int zts_bind_easy(int fd, int family, char *ipstr, int port) { +int zts_bind_easy(int fd, int family, char* ipstr, int port) +{ if (family == ZTS_AF_INET) { struct zts_sockaddr_in in4; zts_socklen_t addrlen = sizeof(in4); - ipstr2sockaddr( - family, ipstr, port, (struct zts_sockaddr *)&in4, &addrlen); - struct zts_sockaddr *sa = (struct zts_sockaddr *)&in4; + ipstr2sockaddr(family, ipstr, port, (struct zts_sockaddr*)&in4, &addrlen); + struct zts_sockaddr* sa = (struct zts_sockaddr*)&in4; return zts_bind(fd, sa, addrlen); } if (family == ZTS_AF_INET6) { struct zts_sockaddr_in6 in6; zts_socklen_t addrlen = sizeof(in6); - ipstr2sockaddr( - family, ipstr, port, (struct zts_sockaddr *)&in6, &addrlen); - struct zts_sockaddr *sa = (struct zts_sockaddr *)&in6; + ipstr2sockaddr(family, ipstr, port, (struct zts_sockaddr*)&in6, &addrlen); + struct zts_sockaddr* sa = (struct zts_sockaddr*)&in6; return zts_bind(fd, sa, addrlen); } return ZTS_ERR_ARG; @@ -145,21 +142,21 @@ int zts_bind_easy(int fd, int family, char *ipstr, int port) { int zts_listen(int fd, int backlog) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_listen(fd, backlog); } -int zts_accept(int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen) +int zts_accept(int fd, 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 lwip_accept(fd, (sockaddr*)addr, (socklen_t*)addrlen); } -int zts_accept_easy(int fd, char *remoteIpStr, int len, int *port) +int zts_accept_easy(int fd, char* remoteIpStr, int len, int* port) { if (len != ZTS_INET6_ADDRSTRLEN) { return ZTS_ERR_ARG; @@ -171,65 +168,61 @@ int zts_accept_easy(int fd, char *remoteIpStr, int len, int *port) zts_socklen_t addrlen = sizeof(ss); int acc_fd = zts_accept(fd, (zts_sockaddr*)&ss, (zts_socklen_t*)&addrlen); - struct zts_sockaddr *sa = (struct zts_sockaddr *)&ss; + struct zts_sockaddr* sa = (struct zts_sockaddr*)&ss; if (sa->sa_family == ZTS_AF_INET) { - struct zts_sockaddr_in *in4 = (struct zts_sockaddr_in*)sa; - zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), - remoteIpStr, ZTS_INET_ADDRSTRLEN); + struct zts_sockaddr_in* in4 = (struct zts_sockaddr_in*)sa; + zts_inet_ntop(ZTS_AF_INET, &(in4->sin_addr), remoteIpStr, ZTS_INET_ADDRSTRLEN); *port = ntohs(in4->sin_port); } if (sa->sa_family == ZTS_AF_INET6) { - struct zts_sockaddr_in6 *in6 = (struct zts_sockaddr_in6*)sa; - zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), - remoteIpStr, ZTS_INET6_ADDRSTRLEN); + struct zts_sockaddr_in6* in6 = (struct zts_sockaddr_in6*)sa; + zts_inet_ntop(ZTS_AF_INET6, &(in6->sin6_addr), remoteIpStr, ZTS_INET6_ADDRSTRLEN); *port = ntohs(in6->sin6_port); } return acc_fd; } -int zts_setsockopt( - int fd, int level, int optname, const void *optval,zts_socklen_t optlen) +int zts_setsockopt(int fd, int level, int optname, const void* optval, zts_socklen_t optlen) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_setsockopt(fd, level, optname, optval, optlen); } -int zts_getsockopt( - int fd, int level, int optname, void *optval, zts_socklen_t *optlen) +int zts_getsockopt(int fd, int level, int optname, void* optval, zts_socklen_t* optlen) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_getsockopt(fd, level, optname, optval, (socklen_t*)optlen); } -int zts_getsockname(int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen) +int zts_getsockname(int fd, 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; } - if (!addr) { + if (! addr) { return ZTS_ERR_ARG; } if (*addrlen > (int)sizeof(struct zts_sockaddr_storage) - || *addrlen < (int)sizeof(struct zts_sockaddr_in)) { + || *addrlen < (int)sizeof(struct zts_sockaddr_in)) { return ZTS_ERR_ARG; } return lwip_getsockname(fd, (sockaddr*)addr, (socklen_t*)addrlen); } -int zts_getpeername(int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen) +int zts_getpeername(int fd, 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; } - if (!addr) { + if (! addr) { return ZTS_ERR_ARG; } if (*addrlen > (int)sizeof(struct zts_sockaddr_storage) - || *addrlen < (int)sizeof(struct zts_sockaddr_in)) { + || *addrlen < (int)sizeof(struct zts_sockaddr_in)) { return ZTS_ERR_ARG; } return lwip_getpeername(fd, (sockaddr*)addr, (socklen_t*)addrlen); @@ -237,156 +230,172 @@ int zts_getpeername(int fd, struct zts_sockaddr *addr, zts_socklen_t *addrlen) int zts_close(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_close(fd); } int 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) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_select( - nfds, (fd_set*)readfds, (fd_set*)writefds, (fd_set*)exceptfds, (timeval*)timeout); + nfds, + (fd_set*)readfds, + (fd_set*)writefds, + (fd_set*)exceptfds, + (timeval*)timeout); } int zts_fcntl(int fd, int cmd, int flags) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_fcntl(fd, cmd, flags); } -int zts_poll(struct zts_pollfd *fds, nfds_t nfds, int timeout) +int zts_poll(struct zts_pollfd* fds, nfds_t nfds, int timeout) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_poll((pollfd*)fds, nfds, timeout); } -int zts_ioctl(int fd, unsigned long request, void *argp) +int zts_ioctl(int fd, unsigned long request, void* argp) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - if (!argp) { + if (! argp) { return ZTS_ERR_ARG; } return lwip_ioctl(fd, request, argp); } -ssize_t zts_send(int fd, const void *buf, size_t len, int flags) +ssize_t zts_send(int fd, const void* buf, size_t len, int flags) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - if (!buf) { + if (! buf) { return ZTS_ERR_ARG; } return lwip_send(fd, buf, len, flags); } -ssize_t zts_sendto(int fd, const void *buf, size_t len, int flags, - const struct zts_sockaddr *addr,zts_socklen_t addrlen) +ssize_t zts_sendto( + int fd, + const void* buf, + size_t len, + int flags, + const struct zts_sockaddr* addr, + zts_socklen_t addrlen) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - if (!addr || !buf) { + if (! addr || ! buf) { return ZTS_ERR_ARG; } if (addrlen > (int)sizeof(struct zts_sockaddr_storage) - || addrlen < (int)sizeof(struct zts_sockaddr_in)) { + || addrlen < (int)sizeof(struct zts_sockaddr_in)) { return ZTS_ERR_ARG; } return lwip_sendto(fd, buf, len, flags, (sockaddr*)addr, addrlen); } -ssize_t zts_sendmsg(int fd, const struct zts_msghdr *msg, int flags) +ssize_t zts_sendmsg(int fd, const struct zts_msghdr* msg, int flags) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - return lwip_sendmsg(fd, (const struct msghdr *)msg, flags); + return lwip_sendmsg(fd, (const struct msghdr*)msg, flags); } -ssize_t zts_recv(int fd, void *buf, size_t len, int flags) +ssize_t zts_recv(int fd, void* buf, size_t len, int flags) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - if (!buf) { + if (! buf) { return ZTS_ERR_ARG; } return lwip_recv(fd, buf, len, flags); } -ssize_t zts_recvfrom(int fd, void *buf, size_t len, int flags, - struct zts_sockaddr *addr, zts_socklen_t *addrlen) +ssize_t zts_recvfrom( + int fd, + void* buf, + size_t len, + int flags, + struct zts_sockaddr* addr, + zts_socklen_t* addrlen) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - if (!buf) { + if (! buf) { return ZTS_ERR_ARG; } - return lwip_recvfrom( - fd, buf, len, flags, (sockaddr*)addr, (socklen_t*)addrlen); + return lwip_recvfrom(fd, buf, len, flags, (sockaddr*)addr, (socklen_t*)addrlen); } -ssize_t zts_recvmsg(int fd, struct zts_msghdr *msg, int flags) +ssize_t zts_recvmsg(int fd, struct zts_msghdr* msg, int flags) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - if (!msg) { + if (! msg) { return ZTS_ERR_ARG; } - return lwip_recvmsg(fd, (struct msghdr *)msg, flags); + return lwip_recvmsg(fd, (struct msghdr*)msg, flags); } -ssize_t zts_read(int fd, void *buf, size_t len) +ssize_t zts_read(int fd, void* buf, size_t len) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - if (!buf) { + if (! buf) { return ZTS_ERR_ARG; } return lwip_read(fd, buf, len); } -ssize_t zts_readv(int fd, const struct zts_iovec *iov, int iovcnt) +ssize_t zts_readv(int fd, const struct zts_iovec* iov, int iovcnt) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_readv(fd, (iovec*)iov, iovcnt); } -ssize_t zts_write(int fd, const void *buf, size_t len) +ssize_t zts_write(int fd, const void* buf, size_t len) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } - if (!buf) { + if (! buf) { return ZTS_ERR_ARG; } return lwip_write(fd, buf, len); } -ssize_t zts_writev(int fd, const struct zts_iovec *iov, int iovcnt) +ssize_t zts_writev(int fd, const struct zts_iovec* iov, int iovcnt) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } @@ -395,72 +404,76 @@ ssize_t zts_writev(int fd, const struct zts_iovec *iov, int iovcnt) int zts_shutdown(int fd, int how) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } return lwip_shutdown(fd, how); } -struct zts_hostent *zts_gethostbyname(const char *name) +struct zts_hostent* zts_gethostbyname(const char* name) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return NULL; } - if (!name) { + if (! name) { return NULL; } - return (struct zts_hostent *)lwip_gethostbyname(name); + return (struct zts_hostent*)lwip_gethostbyname(name); } -int zts_dns_set_server(uint8_t index, const zts_ip_addr *addr) +int zts_dns_set_server(uint8_t index, const zts_ip_addr* addr) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (index >= DNS_MAX_SERVERS) { return ZTS_ERR_ARG; } - if (!addr) { + if (! addr) { return ZTS_ERR_ARG; } - dns_setserver(index, (const ip_addr_t *)addr); + dns_setserver(index, (const ip_addr_t*)addr); return ZTS_ERR_OK; } -const zts_ip_addr *zts_dns_get_server(uint8_t index) +const zts_ip_addr* zts_dns_get_server(uint8_t index) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return NULL; } if (index >= DNS_MAX_SERVERS) { return NULL; } - return (const zts_ip_addr *)dns_getserver(index); + return (const zts_ip_addr*)dns_getserver(index); } -char *zts_ipaddr_ntoa(const zts_ip_addr *addr) +char* zts_ipaddr_ntoa(const zts_ip_addr* addr) { - return ipaddr_ntoa((ip_addr_t *)addr); + return ipaddr_ntoa((ip_addr_t*)addr); } -int zts_ipaddr_aton(const char *cp, zts_ip_addr *addr) +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( - int family, const void *src, char *dst, zts_socklen_t size) +const char* zts_inet_ntop(int family, const void* src, char* dst, zts_socklen_t size) { - return lwip_inet_ntop(family,src,dst,size); + return lwip_inet_ntop(family, src, dst, size); } -int zts_inet_pton(int family, const char *src, void *dst) +int zts_inet_pton(int family, const char* src, void* dst) { - return lwip_inet_pton(family,src,dst); + return lwip_inet_pton(family, src, dst); } int ipstr2sockaddr( - int family, char *src_ipstr, int port, struct zts_sockaddr *dest_addr, zts_socklen_t *addrlen) { + int family, + char* src_ipstr, + int port, + struct zts_sockaddr* dest_addr, + zts_socklen_t* addrlen) +{ if (family == ZTS_AF_INET) { struct zts_sockaddr_in in4; in4.sin_port = htons(port); @@ -470,7 +483,7 @@ int ipstr2sockaddr( #else zts_inet_pton(family, src_ipstr, &(in4.sin_addr.s_addr)); #endif - dest_addr = (struct zts_sockaddr *)&in4; + dest_addr = (struct zts_sockaddr*)&in4; *addrlen = sizeof(in4); return ZTS_ERR_OK; } @@ -483,7 +496,7 @@ int ipstr2sockaddr( #else zts_inet_pton(family, src_ipstr, &(in6.sin6_addr)); #endif - dest_addr = (struct zts_sockaddr *)&in6; + dest_addr = (struct zts_sockaddr*)&in6; *addrlen = sizeof(in6); return ZTS_ERR_OK; } @@ -495,39 +508,39 @@ int ipstr2sockaddr( //----------------------------------------------------------------------------// /** -* Helper functions that simplify API wrapper generation and usage in other -* non-C-like languages. Use simple integer types instead of bit flags, limit -* the number of operations each function performs, prevent the user from -* needing to manipulate the content of structures in a non-native language. -*/ + * Helper functions that simplify API wrapper generation and usage in other + * non-C-like languages. Use simple integer types instead of bit flags, limit + * the number of operations each function performs, prevent the user from + * needing to manipulate the content of structures in a non-native language. + */ -int zts_set_no_delay(int fd, int enabled) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { +int zts_set_no_delay(int fd, int enabled) +{ + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (enabled != 0 && enabled != 1) { return ZTS_ERR_ARG; } - return zts_setsockopt( - fd, ZTS_IPPROTO_TCP, ZTS_TCP_NODELAY, (void *)&enabled, sizeof(int)); + return zts_setsockopt(fd, ZTS_IPPROTO_TCP, ZTS_TCP_NODELAY, (void*)&enabled, sizeof(int)); } int zts_get_no_delay(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int err, optval = 0; zts_socklen_t len = sizeof(optval); - if ((err = zts_getsockopt( - fd, ZTS_IPPROTO_TCP, ZTS_TCP_NODELAY, (void *)&optval, &len)) < 0) { + if ((err = zts_getsockopt(fd, ZTS_IPPROTO_TCP, ZTS_TCP_NODELAY, (void*)&optval, &len)) < 0) { return err; } return optval != 0; } -int zts_set_linger(int fd, int enabled, int value) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { +int zts_set_linger(int fd, int enabled, int value) +{ + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (enabled != 0 && enabled != 1) { @@ -539,20 +552,18 @@ int zts_set_linger(int fd, int enabled, int value) { struct zts_linger linger; linger.l_onoff = enabled; linger.l_linger = value; - return zts_setsockopt( - fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void *)&linger, sizeof(linger)); + return zts_setsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void*)&linger, sizeof(linger)); } int zts_get_linger_enabled(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int err; struct zts_linger linger; zts_socklen_t len = sizeof(linger); - if ((err = zts_getsockopt( - fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void *)&linger, &len)) < 0) { + if ((err = zts_getsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void*)&linger, &len)) < 0) { return err; } return linger.l_onoff; @@ -560,14 +571,13 @@ int zts_get_linger_enabled(int fd) int zts_get_linger_value(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int err; struct zts_linger linger; zts_socklen_t len = sizeof(linger); - if ((err = zts_getsockopt( - fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void *)&linger, &len)) < 0) { + if ((err = zts_getsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_LINGER, (void*)&linger, &len)) < 0) { return err; } return linger.l_linger; @@ -575,26 +585,24 @@ int zts_get_linger_value(int fd) int zts_set_reuse_addr(int fd, int enabled) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (enabled != 0 && enabled != 1) { return ZTS_ERR_ARG; } - return zts_setsockopt( - fd, ZTS_SOL_SOCKET, ZTS_SO_REUSEADDR, (void *)&enabled, sizeof(enabled)); + return zts_setsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_REUSEADDR, (void*)&enabled, sizeof(enabled)); } int zts_get_reuse_addr(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int err; int optval = 0; zts_socklen_t optlen = sizeof(optval); - if ((err = zts_getsockopt( - fd, ZTS_SOL_SOCKET, ZTS_SO_REUSEADDR, (void *)&optval, &optlen)) < 0) { + if ((err = zts_getsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_REUSEADDR, (void*)&optval, &optlen)) < 0) { return err; } return optval != 0; @@ -602,7 +610,7 @@ int zts_get_reuse_addr(int fd) int zts_set_recv_timeout(int fd, int seconds, int microseconds) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (seconds < 0 || microseconds < 0) { @@ -611,28 +619,26 @@ int zts_set_recv_timeout(int fd, int seconds, int microseconds) struct timeval tv; tv.tv_sec = seconds; tv.tv_usec = microseconds; - return zts_setsockopt( - fd, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, sizeof(tv)); + return zts_setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, sizeof(tv)); } int zts_get_recv_timeout(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } struct timeval tv; zts_socklen_t optlen = sizeof(tv); int err; - if ((err = zts_getsockopt( - fd, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, &optlen)) < 0) { + if ((err = zts_getsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &optlen)) < 0) { return err; } - return tv.tv_sec; // TODO microseconds + return tv.tv_sec; // TODO microseconds } int zts_set_send_timeout(int fd, int seconds, int microseconds) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (seconds < 0 || microseconds < 0) { @@ -641,46 +647,42 @@ int zts_set_send_timeout(int fd, int seconds, int microseconds) struct timeval tv; tv.tv_sec = seconds; tv.tv_usec = microseconds; - return zts_setsockopt( - fd, SOL_SOCKET, SO_SNDTIMEO, (void *)&tv, sizeof(tv)); + return zts_setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (void*)&tv, sizeof(tv)); } int zts_get_send_timeout(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } struct zts_timeval tv; zts_socklen_t optlen = sizeof(tv); int err; - if ((err = zts_getsockopt( - fd, SOL_SOCKET, SO_SNDTIMEO, (void *)&tv, &optlen)) < 0) { + if ((err = zts_getsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (void*)&tv, &optlen)) < 0) { return err; } - return tv.tv_sec; // TODO microseconds + return tv.tv_sec; // TODO microseconds } int zts_set_send_buf_size(int fd, int size) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (size < 0) { return ZTS_ERR_ARG; } - return zts_setsockopt( - fd, SOL_SOCKET, SO_SNDBUF, (void *)&size, sizeof(int)); + return zts_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void*)&size, sizeof(int)); } int zts_get_send_buf_size(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int err, optval = 0; zts_socklen_t optlen = sizeof(optval); - if ((err = zts_getsockopt( - fd, SOL_SOCKET, SO_SNDBUF, (char *)&optval, &optlen)) < 0) { + if ((err = zts_getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&optval, &optlen)) < 0) { return err; } return optval; @@ -688,25 +690,23 @@ int zts_get_send_buf_size(int fd) int zts_set_recv_buf_size(int fd, int size) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (size < 0) { return ZTS_ERR_ARG; } - return zts_setsockopt( - fd, SOL_SOCKET, SO_RCVBUF, (void *)&size, sizeof(int)); + return zts_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void*)&size, sizeof(int)); } int zts_get_recv_buf_size(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int err, optval = 0; zts_socklen_t optlen = sizeof(optval); - if ((err = zts_getsockopt( - fd, SOL_SOCKET, SO_RCVBUF, (char *)&optval, &optlen)) < 0) { + if ((err = zts_getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&optval, &optlen)) < 0) { return err; } return optval; @@ -714,7 +714,7 @@ int zts_get_recv_buf_size(int fd) int zts_set_ttl(int fd, int ttl) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (ttl < 0 || ttl > 255) { @@ -725,7 +725,7 @@ int zts_set_ttl(int fd, int ttl) int zts_get_ttl(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int err, ttl = 0; @@ -738,14 +738,14 @@ int zts_get_ttl(int fd) int zts_set_blocking(int fd, int enabled) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (enabled != 0 && enabled != 1) { return ZTS_ERR_ARG; } int flags = zts_fcntl(fd, ZTS_F_GETFL, 0); - if (!enabled) { + if (! enabled) { return zts_fcntl(fd, ZTS_F_SETFL, flags | ZTS_O_NONBLOCK); } else { @@ -756,40 +756,38 @@ int zts_set_blocking(int fd, int enabled) int zts_get_blocking(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int flags = zts_fcntl(fd, ZTS_F_GETFL, 0); if (flags < 0) { return flags; } - return !(flags & ZTS_O_NONBLOCK); + return ! (flags & ZTS_O_NONBLOCK); } int zts_set_keepalive(int fd, int enabled) { // - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } if (enabled != 0 && enabled != 1) { return ZTS_ERR_ARG; } int keepalive = enabled; - return zts_setsockopt( - fd, ZTS_SOL_SOCKET, ZTS_SO_KEEPALIVE, &keepalive , sizeof(keepalive)); + return zts_setsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_KEEPALIVE, &keepalive, sizeof(keepalive)); } int zts_get_keepalive(int fd) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } int err; int optval = 0; zts_socklen_t optlen = sizeof(optval); - if ((err = zts_getsockopt( - fd, ZTS_SOL_SOCKET, ZTS_SO_KEEPALIVE, (void *)&optval, &optlen)) < 0) { + if ((err = zts_getsockopt(fd, ZTS_SOL_SOCKET, ZTS_SO_KEEPALIVE, (void*)&optval, &optlen)) < 0) { return err; } return optval != 0; @@ -803,13 +801,13 @@ int zts_get_keepalive(int fd) extern struct stats_ lwip_stats; -int zts_get_all_stats(struct zts_stats *statsDest) +int zts_get_all_stats(struct zts_stats* statsDest) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } -#if LWIP_STATS - if (!statsDest) { + #if LWIP_STATS + if (! statsDest) { return ZTS_ERR_ARG; } memset(statsDest, 0, sizeof(struct zts_stats)); @@ -819,7 +817,7 @@ int zts_get_all_stats(struct zts_stats *statsDest) memcpy(&(statsDest->ip_frag), &(lwip_stats.ip_frag), sizeof(struct stats_proto)); memcpy(&(statsDest->ip), &(lwip_stats.ip), sizeof(struct stats_proto)); memcpy(&(statsDest->icmp), &(lwip_stats.icmp), sizeof(struct stats_proto)); - //memcpy(&(statsDest->igmp), &(lwip_stats.igmp), sizeof(struct stats_igmp)); + // memcpy(&(statsDest->igmp), &(lwip_stats.igmp), sizeof(struct stats_igmp)); memcpy(&(statsDest->udp), &(lwip_stats.udp), sizeof(struct stats_proto)); memcpy(&(statsDest->tcp), &(lwip_stats.tcp), sizeof(struct stats_proto)); // mem omitted @@ -835,23 +833,22 @@ int zts_get_all_stats(struct zts_stats *statsDest) // Copy ZT stats // ... return ZTS_ERR_OK; -#else + #else return ZTS_ERR_NO_RESULT; -#endif + #endif } -int zts_get_protocol_stats(int protocolType, void *protoStatsDest) +int zts_get_protocol_stats(int protocolType, void* protoStatsDest) { - if (!(_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { + if (! (_serviceStateFlags & ZTS_STATE_NET_SERVICE_RUNNING)) { return ZTS_ERR_SERVICE; } -#if LWIP_STATS - if (!protoStatsDest) { + #if LWIP_STATS + if (! protoStatsDest) { return ZTS_ERR_ARG; } memset(protoStatsDest, 0, sizeof(struct stats_proto)); - switch (protocolType) - { + switch (protocolType) { case ZTS_STATS_PROTOCOL_LINK: memcpy(protoStatsDest, &(lwip_stats.link), sizeof(struct stats_proto)); break; @@ -882,19 +879,18 @@ int zts_get_protocol_stats(int protocolType, void *protoStatsDest) case ZTS_STATS_PROTOCOL_IP6_FRAG: memcpy(protoStatsDest, &(lwip_stats.ip6_frag), sizeof(struct stats_proto)); break; - default: - return ZTS_ERR_ARG; + default: return ZTS_ERR_ARG; } return ZTS_ERR_OK; -#else + #else return ZTS_ERR_NO_RESULT; -#endif + #endif } -#endif // ZTS_ENABLE_STATS +#endif // ZTS_ENABLE_STATS #ifdef __cplusplus } #endif -} // namespace ZeroTier +} // namespace ZeroTier diff --git a/src/VirtualTap.cpp b/src/VirtualTap.cpp index 4f7b798..adef47a 100644 --- a/src/VirtualTap.cpp +++ b/src/VirtualTap.cpp @@ -18,30 +18,30 @@ */ #include "Constants.hpp" -#include "MAC.hpp" -#include "Mutex.hpp" #include "InetAddress.hpp" +#include "MAC.hpp" #include "MulticastGroup.hpp" - -#include "lwip/netif.h" +#include "Mutex.hpp" #include "lwip/etharp.h" -#include "lwip/sys.h" #include "lwip/ethip6.h" +#include "lwip/netif.h" +#include "lwip/sys.h" #include "lwip/tcpip.h" #include "netif/ethernet.h" #ifdef LWIP_STATS -#include "lwip/stats.h" + #include "lwip/stats.h" #endif +#include "Debug.hpp" +#include "Events.hpp" #include "VirtualTap.hpp" #include "ZeroTierSockets.h" -#include "Events.hpp" -#include "Debug.hpp" #if defined(__WINDOWS__) -#include -#include "Synchapi.h" + #include "Synchapi.h" + + #include #endif #define ZTS_TAP_THREAD_POLLING_INTERVAL 50 @@ -49,33 +49,41 @@ namespace ZeroTier { -extern void _enqueueEvent(int16_t eventCode, void *arg = NULL); +extern void _enqueueEvent(int16_t eventCode, void* arg = NULL); /** * A virtual tap device. The ZeroTier core service creates one of these for each * virtual network joined. It will be destroyed upon leave(). */ VirtualTap::VirtualTap( - const char *homePath, - const MAC &mac, - unsigned int mtu, - unsigned int metric, - uint64_t nwid, - const char *friendlyName, - void (*handler)(void *,void*,uint64_t,const MAC &,const MAC &, - unsigned int,unsigned int,const void *,unsigned int), - void *arg) : - _handler(handler), - _homePath(homePath), - _arg(arg), - _initialized(false), - _enabled(true), - _run(true), - _mac(mac), - _mtu(mtu), - _nwid(nwid), - _unixListenSocket((PhySocket *)0), - _phy(this,false,true) + const char* homePath, + const MAC& mac, + unsigned int mtu, + unsigned int metric, + uint64_t nwid, + const char* friendlyName, + void (*handler)( + void*, + void*, + uint64_t, + const MAC&, + const MAC&, + unsigned int, + unsigned int, + const void*, + unsigned int), + void* arg) + : _handler(handler) + , _homePath(homePath) + , _arg(arg) + , _initialized(false) + , _enabled(true) + , _run(true) + , _mac(mac) + , _mtu(mtu) + , _nwid(nwid) + , _unixListenSocket((PhySocket*)0) + , _phy(this, false, true) { memset(vtap_full_name, 0, sizeof(vtap_full_name)); snprintf(vtap_full_name, sizeof(vtap_full_name), "libzt%llx", (unsigned long long)_nwid); @@ -89,11 +97,11 @@ VirtualTap::VirtualTap( VirtualTap::~VirtualTap() { - struct zts_network_details *nd = new zts_network_details; + struct zts_network_details* nd = new zts_network_details; nd->nwid = _nwid; _run = false; #ifndef __WINDOWS__ - ::write(_shutdownSignalPipe[1],"\0",1); + ::write(_shutdownSignalPipe[1], "\0", 1); #endif _phy.whack(); _lwip_remove_netif(netif4); @@ -128,7 +136,9 @@ bool VirtualTap::hasIpv4Addr() Mutex::Lock _l(_ips_m); std::vector::iterator it(_ips.begin()); while (it != _ips.end()) { - if ((*it).isV4()) { return true; } + if ((*it).isV4()) { + return true; + } ++it; } return false; @@ -139,17 +149,19 @@ bool VirtualTap::hasIpv6Addr() Mutex::Lock _l(_ips_m); std::vector::iterator it(_ips.begin()); while (it != _ips.end()) { - if ((*it).isV6()) { return true; } + if ((*it).isV6()) { + return true; + } ++it; } return false; } -bool VirtualTap::addIp(const InetAddress &ip) +bool VirtualTap::addIp(const InetAddress& ip) { char ipbuf[128]; - //ip.toString(ipbuf); - //DEBUG_INFO("addr=%s", ipbuf); + // ip.toString(ipbuf); + // DEBUG_INFO("addr=%s", ipbuf); /* Limit address assignments to one per type. This limitation can be removed if some changes @@ -169,18 +181,18 @@ bool VirtualTap::addIp(const InetAddress &ip) if (_ips.size() >= ZT_MAX_ZT_ASSIGNED_ADDRESSES) { return false; } - if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) { + if (std::find(_ips.begin(), _ips.end(), ip) == _ips.end()) { _lwip_init_interface((void*)this, ip); _ips.push_back(ip); - std::sort(_ips.begin(),_ips.end()); + std::sort(_ips.begin(), _ips.end()); } return true; } -bool VirtualTap::removeIp(const InetAddress &ip) +bool VirtualTap::removeIp(const InetAddress& ip) { Mutex::Lock _l(_ips_m); - if (std::find(_ips.begin(),_ips.end(),ip) != _ips.end()) { + if (std::find(_ips.begin(), _ips.end(), ip) != _ips.end()) { std::vector::iterator i(std::find(_ips.begin(), _ips.end(), ip)); _lwip_remove_address_from_netif((void*)this, ip); _ips.erase(i); @@ -194,8 +206,12 @@ std::vector VirtualTap::ips() const return _ips; } -void VirtualTap::put(const MAC &from,const MAC &to,unsigned int etherType, - const void *data,unsigned int len) +void VirtualTap::put( + const MAC& from, + const MAC& to, + unsigned int etherType, + const void* data, + unsigned int len) { if (len && _enabled) { _lwip_eth_rx(this, from, to, etherType, data, len); @@ -207,29 +223,32 @@ std::string VirtualTap::deviceName() const return _dev; } -void VirtualTap::setFriendlyName(const char *friendlyName) +void VirtualTap::setFriendlyName(const char* friendlyName) { DEBUG_INFO("%s", friendlyName); } -void VirtualTap::scanMulticastGroups(std::vector &added, - std::vector &removed) +void VirtualTap::scanMulticastGroups( + std::vector& added, + std::vector& removed) { std::vector newGroups; Mutex::Lock _l(_multicastGroups_m); // TODO: get multicast subscriptions std::vector allIps(ips()); - for (std::vector::iterator ip(allIps.begin());ip!=allIps.end();++ip) + for (std::vector::iterator ip(allIps.begin()); ip != allIps.end(); ++ip) newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip)); - std::sort(newGroups.begin(),newGroups.end()); + std::sort(newGroups.begin(), newGroups.end()); - for (std::vector::iterator m(newGroups.begin());m!=newGroups.end();++m) { - if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m)) + for (std::vector::iterator m(newGroups.begin()); m != newGroups.end(); ++m) { + if (! std::binary_search(_multicastGroups.begin(), _multicastGroups.end(), *m)) added.push_back(*m); } - for (std::vector::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) { - if (!std::binary_search(newGroups.begin(),newGroups.end(),*m)) + for (std::vector::iterator m(_multicastGroups.begin()); + m != _multicastGroups.end(); + ++m) { + if (! std::binary_search(newGroups.begin(), newGroups.end(), *m)) removed.push_back(*m); } _multicastGroups.swap(newGroups); @@ -240,16 +259,15 @@ void VirtualTap::setMtu(unsigned int mtu) _mtu = mtu; } -void VirtualTap::threadMain() - throw() +void VirtualTap::threadMain() throw() { - fd_set readfds,nullfds; + fd_set readfds, nullfds; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; FD_ZERO(&readfds); FD_ZERO(&nullfds); - int nfds = (int)std::max(_shutdownSignalPipe[0],0) + 1; + int nfds = (int)std::max(_shutdownSignalPipe[0], 0) + 1; #if defined(__linux__) pthread_setname_np(pthread_self(), vtap_full_name); #endif @@ -257,31 +275,54 @@ void VirtualTap::threadMain() pthread_setname_np(vtap_full_name); #endif while (true) { - FD_SET(_shutdownSignalPipe[0],&readfds); - select(nfds,&readfds,&nullfds,&nullfds,&tv); + FD_SET(_shutdownSignalPipe[0], &readfds); + select(nfds, &readfds, &nullfds, &nullfds, &tv); // writes to shutdown pipe terminate thread - if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) { + if (FD_ISSET(_shutdownSignalPipe[0], &readfds)) { break; } #if defined(__WINDOWS__) Sleep(ZTS_TAP_THREAD_POLLING_INTERVAL); #else - struct timespec sleepValue = {0}; + struct timespec sleepValue = { 0 }; sleepValue.tv_nsec = ZTS_TAP_THREAD_POLLING_INTERVAL * 500000; nanosleep(&sleepValue, NULL); #endif } } -void VirtualTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *local_address, - const struct sockaddr *from,void *data,unsigned long len) {} -void VirtualTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {} -void VirtualTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN, - const struct sockaddr *from) {} -void VirtualTap::phyOnTcpClose(PhySocket *sock,void **uptr) {} -void VirtualTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {} -void VirtualTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {} -void VirtualTap::phyOnUnixClose(PhySocket *sock,void **uptr) {} +void VirtualTap::phyOnDatagram( + PhySocket* sock, + void** uptr, + const struct sockaddr* local_address, + const struct sockaddr* from, + void* data, + unsigned long len) +{ +} +void VirtualTap::phyOnTcpConnect(PhySocket* sock, void** uptr, bool success) +{ +} +void VirtualTap::phyOnTcpAccept( + PhySocket* sockL, + PhySocket* sockN, + void** uptrL, + void** uptrN, + const struct sockaddr* from) +{ +} +void VirtualTap::phyOnTcpClose(PhySocket* sock, void** uptr) +{ +} +void VirtualTap::phyOnTcpData(PhySocket* sock, void** uptr, void* data, unsigned long len) +{ +} +void VirtualTap::phyOnTcpWritable(PhySocket* sock, void** uptr) +{ +} +void VirtualTap::phyOnUnixClose(PhySocket* sock, void** uptr) +{ +} ////////////////////////////////////////////////////////////////////////////// // Netif driver code for lwIP network stack // @@ -297,17 +338,17 @@ int netifCount = 0; Mutex stackLock; // Callback for when the TCPIP thread has been successfully started -static void _tcpip_init_done(void *arg) +static void _tcpip_init_done(void* arg) { - sys_sem_t *sem; - sem = (sys_sem_t *)arg; + sys_sem_t* sem; + sem = (sys_sem_t*)arg; _setState(ZTS_STATE_STACK_RUNNING); _has_started = true; _enqueueEvent(ZTS_EVENT_STACK_UP); sys_sem_signal(sem); } -static void _main_lwip_driver_loop(void *arg) +static void _main_lwip_driver_loop(void* arg) { #if defined(__linux__) pthread_setname_np(pthread_self(), ZTS_LWIP_DRIVER_THREAD_NAME); @@ -323,7 +364,7 @@ static void _main_lwip_driver_loop(void *arg) tcpip_init(_tcpip_init_done, &sem); sys_sem_wait(&sem); // Main loop - while(_getState(ZTS_STATE_STACK_RUNNING)) { + while (_getState(ZTS_STATE_STACK_RUNNING)) { zts_delay_ms(LWIP_DRIVER_LOOP_INTERVAL); } _has_exited = true; @@ -346,10 +387,14 @@ void _lwip_driver_init() } Mutex::Lock _l(stackLock); #if defined(__WINDOWS__) - sys_init(); // Required for win32 init of critical sections + sys_init(); // Required for win32 init of critical sections #endif - sys_thread_new(ZTS_LWIP_DRIVER_THREAD_NAME, _main_lwip_driver_loop, - NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); + sys_thread_new( + ZTS_LWIP_DRIVER_THREAD_NAME, + _main_lwip_driver_loop, + NULL, + DEFAULT_THREAD_STACKSIZE, + DEFAULT_THREAD_PRIO); } void _lwip_driver_shutdown() @@ -362,16 +407,18 @@ void _lwip_driver_shutdown() _clrState(ZTS_STATE_STACK_RUNNING); // Wait until the main lwIP thread has exited if (_has_started) { - while (!_has_exited) { zts_delay_ms(LWIP_DRIVER_LOOP_INTERVAL); } + while (! _has_exited) { + zts_delay_ms(LWIP_DRIVER_LOOP_INTERVAL); + } } } -void _lwip_remove_netif(void *netif) +void _lwip_remove_netif(void* netif) { - if (!netif) { + if (! netif) { return; } - struct netif *n = (struct netif*)netif; + struct netif* n = (struct netif*)netif; LOCK_TCPIP_CORE(); netif_remove(n); netif_set_down(n); @@ -379,32 +426,32 @@ void _lwip_remove_netif(void *netif) UNLOCK_TCPIP_CORE(); } -err_t _lwip_eth_tx(struct netif *n, struct pbuf *p) +err_t _lwip_eth_tx(struct netif* n, struct pbuf* p) { - if (!n) { + if (! n) { return ERR_IF; } - struct pbuf *q; - char buf[ZT_MAX_MTU+32]; - char *bufptr; + struct pbuf* q; + char buf[ZT_MAX_MTU + 32]; + char* bufptr; int totalLength = 0; - VirtualTap *tap = (VirtualTap*)n->state; + VirtualTap* tap = (VirtualTap*)n->state; bufptr = buf; for (q = p; q != NULL; q = q->next) { memcpy(bufptr, q->payload, q->len); bufptr += q->len; totalLength += q->len; } - struct eth_hdr *ethhdr; - ethhdr = (struct eth_hdr *)buf; + struct eth_hdr* ethhdr; + ethhdr = (struct eth_hdr*)buf; MAC src_mac; MAC dest_mac; src_mac.setTo(ethhdr->src.addr, 6); dest_mac.setTo(ethhdr->dest.addr, 6); - char *data = buf + sizeof(struct eth_hdr); + char* data = buf + sizeof(struct eth_hdr); int len = totalLength - sizeof(struct eth_hdr); int proto = Utils::ntoh((uint16_t)ethhdr->type); tap->_handler(tap->_arg, NULL, tap->_nwid, src_mac, dest_mac, proto, 0, data, len); @@ -412,30 +459,42 @@ err_t _lwip_eth_tx(struct netif *n, struct pbuf *p) char flagbuf[32]; memset(&flagbuf, 0, 32); char macBuf[ZTS_MAC_ADDRSTRLEN], nodeBuf[16]; - snprintf(macBuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x", - ethhdr->dest.addr[0], ethhdr->dest.addr[1], ethhdr->dest.addr[2], - ethhdr->dest.addr[3], ethhdr->dest.addr[4], ethhdr->dest.addr[5]); + snprintf( + macBuf, + ZTS_MAC_ADDRSTRLEN, + "%02x:%02x:%02x:%02x:%02x:%02x", + ethhdr->dest.addr[0], + ethhdr->dest.addr[1], + ethhdr->dest.addr[2], + ethhdr->dest.addr[3], + ethhdr->dest.addr[4], + ethhdr->dest.addr[5]); MAC mac; mac.setTo(ethhdr->dest.addr, 6); mac.toAddress(tap->_nwid).toString(nodeBuf); /* - DEBUG_TRANS("len=%5d dst=%s [%s TX <-- %s] ethertype=0x%04x %s", totalLength, macBuf, nodeBuf, tap->nodeId().c_str(), - Utils::ntoh(ethhdr->type), flagbuf); + DEBUG_TRANS("len=%5d dst=%s [%s TX <-- %s] ethertype=0x%04x %s", totalLength, macBuf, + nodeBuf, tap->nodeId().c_str(), Utils::ntoh(ethhdr->type), flagbuf); */ } return ERR_OK; } -void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int etherType, - const void *data, unsigned int len) +void _lwip_eth_rx( + VirtualTap* tap, + const MAC& from, + const MAC& to, + unsigned int etherType, + const void* data, + unsigned int len) { #ifdef LWIP_STATS stats_display(); #endif - if (!_getState(ZTS_STATE_STACK_RUNNING)) { + if (! _getState(ZTS_STATE_STACK_RUNNING)) { return; } - struct pbuf *p,*q; + struct pbuf *p, *q; struct eth_hdr ethhdr; from.copyTo(ethhdr.src.addr, 6); to.copyTo(ethhdr.dest.addr, 6); @@ -445,20 +504,27 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int char flagbuf[32]; memset(&flagbuf, 0, 32); char macBuf[ZTS_MAC_ADDRSTRLEN], nodeBuf[16]; - snprintf(macBuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x", - ethhdr.dest.addr[0], ethhdr.dest.addr[1], ethhdr.dest.addr[2], - ethhdr.dest.addr[3], ethhdr.dest.addr[4], ethhdr.dest.addr[5]); + snprintf( + macBuf, + ZTS_MAC_ADDRSTRLEN, + "%02x:%02x:%02x:%02x:%02x:%02x", + ethhdr.dest.addr[0], + ethhdr.dest.addr[1], + ethhdr.dest.addr[2], + ethhdr.dest.addr[3], + ethhdr.dest.addr[4], + ethhdr.dest.addr[5]); MAC mac; mac.setTo(ethhdr.src.addr, 6); mac.toAddress(tap->_nwid).toString(nodeBuf); /* - DEBUG_TRANS("len=%5d dst=%s [%s RX --> %s] ethertype=0x%04x %s", len, macBuf, nodeBuf, tap->nodeId().c_str(), - Utils::ntoh(ethhdr.type), flagbuf); + DEBUG_TRANS("len=%5d dst=%s [%s RX --> %s] ethertype=0x%04x %s", len, macBuf, nodeBuf, + tap->nodeId().c_str(), Utils::ntoh(ethhdr.type), flagbuf); */ } - p = pbuf_alloc(PBUF_RAW, (uint16_t)len+sizeof(struct eth_hdr), PBUF_RAM); - if (!p) { + p = pbuf_alloc(PBUF_RAW, (uint16_t)len + sizeof(struct eth_hdr), PBUF_RAM); + if (! p) { DEBUG_ERROR("dropped packet: unable to allocate memory for pbuf"); return; } @@ -471,14 +537,14 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int return; } // Copy frame data into pbuf - const char *dataptr = reinterpret_cast(data); - memcpy(q->payload,ðhdr,sizeof(ethhdr)); + const char* dataptr = reinterpret_cast(data); + memcpy(q->payload, ðhdr, sizeof(ethhdr)); int remainingPayloadSpace = q->len - sizeof(ethhdr); - memcpy((char*)q->payload + sizeof(ethhdr),dataptr,remainingPayloadSpace); + memcpy((char*)q->payload + sizeof(ethhdr), dataptr, remainingPayloadSpace); dataptr += remainingPayloadSpace; // Remaining pbufs (if any) get rest of data while ((q = q->next)) { - memcpy(q->payload,dataptr,q->len); + memcpy(q->payload, dataptr, q->len); dataptr += q->len; } // Feed packet into stack @@ -486,7 +552,8 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int if (Utils::ntoh(ethhdr.type) == 0x800 || Utils::ntoh(ethhdr.type) == 0x806) { if (tap->netif4) { - if ((err = ((struct netif *)tap->netif4)->input(p, (struct netif *)tap->netif4)) != ERR_OK) { + if ((err = ((struct netif*)tap->netif4)->input(p, (struct netif*)tap->netif4)) + != ERR_OK) { DEBUG_ERROR("packet input error (%d)", err); pbuf_free(p); } @@ -494,7 +561,8 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int } if (Utils::ntoh(ethhdr.type) == 0x86DD) { if (tap->netif6) { - if ((err = ((struct netif *)tap->netif6)->input(p, (struct netif *)tap->netif6)) != ERR_OK) { + if ((err = ((struct netif*)tap->netif6)->input(p, (struct netif*)tap->netif6)) + != ERR_OK) { DEBUG_ERROR("packet input error (%d)", err); pbuf_free(p); } @@ -502,9 +570,9 @@ void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int } } -bool _lwip_is_netif_up(void *n) +bool _lwip_is_netif_up(void* n) { - if (!n) { + if (! n) { return false; } LOCK_TCPIP_CORE(); @@ -516,112 +584,102 @@ bool _lwip_is_netif_up(void *n) /* static struct zts_netif_details *_lwip_prepare_netif_status_msg(struct netif *n) { - if (!n || !n->state) { - return NULL; - } - VirtualTap *tap = (VirtualTap *)n->state; - struct zts_netif_details *details = new zts_netif_details(); - details->nwid = tap->_nwid; - memcpy(&(details->mac), n->hwaddr, n->hwaddr_len); - details->mtu = n->mtu; - return details; + if (!n || !n->state) { + return NULL; + } + VirtualTap *tap = (VirtualTap *)n->state; + struct zts_netif_details *details = new zts_netif_details(); + details->nwid = tap->_nwid; + memcpy(&(details->mac), n->hwaddr, n->hwaddr_len); + details->mtu = n->mtu; + return details; } static void _netif_remove_callback(struct netif *n) { - // Called from core, no need to lock - if (!n || !n->state) { - return; - } - VirtualTap *tap = (VirtualTap *)n->state; - struct zts_netif_details *details = new zts_netif_details(); - details->nwid = tap->_nwid; - details->mac = 0; - details->mtu = 0; - _enqueueEvent(ZTS_EVENT_NETIF_REMOVED, (void*)details); + // Called from core, no need to lock + if (!n || !n->state) { + return; + } + VirtualTap *tap = (VirtualTap *)n->state; + struct zts_netif_details *details = new zts_netif_details(); + details->nwid = tap->_nwid; + details->mac = 0; + details->mtu = 0; + _enqueueEvent(ZTS_EVENT_NETIF_REMOVED, (void*)details); } static void _netif_status_callback(struct netif *n) { - // Called from core, no need to lock - if (!n) { - return; - } if (netif_is_up(n)) { - _enqueueEvent(ZTS_EVENT_NETIF_UP, (void*)_lwip_prepare_netif_status_msg(n)); - } else { - _enqueueEvent(ZTS_EVENT_NETIF_DOWN, (void*)_lwip_prepare_netif_status_msg(n)); - } + // Called from core, no need to lock + if (!n) { + return; + } if (netif_is_up(n)) { + _enqueueEvent(ZTS_EVENT_NETIF_UP, (void*)_lwip_prepare_netif_status_msg(n)); + } else { + _enqueueEvent(ZTS_EVENT_NETIF_DOWN, (void*)_lwip_prepare_netif_status_msg(n)); + } } static void _netif_link_callback(struct netif *n) { - // Called from core, no need to lock - if (!n) { - return; - } if (netif_is_link_up(n)) { - _enqueueEvent(ZTS_EVENT_NETIF_LINK_UP, (void*)_lwip_prepare_netif_status_msg(n)); - } else { - _enqueueEvent(ZTS_EVENT_NETIF_LINK_DOWN, (void*)_lwip_prepare_netif_status_msg(n)); - } + // Called from core, no need to lock + if (!n) { + return; + } if (netif_is_link_up(n)) { + _enqueueEvent(ZTS_EVENT_NETIF_LINK_UP, (void*)_lwip_prepare_netif_status_msg(n)); + } else { + _enqueueEvent(ZTS_EVENT_NETIF_LINK_DOWN, (void*)_lwip_prepare_netif_status_msg(n)); + } } */ -static err_t _netif_init4(struct netif *n) +static err_t _netif_init4(struct netif* n) { - if (!n || !n->state) { + if (! n || ! n->state) { return ERR_IF; } // Called from core, no need to lock - VirtualTap *tap = (VirtualTap*)(n->state); + VirtualTap* tap = (VirtualTap*)(n->state); n->hwaddr_len = 6; - n->name[0] = '4'; - n->name[1] = 'a'+netifCount; + n->name[0] = '4'; + n->name[1] = 'a' + netifCount; n->linkoutput = _lwip_eth_tx; - n->output = etharp_output; - n->mtu = std::min(LWIP_MTU,(int)tap->_mtu); - n->flags = NETIF_FLAG_BROADCAST - | NETIF_FLAG_ETHARP - | NETIF_FLAG_ETHERNET - | NETIF_FLAG_IGMP - | NETIF_FLAG_MLD6 - | NETIF_FLAG_LINK_UP - | NETIF_FLAG_UP; + n->output = etharp_output; + n->mtu = std::min(LWIP_MTU, (int)tap->_mtu); + n->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP + | NETIF_FLAG_MLD6 | NETIF_FLAG_LINK_UP | NETIF_FLAG_UP; n->hwaddr_len = sizeof(n->hwaddr); tap->_mac.copyTo(n->hwaddr, n->hwaddr_len); return ERR_OK; } -static err_t _netif_init6(struct netif *n) +static err_t _netif_init6(struct netif* n) { - if (!n || !n->state) { + if (! n || ! n->state) { return ERR_IF; } n->hwaddr_len = sizeof(n->hwaddr); - VirtualTap *tap = (VirtualTap*)(n->state); + VirtualTap* tap = (VirtualTap*)(n->state); tap->_mac.copyTo(n->hwaddr, n->hwaddr_len); // Called from core, no need to lock n->hwaddr_len = 6; - n->name[0] = '6'; - n->name[1] = 'a'+netifCount; + n->name[0] = '6'; + n->name[1] = 'a' + netifCount; n->linkoutput = _lwip_eth_tx; n->output_ip6 = ethip6_output; - n->mtu = std::min(LWIP_MTU,(int)tap->_mtu); - n->flags = NETIF_FLAG_BROADCAST - | NETIF_FLAG_ETHARP - | NETIF_FLAG_ETHERNET - | NETIF_FLAG_IGMP - | NETIF_FLAG_MLD6 - | NETIF_FLAG_LINK_UP - | NETIF_FLAG_UP; + n->mtu = std::min(LWIP_MTU, (int)tap->_mtu); + n->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP + | NETIF_FLAG_MLD6 | NETIF_FLAG_LINK_UP | NETIF_FLAG_UP; return ERR_OK; } -void _lwip_init_interface(void *tapref, const InetAddress &ip) +void _lwip_init_interface(void* tapref, const InetAddress& ip) { char macbuf[ZTS_MAC_ADDRSTRLEN]; - VirtualTap *vtap = (VirtualTap*)tapref; - struct netif *n = NULL; + VirtualTap* vtap = (VirtualTap*)tapref; + struct netif* n = NULL; bool isNewNetif = false; if (ip.isV4()) { @@ -639,21 +697,28 @@ void _lwip_init_interface(void *tapref, const InetAddress &ip) netif_set_link_callback(n, _netif_link_callback); */ static ip4_addr_t ip4, netmask, gw; - IP4_ADDR(&gw,127,0,0,1); - ip4.addr = *((u32_t *)ip.rawIpData()); - netmask.addr = *((u32_t *)ip.netmask().rawIpData()); + IP4_ADDR(&gw, 127, 0, 0, 1); + ip4.addr = *((u32_t*)ip.rawIpData()); + netmask.addr = *((u32_t*)ip.netmask().rawIpData()); LOCK_TCPIP_CORE(); netif_add(n, &ip4, &netmask, &gw, (void*)vtap, _netif_init4, tcpip_input); vtap->netif4 = (void*)n; UNLOCK_TCPIP_CORE(); - snprintf(macbuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x", - n->hwaddr[0], n->hwaddr[1], n->hwaddr[2], - n->hwaddr[3], n->hwaddr[4], n->hwaddr[5]); + snprintf( + macbuf, + ZTS_MAC_ADDRSTRLEN, + "%02x:%02x:%02x:%02x:%02x:%02x", + n->hwaddr[0], + n->hwaddr[1], + n->hwaddr[2], + n->hwaddr[3], + n->hwaddr[4], + n->hwaddr[5]); /* char nmbuf[INET6_ADDRSTRLEN]; char ipbuf[INET6_ADDRSTRLEN]; DEBUG_INFO("initialized netif=%p as [mac=%s, addr=%s, nm=%s, tap=%p]",n, - macbuf, ip.toString(ipbuf), ip.netmask().toString(nmbuf), vtap); + macbuf, ip.toString(ipbuf), ip.netmask().toString(nmbuf), vtap); */ } if (ip.isV6()) { @@ -664,11 +729,11 @@ void _lwip_init_interface(void *tapref, const InetAddress &ip) n = new struct netif; isNewNetif = true; netifCount++; - }/* - netif_set_status_callback(n, _netif_status_callback); - netif_set_remove_callback(n, _netif_remove_callback); - netif_set_link_callback(n, _netif_link_callback); - */ + } /* + netif_set_status_callback(n, _netif_status_callback); + netif_set_remove_callback(n, _netif_remove_callback); + netif_set_link_callback(n, _netif_link_callback); + */ static ip6_addr_t ip6; memcpy(&(ip6.addr), ip.rawIpData(), sizeof(ip6.addr)); LOCK_TCPIP_CORE(); @@ -682,26 +747,33 @@ void _lwip_init_interface(void *tapref, const InetAddress &ip) netif_set_up(n); netif_set_default(n); } - netif_add_ip6_address(n,&ip6,NULL); + netif_add_ip6_address(n, &ip6, NULL); n->output_ip6 = ethip6_output; UNLOCK_TCPIP_CORE(); - snprintf(macbuf, ZTS_MAC_ADDRSTRLEN, "%02x:%02x:%02x:%02x:%02x:%02x", - n->hwaddr[0], n->hwaddr[1], n->hwaddr[2], - n->hwaddr[3], n->hwaddr[4], n->hwaddr[5]); + snprintf( + macbuf, + ZTS_MAC_ADDRSTRLEN, + "%02x:%02x:%02x:%02x:%02x:%02x", + n->hwaddr[0], + n->hwaddr[1], + n->hwaddr[2], + n->hwaddr[3], + n->hwaddr[4], + n->hwaddr[5]); /* DEBUG_INFO("initialized netif=%p as [mac=%s, addr=%s, tap=%p]", n, - macbuf, ip.toString(ipbuf), vtap); + macbuf, ip.toString(ipbuf), vtap); */ } } -void _lwip_remove_address_from_netif(void *tapref, const InetAddress &ip) +void _lwip_remove_address_from_netif(void* tapref, const InetAddress& ip) { - if (!tapref) { + if (! tapref) { return; } - VirtualTap *vtap = (VirtualTap*)tapref; - struct netif *n = NULL; + VirtualTap* vtap = (VirtualTap*)tapref; + struct netif* n = NULL; /* When true multi-homing is implemented this will need to be a bit more sophisticated */ if (ip.isV4()) { @@ -714,10 +786,10 @@ void _lwip_remove_address_from_netif(void *tapref, const InetAddress &ip) n = (struct netif*)vtap->netif6; } } - if (!n) { + if (! n) { return; } _lwip_remove_netif(n); } -} // namespace ZeroTier +} // namespace ZeroTier diff --git a/src/VirtualTap.hpp b/src/VirtualTap.hpp index e0bef64..7a0fd35 100644 --- a/src/VirtualTap.hpp +++ b/src/VirtualTap.hpp @@ -39,21 +39,28 @@ struct InetAddress; * A virtual tap device. The ZeroTier Node Service will create one per * joined network. It will be destroyed upon leave(). */ -class VirtualTap -{ - friend class Phy; +class VirtualTap { + friend class Phy; -public: + public: VirtualTap( - const char *homePath, - const MAC &mac, - unsigned int mtu, - unsigned int metric, - uint64_t nwid, - const char *friendlyName, - void (*handler)(void *, void *, uint64_t, const MAC &, - const MAC &, unsigned int, unsigned int, const void *, unsigned int), - void *arg); + const char* homePath, + const MAC& mac, + unsigned int mtu, + unsigned int metric, + uint64_t nwid, + const char* friendlyName, + void (*handler)( + void*, + void*, + uint64_t, + const MAC&, + const MAC&, + unsigned int, + unsigned int, + const void*, + unsigned int), + void* arg); ~VirtualTap(); @@ -63,7 +70,7 @@ public: /** * Mutex for protecting IP address container for this tap. */ - Mutex _ips_m; // Public because we want it accessible by the driver layer + Mutex _ips_m; // Public because we want it accessible by the driver layer /** * Return whether this tap has been assigned an IPv4 address. @@ -79,18 +86,18 @@ public: * Adds an address to the user-space stack interface associated with this VirtualTap * - Starts VirtualTap main thread ONLY if successful */ - bool addIp(const InetAddress &ip); + bool addIp(const InetAddress& ip); /** * Removes an address from the user-space stack interface associated with this VirtualTap */ - bool removeIp(const InetAddress &ip); + bool removeIp(const InetAddress& ip); /** * Presents data to the user-space stack */ - void put(const MAC &from,const MAC &to,unsigned int etherType,const void *data, - unsigned int len); + void + put(const MAC& from, const MAC& to, unsigned int etherType, const void* data, unsigned int len); /** * Get VirtualTap device name (e.g. 'libzt17d72843bc2c5760') @@ -100,13 +107,13 @@ public: /** * Set friendly name */ - void setFriendlyName(const char *friendlyName); + void setFriendlyName(const char* friendlyName); /** * Scan multicast groups */ - void scanMulticastGroups(std::vector &added, - std::vector &removed); + void + scanMulticastGroups(std::vector& added, std::vector& removed); /** * Set MTU @@ -116,17 +123,24 @@ public: /** * Calls main network stack loops */ - void threadMain() - throw(); + void threadMain() throw(); /** * For moving data onto the ZeroTier virtual wire */ - void (*_handler)(void *, void *, uint64_t, const MAC &, const MAC &, unsigned int, unsigned int, - const void *, unsigned int); + void (*_handler)( + void*, + void*, + uint64_t, + const MAC&, + const MAC&, + unsigned int, + unsigned int, + const void*, + unsigned int); - void *netif4 = NULL; - void *netif6 = NULL; + void* netif4 = NULL; + void* netif6 = NULL; /** * The last time that this virtual tap received a network config update from the core @@ -143,21 +157,21 @@ public: std::vector _ips; std::string _homePath; - void *_arg; + void* _arg; volatile bool _initialized; volatile bool _enabled; volatile bool _run; MAC _mac; unsigned int _mtu; uint64_t _nwid; - PhySocket *_unixListenSocket; - Phy _phy; + PhySocket* _unixListenSocket; + Phy _phy; Thread _thread; int _shutdownSignalPipe[2]; - std::string _dev; // path to Unix domain socket + std::string _dev; // path to Unix domain socket std::vector _multicastGroups; Mutex _multicastGroups_m; @@ -166,15 +180,24 @@ public: // Not used in this implementation // ////////////////////////////////////////////////////////////////////////////// - void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *local_address, - const struct sockaddr *from,void *data,unsigned long len); - void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success); - void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN, - const struct sockaddr *from); - void phyOnTcpClose(PhySocket *sock,void **uptr); - void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len); - void phyOnTcpWritable(PhySocket *sock,void **uptr); - void phyOnUnixClose(PhySocket *sock,void **uptr); + void phyOnDatagram( + PhySocket* sock, + void** uptr, + const struct sockaddr* local_address, + const struct sockaddr* from, + void* data, + unsigned long len); + void phyOnTcpConnect(PhySocket* sock, void** uptr, bool success); + void phyOnTcpAccept( + PhySocket* sockL, + PhySocket* sockN, + void** uptrL, + void** uptrN, + const struct sockaddr* from); + void phyOnTcpClose(PhySocket* sock, void** uptr); + void phyOnTcpData(PhySocket* sock, void** uptr, void* data, unsigned long len); + void phyOnTcpWritable(PhySocket* sock, void** uptr); + void phyOnUnixClose(PhySocket* sock, void** uptr); }; /** @@ -182,7 +205,7 @@ public: * * @usage This is a convenience function to encapsulate a macro */ -bool _lwip_is_netif_up(void *netif); +bool _lwip_is_netif_up(void* netif); /** * @brief Increase the delay multiplier for the main driver loop @@ -206,28 +229,29 @@ bool _lwip_is_up(); /** * @brief Initialize network stack semaphores, threads, and timers. * - * @usage This is called during the initial setup of each VirtualTap but is only allowed to execute once + * @usage This is called during the initial setup of each VirtualTap but is only allowed to execute + * once */ void _lwip_driver_init(); /** * @brief Shutdown the stack as completely as possible (not officially supported by lwIP) * - * @usage This is to be called after it is determined that no further network activity will take place. - * The tcpip thread will be stopped, all interfaces will be brought down and all resources will - * be deallocated. A full application restart will be required to bring the stack back online. + * @usage This is to be called after it is determined that no further network activity will take + * place. The tcpip thread will be stopped, all interfaces will be brought down and all resources + * will be deallocated. A full application restart will be required to bring the stack back online. */ void _lwip_driver_shutdown(); /** * @brief Requests that a netif be brought down and removed. */ -void _lwip_remove_netif(void *netif); +void _lwip_remove_netif(void* netif); /** * @brief Starts DHCP timers */ -void _lwip_start_dhcp(void *netif); +void _lwip_start_dhcp(void* netif); /** * @brief Called when the status of a netif changes: @@ -235,21 +259,22 @@ void _lwip_start_dhcp(void *netif); * - Address changes while up (ZTS_EVENT_NETIF_NEW_ADDRESS) */ #if LWIP_NETIF_STATUS_CALLBACK -static void _netif_status_callback(struct netif *netif); +static void _netif_status_callback(struct netif* netif); #endif /** * @brief Called when a netif is removed (ZTS_EVENT_NETIF_INTERFACE_REMOVED) */ #if LWIP_NETIF_REMOVE_CALLBACK -static void _netif_remove_callback(struct netif *netif); +static void _netif_remove_callback(struct netif* netif); #endif /** - * @brief Called when a link is brought up or down (ZTS_EVENT_NETIF_LINK_UP, ZTS_EVENT_NETIF_LINK_DOWN) + * @brief Called when a link is brought up or down (ZTS_EVENT_NETIF_LINK_UP, + * ZTS_EVENT_NETIF_LINK_DOWN) */ #if LWIP_NETIF_LINK_CALLBACK -static void _netif_link_callback(struct netif *netif); +static void _netif_link_callback(struct netif* netif); #endif /** @@ -258,7 +283,7 @@ static void _netif_link_callback(struct netif *netif); * @param tapref Reference to VirtualTap that will be responsible for sending and receiving data * @param ip Virtual IP address for this ZeroTier VirtualTap interface */ -void _lwip_init_interface(void *tapref, const InetAddress &ip); +void _lwip_init_interface(void* tapref, const InetAddress& ip); /** * @brief Remove an assigned address from an lwIP netif @@ -266,17 +291,19 @@ void _lwip_init_interface(void *tapref, const InetAddress &ip); * @param tapref Reference to VirtualTap * @param ip Virtual IP address to remove from this interface */ -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. - * @param netif Transmits an outgoing Ethernet fram from the network stack onto the ZeroTier virtual wire + * @param netif Transmits an outgoing Ethernet fram from the network stack onto the ZeroTier virtual + * wire * @param p A pointer to the beginning of a chain pf struct pbufs * @return */ -err_t _lwip_eth_tx(struct netif *netif, struct pbuf *p); +err_t _lwip_eth_tx(struct netif* netif, struct pbuf* p); /** * @brief Receives incoming Ethernet frames from the ZeroTier virtual wire @@ -289,10 +316,14 @@ err_t _lwip_eth_tx(struct netif *netif, struct pbuf *p); * @param data Pointer to Ethernet frame * @param len Length of Ethernet frame */ -void _lwip_eth_rx(VirtualTap *tap, const MAC &from, const MAC &to, unsigned int etherType, - const void *data, unsigned int len); +void _lwip_eth_rx( + VirtualTap* tap, + const MAC& from, + const MAC& to, + unsigned int etherType, + const void* data, + unsigned int len); -} // namespace ZeroTier - -#endif // _H +} // namespace ZeroTier +#endif // _H