(1) Make ZT_ naming convention consistent (get rid of ZT1_), (2) Make local interface a full sockaddr_storage instead of an int identifier, which turns out to be better for multi-homing and other uses.

This commit is contained in:
Adam Ierymenko 2015-09-24 16:21:36 -07:00
parent 0e5aac6a11
commit f69454ec98
29 changed files with 622 additions and 622 deletions

View file

@ -26,8 +26,8 @@
*/ */
/* /*
* This defines the external C API for ZeroTier One, the core network * This defines the external C API for ZeroTier's core network virtualization
* virtualization engine. * engine.
*/ */
#ifndef ZT_ZEROTIERONE_H #ifndef ZT_ZEROTIERONE_H
@ -56,9 +56,9 @@ extern "C" {
/****************************************************************************/ /****************************************************************************/
/** /**
* Default port for the ZeroTier service * Default UDP port for devices running a ZeroTier endpoint
*/ */
#define ZT1_DEFAULT_PORT 9993 #define ZT_DEFAULT_PORT 9993
/** /**
* Maximum MTU for ZeroTier virtual networks * Maximum MTU for ZeroTier virtual networks
@ -83,37 +83,42 @@ extern "C" {
* We use 2800, which leaves some room for other payload in other types of * We use 2800, which leaves some room for other payload in other types of
* messages such as multicast propagation or future support for bridging. * messages such as multicast propagation or future support for bridging.
*/ */
#define ZT1_MAX_MTU 2800 #define ZT_MAX_MTU 2800
/** /**
* Maximum length of network short name * Maximum length of network short name
*/ */
#define ZT1_MAX_NETWORK_SHORT_NAME_LENGTH 255 #define ZT_MAX_NETWORK_SHORT_NAME_LENGTH 255
/** /**
* 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 ZT1_MAX_ZT_ASSIGNED_ADDRESSES 16 #define ZT_MAX_ZT_ASSIGNED_ADDRESSES 16
/** /**
* Maximum number of multicast group subscriptions per network * Maximum number of multicast group subscriptions per network
*/ */
#define ZT1_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS 4096 #define ZT_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS 4096
/** /**
* Maximum number of direct network paths to a given peer * Maximum number of direct network paths to a given peer
*/ */
#define ZT1_MAX_PEER_NETWORK_PATHS 4 #define ZT_MAX_PEER_NETWORK_PATHS 4
/** /**
* Feature flag: ZeroTier One was built to be thread-safe -- concurrent processXXX() calls are okay * Feature flag: ZeroTier One was built to be thread-safe -- concurrent processXXX() calls are okay
*/ */
#define ZT1_FEATURE_FLAG_THREAD_SAFE 0x00000001 #define ZT_FEATURE_FLAG_THREAD_SAFE 0x00000001
/** /**
* Feature flag: FIPS compliant build (not available yet, but reserved for future use if we ever do this) * Feature flag: FIPS compliant build (not available yet, but reserved for future use if we ever do this)
*/ */
#define ZT1_FEATURE_FLAG_FIPS 0x00000002 #define ZT_FEATURE_FLAG_FIPS 0x00000002
/**
* A null/empty sockaddr (all zero) to signify an unspecified socket address
*/
extern const struct sockaddr_storage ZT_SOCKADDR_NULL;
/****************************************************************************/ /****************************************************************************/
/* Structures and other types */ /* Structures and other types */
@ -122,53 +127,53 @@ extern "C" {
/** /**
* Function return code: OK (0) or error results * Function return code: OK (0) or error results
* *
* Use ZT1_ResultCode_isFatal() to check for a fatal error. If a fatal error * Use ZT_ResultCode_isFatal() to check for a fatal error. If a fatal error
* occurs, the node should be considered to not be working correctly. These * occurs, the node should be considered to not be working correctly. These
* indicate serious problems like an inaccessible data store or a compile * indicate serious problems like an inaccessible data store or a compile
* problem. * problem.
*/ */
enum ZT1_ResultCode enum ZT_ResultCode
{ {
/** /**
* Operation completed normally * Operation completed normally
*/ */
ZT1_RESULT_OK = 0, ZT_RESULT_OK = 0,
// Fatal errors (>0, <1000) // Fatal errors (>0, <1000)
/** /**
* Ran out of memory * Ran out of memory
*/ */
ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY = 1, ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY = 1,
/** /**
* Data store is not writable or has failed * Data store is not writable or has failed
*/ */
ZT1_RESULT_FATAL_ERROR_DATA_STORE_FAILED = 2, ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED = 2,
/** /**
* Internal error (e.g. unexpected exception indicating bug or build problem) * Internal error (e.g. unexpected exception indicating bug or build problem)
*/ */
ZT1_RESULT_FATAL_ERROR_INTERNAL = 3, ZT_RESULT_FATAL_ERROR_INTERNAL = 3,
// Non-fatal errors (>1000) // Non-fatal errors (>1000)
/** /**
* Network ID not valid * Network ID not valid
*/ */
ZT1_RESULT_ERROR_NETWORK_NOT_FOUND = 1000 ZT_RESULT_ERROR_NETWORK_NOT_FOUND = 1000
}; };
/** /**
* @param x Result code * @param x Result code
* @return True if result code indicates a fatal error * @return True if result code indicates a fatal error
*/ */
#define ZT1_ResultCode_isFatal(x) ((((int)(x)) > 0)&&(((int)(x)) < 1000)) #define ZT_ResultCode_isFatal(x) ((((int)(x)) > 0)&&(((int)(x)) < 1000))
/** /**
* Status codes sent to status update callback when things happen * Status codes sent to status update callback when things happen
*/ */
enum ZT1_Event enum ZT_Event
{ {
/** /**
* Node has been initialized * Node has been initialized
@ -178,21 +183,21 @@ enum ZT1_Event
* *
* Meta-data: none * Meta-data: none
*/ */
ZT1_EVENT_UP = 0, ZT_EVENT_UP = 0,
/** /**
* Node is offline -- network does not seem to be reachable by any available strategy * Node is offline -- network does not seem to be reachable by any available strategy
* *
* Meta-data: none * Meta-data: none
*/ */
ZT1_EVENT_OFFLINE = 1, ZT_EVENT_OFFLINE = 1,
/** /**
* Node is online -- at least one upstream node appears reachable * Node is online -- at least one upstream node appears reachable
* *
* Meta-data: none * Meta-data: none
*/ */
ZT1_EVENT_ONLINE = 2, ZT_EVENT_ONLINE = 2,
/** /**
* Node is shutting down * Node is shutting down
@ -203,7 +208,7 @@ enum ZT1_Event
* *
* Meta-data: none * Meta-data: none
*/ */
ZT1_EVENT_DOWN = 3, ZT_EVENT_DOWN = 3,
/** /**
* Your identity has collided with another node's ZeroTier address * Your identity has collided with another node's ZeroTier address
@ -235,7 +240,7 @@ enum ZT1_Event
* *
* Meta-data: none * Meta-data: none
*/ */
ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION = 4, ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION = 4,
/** /**
* A more recent version was observed on the network * A more recent version was observed on the network
@ -246,21 +251,21 @@ enum ZT1_Event
* *
* Meta-data: unsigned int[3], more recent version number * Meta-data: unsigned int[3], more recent version number
*/ */
ZT1_EVENT_SAW_MORE_RECENT_VERSION = 5, ZT_EVENT_SAW_MORE_RECENT_VERSION = 5,
/** /**
* A packet failed authentication * A packet failed authentication
* *
* Meta-data: struct sockaddr_storage containing origin address of packet * Meta-data: struct sockaddr_storage containing origin address of packet
*/ */
ZT1_EVENT_AUTHENTICATION_FAILURE = 6, ZT_EVENT_AUTHENTICATION_FAILURE = 6,
/** /**
* A received packet was not valid * A received packet was not valid
* *
* Meta-data: struct sockaddr_storage containing origin address of packet * Meta-data: struct sockaddr_storage containing origin address of packet
*/ */
ZT1_EVENT_INVALID_PACKET = 7, ZT_EVENT_INVALID_PACKET = 7,
/** /**
* Trace (debugging) message * Trace (debugging) message
@ -269,7 +274,7 @@ enum ZT1_Event
* *
* Meta-data: C string, TRACE message * Meta-data: C string, TRACE message
*/ */
ZT1_EVENT_TRACE = 8 ZT_EVENT_TRACE = 8
}; };
/** /**
@ -300,58 +305,58 @@ typedef struct
* True if some kind of connectivity appears available * True if some kind of connectivity appears available
*/ */
int online; int online;
} ZT1_NodeStatus; } ZT_NodeStatus;
/** /**
* Virtual network status codes * Virtual network status codes
*/ */
enum ZT1_VirtualNetworkStatus enum ZT_VirtualNetworkStatus
{ {
/** /**
* Waiting for network configuration (also means revision == 0) * Waiting for network configuration (also means revision == 0)
*/ */
ZT1_NETWORK_STATUS_REQUESTING_CONFIGURATION = 0, ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION = 0,
/** /**
* Configuration received and we are authorized * Configuration received and we are authorized
*/ */
ZT1_NETWORK_STATUS_OK = 1, ZT_NETWORK_STATUS_OK = 1,
/** /**
* Netconf master told us 'nope' * Netconf master told us 'nope'
*/ */
ZT1_NETWORK_STATUS_ACCESS_DENIED = 2, ZT_NETWORK_STATUS_ACCESS_DENIED = 2,
/** /**
* Netconf master exists, but this virtual network does not * Netconf master exists, but this virtual network does not
*/ */
ZT1_NETWORK_STATUS_NOT_FOUND = 3, ZT_NETWORK_STATUS_NOT_FOUND = 3,
/** /**
* Initialization of network failed or other internal error * Initialization of network failed or other internal error
*/ */
ZT1_NETWORK_STATUS_PORT_ERROR = 4, ZT_NETWORK_STATUS_PORT_ERROR = 4,
/** /**
* ZeroTier One version too old * ZeroTier One version too old
*/ */
ZT1_NETWORK_STATUS_CLIENT_TOO_OLD = 5 ZT_NETWORK_STATUS_CLIENT_TOO_OLD = 5
}; };
/** /**
* Virtual network type codes * Virtual network type codes
*/ */
enum ZT1_VirtualNetworkType enum ZT_VirtualNetworkType
{ {
/** /**
* Private networks are authorized via certificates of membership * Private networks are authorized via certificates of membership
*/ */
ZT1_NETWORK_TYPE_PRIVATE = 0, ZT_NETWORK_TYPE_PRIVATE = 0,
/** /**
* Public networks have no access control -- they'll always be AUTHORIZED * Public networks have no access control -- they'll always be AUTHORIZED
*/ */
ZT1_NETWORK_TYPE_PUBLIC = 1 ZT_NETWORK_TYPE_PUBLIC = 1
}; };
/** /**
@ -368,32 +373,32 @@ typedef struct
* Additional distinguishing information (usually zero) * Additional distinguishing information (usually zero)
*/ */
unsigned long adi; unsigned long adi;
} ZT1_MulticastGroup; } ZT_MulticastGroup;
/** /**
* Virtual network configuration update type * Virtual network configuration update type
*/ */
enum ZT1_VirtualNetworkConfigOperation enum ZT_VirtualNetworkConfigOperation
{ {
/** /**
* Network is coming up (either for the first time or after service restart) * Network is coming up (either for the first time or after service restart)
*/ */
ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP = 1, ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP = 1,
/** /**
* Network configuration has been updated * Network configuration has been updated
*/ */
ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE = 2, ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE = 2,
/** /**
* Network is going down (not permanently) * Network is going down (not permanently)
*/ */
ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN = 3, ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN = 3,
/** /**
* Network is going down permanently (leave/delete) * Network is going down permanently (leave/delete)
*/ */
ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY = 4 ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY = 4
}; };
/** /**
@ -414,17 +419,17 @@ typedef struct
/** /**
* Network name (from network configuration master) * Network name (from network configuration master)
*/ */
char name[ZT1_MAX_NETWORK_SHORT_NAME_LENGTH + 1]; char name[ZT_MAX_NETWORK_SHORT_NAME_LENGTH + 1];
/** /**
* Network configuration request status * Network configuration request status
*/ */
enum ZT1_VirtualNetworkStatus status; enum ZT_VirtualNetworkStatus status;
/** /**
* Network type * Network type
*/ */
enum ZT1_VirtualNetworkType type; enum ZT_VirtualNetworkType type;
/** /**
* Maximum interface MTU * Maximum interface MTU
@ -478,7 +483,7 @@ typedef struct
/** /**
* Multicast group subscriptions * Multicast group subscriptions
*/ */
ZT1_MulticastGroup multicastSubscriptions[ZT1_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS]; ZT_MulticastGroup multicastSubscriptions[ZT_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS];
/** /**
* Number of assigned addresses * Number of assigned addresses
@ -495,17 +500,17 @@ typedef struct
* This is only used for ZeroTier-managed address assignments sent by the * This is only used for ZeroTier-managed address assignments sent by the
* virtual network's configuration master. * virtual network's configuration master.
*/ */
struct sockaddr_storage assignedAddresses[ZT1_MAX_ZT_ASSIGNED_ADDRESSES]; struct sockaddr_storage assignedAddresses[ZT_MAX_ZT_ASSIGNED_ADDRESSES];
} ZT1_VirtualNetworkConfig; } ZT_VirtualNetworkConfig;
/** /**
* A list of networks * A list of networks
*/ */
typedef struct typedef struct
{ {
ZT1_VirtualNetworkConfig *networks; ZT_VirtualNetworkConfig *networks;
unsigned long networkCount; unsigned long networkCount;
} ZT1_VirtualNetworkList; } ZT_VirtualNetworkList;
/** /**
* Physical network path to a peer * Physical network path to a peer
@ -541,15 +546,15 @@ typedef struct
* Is path preferred? * Is path preferred?
*/ */
int preferred; int preferred;
} ZT1_PeerPhysicalPath; } ZT_PeerPhysicalPath;
/** /**
* What trust hierarchy role does this peer have? * What trust hierarchy role does this peer have?
*/ */
enum ZT1_PeerRole { enum ZT_PeerRole {
ZT1_PEER_ROLE_LEAF = 0, // ordinary node ZT_PEER_ROLE_LEAF = 0, // ordinary node
ZT1_PEER_ROLE_RELAY = 1, // relay node ZT_PEER_ROLE_RELAY = 1, // relay node
ZT1_PEER_ROLE_ROOT = 2 // root server ZT_PEER_ROLE_ROOT = 2 // root server
}; };
/** /**
@ -595,7 +600,7 @@ typedef struct
/** /**
* What trust hierarchy role does this device have? * What trust hierarchy role does this device have?
*/ */
enum ZT1_PeerRole role; enum ZT_PeerRole role;
/** /**
* Number of paths (size of paths[]) * Number of paths (size of paths[])
@ -605,31 +610,31 @@ typedef struct
/** /**
* Known network paths to peer * Known network paths to peer
*/ */
ZT1_PeerPhysicalPath paths[ZT1_MAX_PEER_NETWORK_PATHS]; ZT_PeerPhysicalPath paths[ZT_MAX_PEER_NETWORK_PATHS];
} ZT1_Peer; } ZT_Peer;
/** /**
* List of peers * List of peers
*/ */
typedef struct typedef struct
{ {
ZT1_Peer *peers; ZT_Peer *peers;
unsigned long peerCount; unsigned long peerCount;
} ZT1_PeerList; } ZT_PeerList;
/** /**
* Local interface trust levels * Local interface trust levels
*/ */
typedef enum { typedef enum {
ZT1_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL = 0, ZT_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL = 0,
ZT1_LOCAL_INTERFACE_ADDRESS_TRUST_PRIVACY = 1, ZT_LOCAL_INTERFACE_ADDRESS_TRUST_PRIVACY = 1,
ZT1_LOCAL_INTERFACE_ADDRESS_TRUST_ULTIMATE = 2 ZT_LOCAL_INTERFACE_ADDRESS_TRUST_ULTIMATE = 2
} ZT1_LocalInterfaceAddressTrust; } ZT_LocalInterfaceAddressTrust;
/** /**
* An instance of a ZeroTier One node (opaque) * An instance of a ZeroTier One node (opaque)
*/ */
typedef void ZT1_Node; typedef void ZT_Node;
/****************************************************************************/ /****************************************************************************/
/* Callbacks used by Node API */ /* Callbacks used by Node API */
@ -656,12 +661,12 @@ typedef void ZT1_Node;
* on failure, and this results in the network being placed into the * on failure, and this results in the network being placed into the
* PORT_ERROR state. * PORT_ERROR state.
*/ */
typedef int (*ZT1_VirtualNetworkConfigFunction)( typedef int (*ZT_VirtualNetworkConfigFunction)(
ZT1_Node *, ZT_Node *,
void *, void *,
uint64_t, uint64_t,
enum ZT1_VirtualNetworkConfigOperation, enum ZT_VirtualNetworkConfigOperation,
const ZT1_VirtualNetworkConfig *); const ZT_VirtualNetworkConfig *);
/** /**
* Function to send a frame out to a virtual network port * Function to send a frame out to a virtual network port
@ -670,8 +675,8 @@ typedef int (*ZT1_VirtualNetworkConfigFunction)(
* (5) destination MAC, (6) ethertype, (7) VLAN ID, (8) frame data, * (5) destination MAC, (6) ethertype, (7) VLAN ID, (8) frame data,
* (9) frame length. * (9) frame length.
*/ */
typedef void (*ZT1_VirtualNetworkFrameFunction)( typedef void (*ZT_VirtualNetworkFrameFunction)(
ZT1_Node *, ZT_Node *,
void *, void *,
uint64_t, uint64_t,
uint64_t, uint64_t,
@ -688,12 +693,12 @@ typedef void (*ZT1_VirtualNetworkFrameFunction)(
* and on certain non-fatal errors and events of interest. The final void * and on certain non-fatal errors and events of interest. The final void
* parameter points to event meta-data. The type of event meta-data (and * parameter points to event meta-data. The type of event meta-data (and
* whether it is present at all) is event type dependent. See the comments * whether it is present at all) is event type dependent. See the comments
* in the definition of ZT1_Event. * in the definition of ZT_Event.
*/ */
typedef void (*ZT1_EventCallback)( typedef void (*ZT_EventCallback)(
ZT1_Node *, ZT_Node *,
void *, void *,
enum ZT1_Event, enum ZT_Event,
const void *); const void *);
/** /**
@ -716,8 +721,8 @@ typedef void (*ZT1_EventCallback)(
* read. The caller may call the function multiple times to read the whole * read. The caller may call the function multiple times to read the whole
* object. * object.
*/ */
typedef long (*ZT1_DataStoreGetFunction)( typedef long (*ZT_DataStoreGetFunction)(
ZT1_Node *, ZT_Node *,
void *, void *,
const char *, const char *,
void *, void *,
@ -741,8 +746,8 @@ typedef long (*ZT1_DataStoreGetFunction)(
* If the data pointer is null, this must be interpreted as a delete * If the data pointer is null, this must be interpreted as a delete
* operation. * operation.
*/ */
typedef int (*ZT1_DataStorePutFunction)( typedef int (*ZT_DataStorePutFunction)(
ZT1_Node *, ZT_Node *,
void *, void *,
const char *, const char *,
const void *, const void *,
@ -755,23 +760,25 @@ typedef int (*ZT1_DataStorePutFunction)(
* Parameters: * Parameters:
* (1) Node * (1) Node
* (2) User pointer * (2) User pointer
* (3) Local interface ID, -1==unspcified/random * (3) Local interface address
* (4) Remote address * (4) Remote address
* (5) Packet data * (5) Packet data
* (6) Packet length * (6) Packet length
* *
* If you have only one local interface it is fine to ignore the local * If there is only one local interface it is safe to ignore the local
* interface ID field. This is used to support different local interface * interface address. Otherwise if running with multiple interfaces, the
* endpoints and differentiation between them. * correct local interface should be chosen by address unless NULL. If
* the ss_family field is zero (NULL address), a random or preferred
* default interface should be used.
* *
* The function must return zero on success and may return any error code * The function must return zero on success and may return any error code
* on failure. Note that success does not (of course) guarantee packet * on failure. Note that success does not (of course) guarantee packet
* delivery. It only means that the packet appears to have been sent. * delivery. It only means that the packet appears to have been sent.
*/ */
typedef int (*ZT1_WirePacketSendFunction)( typedef int (*ZT_WirePacketSendFunction)(
ZT1_Node *, /* Node */ ZT_Node *, /* Node */
void *, /* User ptr */ void *, /* User ptr */
int, /* Local interface ID, -1 for unspecified/random */ const struct sockaddr_storage *, /* Local address */
const struct sockaddr_storage *, /* Remote address */ const struct sockaddr_storage *, /* Remote address */
const void *, /* Packet data */ const void *, /* Packet data */
unsigned int); /* Packet length */ unsigned int); /* Packet length */
@ -796,16 +803,16 @@ typedef int (*ZT1_WirePacketSendFunction)(
* @param overrideRootTopology Alternative root server topology or NULL for default (mostly for test/debug use) * @param overrideRootTopology Alternative root server topology or NULL for default (mostly for test/debug use)
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
enum ZT1_ResultCode ZT1_Node_new( enum ZT_ResultCode ZT_Node_new(
ZT1_Node **node, ZT_Node **node,
void *uptr, void *uptr,
uint64_t now, uint64_t now,
ZT1_DataStoreGetFunction dataStoreGetFunction, ZT_DataStoreGetFunction dataStoreGetFunction,
ZT1_DataStorePutFunction dataStorePutFunction, ZT_DataStorePutFunction dataStorePutFunction,
ZT1_WirePacketSendFunction wirePacketSendFunction, ZT_WirePacketSendFunction wirePacketSendFunction,
ZT1_VirtualNetworkFrameFunction virtualNetworkFrameFunction, ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
ZT1_VirtualNetworkConfigFunction virtualNetworkConfigFunction, ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
ZT1_EventCallback eventCallback, ZT_EventCallback eventCallback,
const char *overrideRootTopology); const char *overrideRootTopology);
/** /**
@ -816,24 +823,24 @@ enum ZT1_ResultCode ZT1_Node_new(
* *
* @param node Node to delete * @param node Node to delete
*/ */
void ZT1_Node_delete(ZT1_Node *node); void ZT_Node_delete(ZT_Node *node);
/** /**
* Process a packet received from the physical wire * Process a packet received from the physical wire
* *
* @param node Node instance * @param node Node instance
* @param now Current clock in milliseconds * @param now Current clock in milliseconds
* @param localInterfaceId Local interface ID on which packet was received (use 0 if only one interface or unsure) * @param localAddress Local address, or point to ZT_SOCKADDR_NULL if unspecified
* @param remoteAddress Origin of packet * @param remoteAddress Origin of packet
* @param packetData Packet data * @param packetData Packet data
* @param packetLength Packet length * @param packetLength Packet length
* @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks() * @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks()
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
enum ZT1_ResultCode ZT1_Node_processWirePacket( enum ZT_ResultCode ZT_Node_processWirePacket(
ZT1_Node *node, ZT_Node *node,
uint64_t now, uint64_t now,
const int localInterfaceId, const struct sockaddr_storage *localAddress,
const struct sockaddr_storage *remoteAddress, const struct sockaddr_storage *remoteAddress,
const void *packetData, const void *packetData,
unsigned int packetLength, unsigned int packetLength,
@ -854,8 +861,8 @@ enum ZT1_ResultCode ZT1_Node_processWirePacket(
* @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks() * @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks()
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
enum ZT1_ResultCode ZT1_Node_processVirtualNetworkFrame( enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
ZT1_Node *node, ZT_Node *node,
uint64_t now, uint64_t now,
uint64_t nwid, uint64_t nwid,
uint64_t sourceMac, uint64_t sourceMac,
@ -874,7 +881,7 @@ enum ZT1_ResultCode ZT1_Node_processVirtualNetworkFrame(
* @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks() * @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks()
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
enum ZT1_ResultCode ZT1_Node_processBackgroundTasks(ZT1_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline); enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline);
/** /**
* Join a network * Join a network
@ -889,7 +896,7 @@ enum ZT1_ResultCode ZT1_Node_processBackgroundTasks(ZT1_Node *node,uint64_t now,
* @param nwid 64-bit ZeroTier network ID * @param nwid 64-bit ZeroTier network ID
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
enum ZT1_ResultCode ZT1_Node_join(ZT1_Node *node,uint64_t nwid); enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid);
/** /**
* Leave a network * Leave a network
@ -902,7 +909,7 @@ enum ZT1_ResultCode ZT1_Node_join(ZT1_Node *node,uint64_t nwid);
* @param nwid 64-bit network ID * @param nwid 64-bit network ID
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
enum ZT1_ResultCode ZT1_Node_leave(ZT1_Node *node,uint64_t nwid); enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid);
/** /**
* Subscribe to an Ethernet multicast group * Subscribe to an Ethernet multicast group
@ -929,7 +936,7 @@ enum ZT1_ResultCode ZT1_Node_leave(ZT1_Node *node,uint64_t nwid);
* @param multicastAdi Multicast ADI (least significant 32 bits only, use 0 if not needed) * @param multicastAdi Multicast ADI (least significant 32 bits only, use 0 if not needed)
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
enum ZT1_ResultCode ZT1_Node_multicastSubscribe(ZT1_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi); enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
/** /**
* Unsubscribe from an Ethernet multicast group (or all groups) * Unsubscribe from an Ethernet multicast group (or all groups)
@ -945,7 +952,7 @@ enum ZT1_ResultCode ZT1_Node_multicastSubscribe(ZT1_Node *node,uint64_t nwid,uin
* @param multicastAdi Multicast ADI (least significant 32 bits only, use 0 if not needed) * @param multicastAdi Multicast ADI (least significant 32 bits only, use 0 if not needed)
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
enum ZT1_ResultCode ZT1_Node_multicastUnsubscribe(ZT1_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi); enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
/** /**
* Get this node's 40-bit ZeroTier address * Get this node's 40-bit ZeroTier address
@ -953,7 +960,7 @@ enum ZT1_ResultCode ZT1_Node_multicastUnsubscribe(ZT1_Node *node,uint64_t nwid,u
* @param node Node instance * @param node Node instance
* @return ZeroTier address (least significant 40 bits of 64-bit int) * @return ZeroTier address (least significant 40 bits of 64-bit int)
*/ */
uint64_t ZT1_Node_address(ZT1_Node *node); uint64_t ZT_Node_address(ZT_Node *node);
/** /**
* Get the status of this node * Get the status of this node
@ -961,7 +968,7 @@ uint64_t ZT1_Node_address(ZT1_Node *node);
* @param node Node instance * @param node Node instance
* @param status Buffer to fill with current node status * @param status Buffer to fill with current node status
*/ */
void ZT1_Node_status(ZT1_Node *node,ZT1_NodeStatus *status); void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status);
/** /**
* Get a list of known peer nodes * Get a list of known peer nodes
@ -972,7 +979,7 @@ void ZT1_Node_status(ZT1_Node *node,ZT1_NodeStatus *status);
* @param node Node instance * @param node Node instance
* @return List of known peers or NULL on failure * @return List of known peers or NULL on failure
*/ */
ZT1_PeerList *ZT1_Node_peers(ZT1_Node *node); ZT_PeerList *ZT_Node_peers(ZT_Node *node);
/** /**
* Get the status of a virtual network * Get the status of a virtual network
@ -984,7 +991,7 @@ ZT1_PeerList *ZT1_Node_peers(ZT1_Node *node);
* @param nwid 64-bit network ID * @param nwid 64-bit network ID
* @return Network configuration or NULL if we are not a member of this network * @return Network configuration or NULL if we are not a member of this network
*/ */
ZT1_VirtualNetworkConfig *ZT1_Node_networkConfig(ZT1_Node *node,uint64_t nwid); ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid);
/** /**
* Enumerate and get status of all networks * Enumerate and get status of all networks
@ -992,7 +999,7 @@ ZT1_VirtualNetworkConfig *ZT1_Node_networkConfig(ZT1_Node *node,uint64_t nwid);
* @param node Node instance * @param node Node instance
* @return List of networks or NULL on failure * @return List of networks or NULL on failure
*/ */
ZT1_VirtualNetworkList *ZT1_Node_networks(ZT1_Node *node); ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node);
/** /**
* Free a query result buffer * Free a query result buffer
@ -1002,7 +1009,7 @@ ZT1_VirtualNetworkList *ZT1_Node_networks(ZT1_Node *node);
* @param node Node instance * @param node Node instance
* @param qr Query result buffer * @param qr Query result buffer
*/ */
void ZT1_Node_freeQueryResult(ZT1_Node *node,void *qr); void ZT_Node_freeQueryResult(ZT_Node *node,void *qr);
/** /**
* Add a local interface address * Add a local interface address
@ -1030,12 +1037,12 @@ void ZT1_Node_freeQueryResult(ZT1_Node *node,void *qr);
* @param trust How much do you trust the local network under this interface? * @param trust How much do you trust the local network under this interface?
* @return Boolean: non-zero if address was accepted and added * @return Boolean: non-zero if address was accepted and added
*/ */
int ZT1_Node_addLocalInterfaceAddress(ZT1_Node *node,const struct sockaddr_storage *addr,int metric,ZT1_LocalInterfaceAddressTrust trust); int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr,int metric,ZT_LocalInterfaceAddressTrust trust);
/** /**
* Clear local interface addresses * Clear local interface addresses
*/ */
void ZT1_Node_clearLocalInterfaceAddresses(ZT1_Node *node); void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node);
/** /**
* Set a network configuration master instance for this node * Set a network configuration master instance for this node
@ -1052,7 +1059,7 @@ void ZT1_Node_clearLocalInterfaceAddresses(ZT1_Node *node);
* @param networkConfigMasterInstance Instance of NetworkConfigMaster C++ class or NULL to disable * @param networkConfigMasterInstance Instance of NetworkConfigMaster C++ class or NULL to disable
* @return OK (0) or error code if a fatal error condition has occurred * @return OK (0) or error code if a fatal error condition has occurred
*/ */
void ZT1_Node_setNetconfMaster(ZT1_Node *node,void *networkConfigMasterInstance); void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkConfigMasterInstance);
/** /**
* Get ZeroTier One version * Get ZeroTier One version
@ -1062,7 +1069,7 @@ void ZT1_Node_setNetconfMaster(ZT1_Node *node,void *networkConfigMasterInstance)
* @param revision Result: revision * @param revision Result: revision
* @param featureFlags: Result: feature flag bitmap * @param featureFlags: Result: feature flag bitmap
*/ */
void ZT1_version(int *major,int *minor,int *revision,unsigned long *featureFlags); void ZT_version(int *major,int *minor,int *revision,unsigned long *featureFlags);
#ifdef __cplusplus #ifdef __cplusplus
} }

View file

@ -53,8 +53,8 @@ set(src_files
../osdep/Http.cpp ../osdep/Http.cpp
../osdep/OSUtils.cpp ../osdep/OSUtils.cpp
jni/com_zerotierone_sdk_Node.cpp jni/com_zerotierone_sdk_Node.cpp
jni/ZT1_jniutils.cpp jni/ZT_jniutils.cpp
jni/ZT1_jnicache.cpp jni/ZT_jnicache.cpp
) )
set(include_dirs set(include_dirs

View file

@ -38,7 +38,7 @@ LOCAL_SRC_FILES := \
# JNI Files # JNI Files
LOCAL_SRC_FILES += \ LOCAL_SRC_FILES += \
com_zerotierone_sdk_Node.cpp \ com_zerotierone_sdk_Node.cpp \
ZT1_jniutils.cpp \ ZT_jniutils.cpp \
ZT1_jnicache.cpp ZT_jnicache.cpp
include $(BUILD_SHARED_LIBRARY) include $(BUILD_SHARED_LIBRARY)

View file

@ -25,8 +25,8 @@
* LLC. Start here: http://www.zerotier.com/ * LLC. Start here: http://www.zerotier.com/
*/ */
#include "ZT1_jnicache.h" #include "ZT_jnicache.h"
#include "ZT1_jniutils.h" #include "ZT_jniutils.h"
JniCache::JniCache() JniCache::JniCache()
: m_jvm(NULL) : m_jvm(NULL)

View file

@ -25,8 +25,8 @@
* LLC. Start here: http://www.zerotier.com/ * LLC. Start here: http://www.zerotier.com/
*/ */
#ifndef ZT1_JNICACHE_H_ #ifndef ZT_JNICACHE_H_
#define ZT1_JNICACHE_H_ #define ZT_JNICACHE_H_
#include <jni.h> #include <jni.h>
#include <map> #include <map>

View file

@ -1,5 +1,5 @@
#include "ZT1_jniutils.h" #include "ZT_jniutils.h"
#include "ZT1_jnicache.h" #include "ZT_jnicache.h"
#include <string> #include <string>
#include <assert.h> #include <assert.h>
@ -9,7 +9,7 @@ extern JniCache cache;
extern "C" { extern "C" {
#endif #endif
jobject createResultObject(JNIEnv *env, ZT1_ResultCode code) jobject createResultObject(JNIEnv *env, ZT_ResultCode code)
{ {
jclass resultClass = NULL; jclass resultClass = NULL;
@ -25,23 +25,23 @@ jobject createResultObject(JNIEnv *env, ZT1_ResultCode code)
std::string fieldName; std::string fieldName;
switch(code) switch(code)
{ {
case ZT1_RESULT_OK: case ZT_RESULT_OK:
LOGV("ZT1_RESULT_OK"); LOGV("ZT_RESULT_OK");
fieldName = "RESULT_OK"; fieldName = "RESULT_OK";
break; break;
case ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY: case ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY:
LOGV("ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY"); LOGV("ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY");
fieldName = "RESULT_FATAL_ERROR_OUT_OF_MEMORY"; fieldName = "RESULT_FATAL_ERROR_OUT_OF_MEMORY";
break; break;
case ZT1_RESULT_FATAL_ERROR_DATA_STORE_FAILED: case ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED:
LOGV("RESULT_FATAL_ERROR_DATA_STORE_FAILED"); LOGV("RESULT_FATAL_ERROR_DATA_STORE_FAILED");
fieldName = "RESULT_FATAL_ERROR_DATA_STORE_FAILED"; fieldName = "RESULT_FATAL_ERROR_DATA_STORE_FAILED";
break; break;
case ZT1_RESULT_ERROR_NETWORK_NOT_FOUND: case ZT_RESULT_ERROR_NETWORK_NOT_FOUND:
LOGV("RESULT_FATAL_ERROR_DATA_STORE_FAILED"); LOGV("RESULT_FATAL_ERROR_DATA_STORE_FAILED");
fieldName = "RESULT_ERROR_NETWORK_NOT_FOUND"; fieldName = "RESULT_ERROR_NETWORK_NOT_FOUND";
break; break;
case ZT1_RESULT_FATAL_ERROR_INTERNAL: case ZT_RESULT_FATAL_ERROR_INTERNAL:
default: default:
LOGV("RESULT_FATAL_ERROR_DATA_STORE_FAILED"); LOGV("RESULT_FATAL_ERROR_DATA_STORE_FAILED");
fieldName = "RESULT_FATAL_ERROR_INTERNAL"; fieldName = "RESULT_FATAL_ERROR_INTERNAL";
@ -64,7 +64,7 @@ jobject createResultObject(JNIEnv *env, ZT1_ResultCode code)
} }
jobject createVirtualNetworkStatus(JNIEnv *env, ZT1_VirtualNetworkStatus status) jobject createVirtualNetworkStatus(JNIEnv *env, ZT_VirtualNetworkStatus status)
{ {
jobject statusObject = NULL; jobject statusObject = NULL;
@ -77,22 +77,22 @@ jobject createVirtualNetworkStatus(JNIEnv *env, ZT1_VirtualNetworkStatus status)
std::string fieldName; std::string fieldName;
switch(status) switch(status)
{ {
case ZT1_NETWORK_STATUS_REQUESTING_CONFIGURATION: case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION:
fieldName = "NETWORK_STATUS_REQUESTING_CONFIGURATION"; fieldName = "NETWORK_STATUS_REQUESTING_CONFIGURATION";
break; break;
case ZT1_NETWORK_STATUS_OK: case ZT_NETWORK_STATUS_OK:
fieldName = "NETWORK_STATUS_OK"; fieldName = "NETWORK_STATUS_OK";
break; break;
case ZT1_NETWORK_STATUS_ACCESS_DENIED: case ZT_NETWORK_STATUS_ACCESS_DENIED:
fieldName = "NETWORK_STATUS_ACCESS_DENIED"; fieldName = "NETWORK_STATUS_ACCESS_DENIED";
break; break;
case ZT1_NETWORK_STATUS_NOT_FOUND: case ZT_NETWORK_STATUS_NOT_FOUND:
fieldName = "NETWORK_STATUS_NOT_FOUND"; fieldName = "NETWORK_STATUS_NOT_FOUND";
break; break;
case ZT1_NETWORK_STATUS_PORT_ERROR: case ZT_NETWORK_STATUS_PORT_ERROR:
fieldName = "NETWORK_STATUS_PORT_ERROR"; fieldName = "NETWORK_STATUS_PORT_ERROR";
break; break;
case ZT1_NETWORK_STATUS_CLIENT_TOO_OLD: case ZT_NETWORK_STATUS_CLIENT_TOO_OLD:
fieldName = "NETWORK_STATUS_CLIENT_TOO_OLD"; fieldName = "NETWORK_STATUS_CLIENT_TOO_OLD";
break; break;
} }
@ -104,7 +104,7 @@ jobject createVirtualNetworkStatus(JNIEnv *env, ZT1_VirtualNetworkStatus status)
return statusObject; return statusObject;
} }
jobject createEvent(JNIEnv *env, ZT1_Event event) jobject createEvent(JNIEnv *env, ZT_Event event)
{ {
jclass eventClass = NULL; jclass eventClass = NULL;
jobject eventObject = NULL; jobject eventObject = NULL;
@ -118,31 +118,31 @@ jobject createEvent(JNIEnv *env, ZT1_Event event)
std::string fieldName; std::string fieldName;
switch(event) switch(event)
{ {
case ZT1_EVENT_UP: case ZT_EVENT_UP:
fieldName = "EVENT_UP"; fieldName = "EVENT_UP";
break; break;
case ZT1_EVENT_OFFLINE: case ZT_EVENT_OFFLINE:
fieldName = "EVENT_OFFLINE"; fieldName = "EVENT_OFFLINE";
break; break;
case ZT1_EVENT_ONLINE: case ZT_EVENT_ONLINE:
fieldName = "EVENT_ONLINE"; fieldName = "EVENT_ONLINE";
break; break;
case ZT1_EVENT_DOWN: case ZT_EVENT_DOWN:
fieldName = "EVENT_DOWN"; fieldName = "EVENT_DOWN";
break; break;
case ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION: case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION:
fieldName = "EVENT_FATAL_ERROR_IDENTITY_COLLISION"; fieldName = "EVENT_FATAL_ERROR_IDENTITY_COLLISION";
break; break;
case ZT1_EVENT_SAW_MORE_RECENT_VERSION: case ZT_EVENT_SAW_MORE_RECENT_VERSION:
fieldName = "EVENT_SAW_MORE_RECENT_VERSION"; fieldName = "EVENT_SAW_MORE_RECENT_VERSION";
break; break;
case ZT1_EVENT_AUTHENTICATION_FAILURE: case ZT_EVENT_AUTHENTICATION_FAILURE:
fieldName = "EVENT_AUTHENTICATION_FAILURE"; fieldName = "EVENT_AUTHENTICATION_FAILURE";
break; break;
case ZT1_EVENT_INVALID_PACKET: case ZT_EVENT_INVALID_PACKET:
fieldName = "EVENT_INVALID_PACKET"; fieldName = "EVENT_INVALID_PACKET";
break; break;
case ZT1_EVENT_TRACE: case ZT_EVENT_TRACE:
fieldName = "EVENT_TRACE"; fieldName = "EVENT_TRACE";
break; break;
} }
@ -154,7 +154,7 @@ jobject createEvent(JNIEnv *env, ZT1_Event event)
return eventObject; return eventObject;
} }
jobject createPeerRole(JNIEnv *env, ZT1_PeerRole role) jobject createPeerRole(JNIEnv *env, ZT_PeerRole role)
{ {
jclass peerRoleClass = NULL; jclass peerRoleClass = NULL;
jobject peerRoleObject = NULL; jobject peerRoleObject = NULL;
@ -168,13 +168,13 @@ jobject createPeerRole(JNIEnv *env, ZT1_PeerRole role)
std::string fieldName; std::string fieldName;
switch(role) switch(role)
{ {
case ZT1_PEER_ROLE_LEAF: case ZT_PEER_ROLE_LEAF:
fieldName = "PEER_ROLE_LEAF"; fieldName = "PEER_ROLE_LEAF";
break; break;
case ZT1_PEER_ROLE_HUB: case ZT_PEER_ROLE_HUB:
fieldName = "PEER_ROLE_HUB"; fieldName = "PEER_ROLE_HUB";
break; break;
case ZT1_PEER_ROLE_ROOTSERVER: case ZT_PEER_ROLE_ROOTSERVER:
fieldName = "PEER_ROLE_ROOTSERVER"; fieldName = "PEER_ROLE_ROOTSERVER";
break; break;
} }
@ -186,7 +186,7 @@ jobject createPeerRole(JNIEnv *env, ZT1_PeerRole role)
return peerRoleObject; return peerRoleObject;
} }
jobject createVirtualNetworkType(JNIEnv *env, ZT1_VirtualNetworkType type) jobject createVirtualNetworkType(JNIEnv *env, ZT_VirtualNetworkType type)
{ {
jclass vntypeClass = NULL; jclass vntypeClass = NULL;
jobject vntypeObject = NULL; jobject vntypeObject = NULL;
@ -200,10 +200,10 @@ jobject createVirtualNetworkType(JNIEnv *env, ZT1_VirtualNetworkType type)
std::string fieldName; std::string fieldName;
switch(type) switch(type)
{ {
case ZT1_NETWORK_TYPE_PRIVATE: case ZT_NETWORK_TYPE_PRIVATE:
fieldName = "NETWORK_TYPE_PRIVATE"; fieldName = "NETWORK_TYPE_PRIVATE";
break; break;
case ZT1_NETWORK_TYPE_PUBLIC: case ZT_NETWORK_TYPE_PUBLIC:
fieldName = "NETWORK_TYPE_PUBLIC"; fieldName = "NETWORK_TYPE_PUBLIC";
break; break;
} }
@ -213,7 +213,7 @@ jobject createVirtualNetworkType(JNIEnv *env, ZT1_VirtualNetworkType type)
return vntypeObject; return vntypeObject;
} }
jobject createVirtualNetworkConfigOperation(JNIEnv *env, ZT1_VirtualNetworkConfigOperation op) jobject createVirtualNetworkConfigOperation(JNIEnv *env, ZT_VirtualNetworkConfigOperation op)
{ {
jclass vnetConfigOpClass = NULL; jclass vnetConfigOpClass = NULL;
jobject vnetConfigOpObject = NULL; jobject vnetConfigOpObject = NULL;
@ -227,16 +227,16 @@ jobject createVirtualNetworkConfigOperation(JNIEnv *env, ZT1_VirtualNetworkConfi
std::string fieldName; std::string fieldName;
switch(op) switch(op)
{ {
case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
fieldName = "VIRTUAL_NETWORK_CONFIG_OPERATION_UP"; fieldName = "VIRTUAL_NETWORK_CONFIG_OPERATION_UP";
break; break;
case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
fieldName = "VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE"; fieldName = "VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE";
break; break;
case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
fieldName = "VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN"; fieldName = "VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN";
break; break;
case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
fieldName = "VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY"; fieldName = "VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY";
break; break;
} }
@ -372,7 +372,7 @@ jobject newInetSocketAddress(JNIEnv *env, const sockaddr_storage &addr)
return inetSocketAddressObject; return inetSocketAddressObject;
} }
jobject newMulticastGroup(JNIEnv *env, const ZT1_MulticastGroup &mc) jobject newMulticastGroup(JNIEnv *env, const ZT_MulticastGroup &mc)
{ {
jclass multicastGroupClass = NULL; jclass multicastGroupClass = NULL;
jmethodID multicastGroup_constructor = NULL; jmethodID multicastGroup_constructor = NULL;
@ -417,7 +417,7 @@ jobject newMulticastGroup(JNIEnv *env, const ZT1_MulticastGroup &mc)
return multicastGroupObj; return multicastGroupObj;
} }
jobject newPeerPhysicalPath(JNIEnv *env, const ZT1_PeerPhysicalPath &ppp) jobject newPeerPhysicalPath(JNIEnv *env, const ZT_PeerPhysicalPath &ppp)
{ {
LOGV("newPeerPhysicalPath Called"); LOGV("newPeerPhysicalPath Called");
jclass pppClass = NULL; jclass pppClass = NULL;
@ -514,7 +514,7 @@ jobject newPeerPhysicalPath(JNIEnv *env, const ZT1_PeerPhysicalPath &ppp)
return pppObject; return pppObject;
} }
jobject newPeer(JNIEnv *env, const ZT1_Peer &peer) jobject newPeer(JNIEnv *env, const ZT_Peer &peer)
{ {
LOGV("newPeer called"); LOGV("newPeer called");
@ -656,7 +656,7 @@ jobject newPeer(JNIEnv *env, const ZT1_Peer &peer)
return peerObject; return peerObject;
} }
jobject newNetworkConfig(JNIEnv *env, const ZT1_VirtualNetworkConfig &vnetConfig) jobject newNetworkConfig(JNIEnv *env, const ZT_VirtualNetworkConfig &vnetConfig)
{ {
jclass vnetConfigClass = NULL; jclass vnetConfigClass = NULL;
jmethodID vnetConfig_constructor = NULL; jmethodID vnetConfig_constructor = NULL;

View file

@ -1,5 +1,5 @@
#ifndef ZT1_jniutils_h_ #ifndef ZT_jniutils_h_
#define ZT1_jniutils_h_ #define ZT_jniutils_h_
#include <stdio.h> #include <stdio.h>
#include <jni.h> #include <jni.h>
#include <ZeroTierOne.h> #include <ZeroTierOne.h>
@ -23,22 +23,22 @@ extern "C" {
#define LOGE(...) fprintf(stdout, __VA_ARGS__) #define LOGE(...) fprintf(stdout, __VA_ARGS__)
#endif #endif
jobject createResultObject(JNIEnv *env, ZT1_ResultCode code); jobject createResultObject(JNIEnv *env, ZT_ResultCode code);
jobject createVirtualNetworkStatus(JNIEnv *env, ZT1_VirtualNetworkStatus status); jobject createVirtualNetworkStatus(JNIEnv *env, ZT_VirtualNetworkStatus status);
jobject createVirtualNetworkType(JNIEnv *env, ZT1_VirtualNetworkType type); jobject createVirtualNetworkType(JNIEnv *env, ZT_VirtualNetworkType type);
jobject createEvent(JNIEnv *env, ZT1_Event event); jobject createEvent(JNIEnv *env, ZT_Event event);
jobject createPeerRole(JNIEnv *env, ZT1_PeerRole role); jobject createPeerRole(JNIEnv *env, ZT_PeerRole role);
jobject createVirtualNetworkConfigOperation(JNIEnv *env, ZT1_VirtualNetworkConfigOperation op); jobject createVirtualNetworkConfigOperation(JNIEnv *env, ZT_VirtualNetworkConfigOperation op);
jobject newInetSocketAddress(JNIEnv *env, const sockaddr_storage &addr); jobject newInetSocketAddress(JNIEnv *env, const sockaddr_storage &addr);
jobject newInetAddress(JNIEnv *env, const sockaddr_storage &addr); jobject newInetAddress(JNIEnv *env, const sockaddr_storage &addr);
jobject newMulticastGroup(JNIEnv *env, const ZT1_MulticastGroup &mc); jobject newMulticastGroup(JNIEnv *env, const ZT_MulticastGroup &mc);
jobject newPeer(JNIEnv *env, const ZT1_Peer &peer); jobject newPeer(JNIEnv *env, const ZT_Peer &peer);
jobject newPeerPhysicalPath(JNIEnv *env, const ZT1_PeerPhysicalPath &ppp); jobject newPeerPhysicalPath(JNIEnv *env, const ZT_PeerPhysicalPath &ppp);
jobject newNetworkConfig(JNIEnv *env, const ZT1_VirtualNetworkConfig &config); jobject newNetworkConfig(JNIEnv *env, const ZT_VirtualNetworkConfig &config);
jobject newVersion(JNIEnv *env, int major, int minor, int rev, long featureFlags); jobject newVersion(JNIEnv *env, int major, int minor, int rev, long featureFlags);

View file

@ -26,8 +26,8 @@
*/ */
#include "com_zerotierone_sdk_Node.h" #include "com_zerotierone_sdk_Node.h"
#include "ZT1_jniutils.h" #include "ZT_jniutils.h"
#include "ZT1_jnicache.h" #include "ZT_jnicache.h"
#include <ZeroTierOne.h> #include <ZeroTierOne.h>
@ -74,7 +74,7 @@ namespace {
JavaVM *jvm; JavaVM *jvm;
ZT1_Node *node; ZT_Node *node;
jobject dataStoreGetListener; jobject dataStoreGetListener;
jobject dataStorePutListener; jobject dataStorePutListener;
@ -86,11 +86,11 @@ namespace {
int VirtualNetworkConfigFunctionCallback( int VirtualNetworkConfigFunctionCallback(
ZT1_Node *node, ZT_Node *node,
void *userData, void *userData,
uint64_t nwid, uint64_t nwid,
enum ZT1_VirtualNetworkConfigOperation operation, enum ZT_VirtualNetworkConfigOperation operation,
const ZT1_VirtualNetworkConfig *config) const ZT_VirtualNetworkConfig *config)
{ {
LOGD("VritualNetworkConfigFunctionCallback"); LOGD("VritualNetworkConfigFunctionCallback");
JniRef *ref = (JniRef*)userData; JniRef *ref = (JniRef*)userData;
@ -133,7 +133,7 @@ namespace {
(jlong)nwid, operationObject, networkConfigObject); (jlong)nwid, operationObject, networkConfigObject);
} }
void VirtualNetworkFrameFunctionCallback(ZT1_Node *node,void *userData, void VirtualNetworkFrameFunctionCallback(ZT_Node *node,void *userData,
uint64_t nwid, uint64_t nwid,
uint64_t sourceMac, uint64_t sourceMac,
uint64_t destMac, uint64_t destMac,
@ -186,7 +186,7 @@ namespace {
} }
void EventCallback(ZT1_Node *node,void *userData,enum ZT1_Event event, const void *data) void EventCallback(ZT_Node *node,void *userData,enum ZT_Event event, const void *data)
{ {
LOGD("EventCallback"); LOGD("EventCallback");
JniRef *ref = (JniRef*)userData; JniRef *ref = (JniRef*)userData;
@ -245,18 +245,18 @@ namespace {
switch(event) switch(event)
{ {
case ZT1_EVENT_UP: case ZT_EVENT_UP:
case ZT1_EVENT_OFFLINE: case ZT_EVENT_OFFLINE:
case ZT1_EVENT_ONLINE: case ZT_EVENT_ONLINE:
case ZT1_EVENT_DOWN: case ZT_EVENT_DOWN:
case ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION: case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION:
{ {
LOGV("Regular Event"); LOGV("Regular Event");
// call onEvent() // call onEvent()
env->CallVoidMethod(ref->eventListener, onEventMethod, eventObject); env->CallVoidMethod(ref->eventListener, onEventMethod, eventObject);
} }
break; break;
case ZT1_EVENT_SAW_MORE_RECENT_VERSION: case ZT_EVENT_SAW_MORE_RECENT_VERSION:
{ {
LOGV("Version Event"); LOGV("Version Event");
// call onOutOfDate() // call onOutOfDate()
@ -268,8 +268,8 @@ namespace {
} }
} }
break; break;
case ZT1_EVENT_AUTHENTICATION_FAILURE: case ZT_EVENT_AUTHENTICATION_FAILURE:
case ZT1_EVENT_INVALID_PACKET: case ZT_EVENT_INVALID_PACKET:
{ {
LOGV("Network Error Event"); LOGV("Network Error Event");
// call onNetworkError() // call onNetworkError()
@ -281,7 +281,7 @@ namespace {
} }
} }
break; break;
case ZT1_EVENT_TRACE: case ZT_EVENT_TRACE:
{ {
LOGV("Trace Event"); LOGV("Trace Event");
// call onTrace() // call onTrace()
@ -296,7 +296,7 @@ namespace {
} }
} }
long DataStoreGetFunction(ZT1_Node *node,void *userData, long DataStoreGetFunction(ZT_Node *node,void *userData,
const char *objectName, const char *objectName,
void *buffer, void *buffer,
unsigned long bufferSize, unsigned long bufferSize,
@ -368,7 +368,7 @@ namespace {
return retval; return retval;
} }
int DataStorePutFunction(ZT1_Node *node,void *userData, int DataStorePutFunction(ZT_Node *node,void *userData,
const char *objectName, const char *objectName,
const void *buffer, const void *buffer,
unsigned long bufferSize, unsigned long bufferSize,
@ -426,7 +426,7 @@ namespace {
} }
} }
int WirePacketSendFunction(ZT1_Node *node,void *userData,\ int WirePacketSendFunction(ZT_Node *node,void *userData,\
const struct sockaddr_storage *address, const struct sockaddr_storage *address,
const void *buffer, const void *buffer,
unsigned int bufferSize) unsigned int bufferSize)
@ -466,7 +466,7 @@ namespace {
typedef std::map<uint64_t, JniRef*> NodeMap; typedef std::map<uint64_t, JniRef*> NodeMap;
static NodeMap nodeMap; static NodeMap nodeMap;
ZT1_Node* findNode(uint64_t nodeId) ZT_Node* findNode(uint64_t nodeId)
{ {
NodeMap::iterator found = nodeMap.find(nodeId); NodeMap::iterator found = nodeMap.find(nodeId);
if(found != nodeMap.end()) if(found != nodeMap.end())
@ -498,10 +498,10 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_node_1init( JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_node_1init(
JNIEnv *env, jobject obj, jlong now) JNIEnv *env, jobject obj, jlong now)
{ {
LOGV("Creating ZT1_Node struct"); LOGV("Creating ZT_Node struct");
jobject resultObject = createResultObject(env, ZT1_RESULT_OK); jobject resultObject = createResultObject(env, ZT_RESULT_OK);
ZT1_Node *node; ZT_Node *node;
JniRef *ref = new JniRef; JniRef *ref = new JniRef;
ref->id = (uint64_t)now; ref->id = (uint64_t)now;
env->GetJavaVM(&ref->jvm); env->GetJavaVM(&ref->jvm);
@ -593,7 +593,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_node_1init(
} }
ref->eventListener = env->NewGlobalRef(tmp); ref->eventListener = env->NewGlobalRef(tmp);
ZT1_ResultCode rc = ZT1_Node_new( ZT_ResultCode rc = ZT_Node_new(
&node, &node,
ref, ref,
(uint64_t)now, (uint64_t)now,
@ -604,13 +604,13 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_node_1init(
&VirtualNetworkConfigFunctionCallback, &VirtualNetworkConfigFunctionCallback,
&EventCallback); &EventCallback);
if(rc != ZT1_RESULT_OK) if(rc != ZT_RESULT_OK)
{ {
LOGE("Error creating Node: %d", rc); LOGE("Error creating Node: %d", rc);
resultObject = createResultObject(env, rc); resultObject = createResultObject(env, rc);
if(node) if(node)
{ {
ZT1_Node_delete(node); ZT_Node_delete(node);
node = NULL; node = NULL;
} }
delete ref; delete ref;
@ -632,7 +632,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_node_1init(
JNIEXPORT void JNICALL Java_com_zerotier_sdk_Node_node_1delete( JNIEXPORT void JNICALL Java_com_zerotier_sdk_Node_node_1delete(
JNIEnv *env, jobject obj, jlong id) JNIEnv *env, jobject obj, jlong id)
{ {
LOGV("Destroying ZT1_Node struct"); LOGV("Destroying ZT_Node struct");
uint64_t nodeId = (uint64_t)id; uint64_t nodeId = (uint64_t)id;
NodeMap::iterator found = nodeMap.find(nodeId); NodeMap::iterator found = nodeMap.find(nodeId);
@ -641,7 +641,7 @@ JNIEXPORT void JNICALL Java_com_zerotier_sdk_Node_node_1delete(
JniRef *ref = found->second; JniRef *ref = found->second;
nodeMap.erase(found); nodeMap.erase(found);
ZT1_Node_delete(ref->node); ZT_Node_delete(ref->node);
delete ref; delete ref;
ref = NULL; ref = NULL;
@ -671,18 +671,18 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processVirtualNetworkFrame(
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
unsigned int nbtd_len = env->GetArrayLength(out_nextBackgroundTaskDeadline); unsigned int nbtd_len = env->GetArrayLength(out_nextBackgroundTaskDeadline);
if(nbtd_len < 1) if(nbtd_len < 1)
{ {
// array for next background task length has 0 elements! // array for next background task length has 0 elements!
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
uint64_t now = (uint64_t)in_now; uint64_t now = (uint64_t)in_now;
@ -697,7 +697,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processVirtualNetworkFrame(
uint64_t nextBackgroundTaskDeadline = 0; uint64_t nextBackgroundTaskDeadline = 0;
ZT1_ResultCode rc = ZT1_Node_processVirtualNetworkFrame( ZT_ResultCode rc = ZT_Node_processVirtualNetworkFrame(
node, node,
now, now,
nwid, nwid,
@ -732,17 +732,17 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
jlongArray out_nextBackgroundTaskDeadline) jlongArray out_nextBackgroundTaskDeadline)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
unsigned int nbtd_len = env->GetArrayLength(out_nextBackgroundTaskDeadline); unsigned int nbtd_len = env->GetArrayLength(out_nextBackgroundTaskDeadline);
if(nbtd_len < 1) if(nbtd_len < 1)
{ {
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
uint64_t now = (uint64_t)in_now; uint64_t now = (uint64_t)in_now;
@ -752,7 +752,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
if(inetAddressClass == NULL) if(inetAddressClass == NULL)
{ {
// can't find java.net.InetAddress // can't find java.net.InetAddress
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
jmethodID getAddressMethod = cache.findMethod( jmethodID getAddressMethod = cache.findMethod(
@ -760,13 +760,13 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
if(getAddressMethod == NULL) if(getAddressMethod == NULL)
{ {
// cant find InetAddress.getAddres() // cant find InetAddress.getAddres()
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
jclass InetSocketAddressClass = cache.findClass("java/net/InetSocketAddress"); jclass InetSocketAddressClass = cache.findClass("java/net/InetSocketAddress");
if(InetSocketAddressClass == NULL) if(InetSocketAddressClass == NULL)
{ {
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
jmethodID inetSockGetAddressMethod = cache.findMethod( jmethodID inetSockGetAddressMethod = cache.findMethod(
@ -776,7 +776,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
if(addrObject == NULL) if(addrObject == NULL)
{ {
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
jmethodID inetSock_getPort = cache.findMethod( jmethodID inetSock_getPort = cache.findMethod(
@ -785,7 +785,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
if(env->ExceptionCheck() || inetSock_getPort == NULL) if(env->ExceptionCheck() || inetSock_getPort == NULL)
{ {
LOGE("Couldn't find getPort method on InetSocketAddress"); LOGE("Couldn't find getPort method on InetSocketAddress");
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
// call InetSocketAddress.getPort() // call InetSocketAddress.getPort()
@ -793,7 +793,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
if(env->ExceptionCheck()) if(env->ExceptionCheck())
{ {
LOGE("Exception calling InetSocketAddress.getPort()"); LOGE("Exception calling InetSocketAddress.getPort()");
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
// Call InetAddress.getAddress() // Call InetAddress.getAddress()
@ -801,7 +801,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
if(addressArray == NULL) if(addressArray == NULL)
{ {
// unable to call getAddress() // unable to call getAddress()
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
unsigned int addrSize = env->GetArrayLength(addressArray); unsigned int addrSize = env->GetArrayLength(addressArray);
@ -833,7 +833,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
{ {
// unknown address type // unknown address type
env->ReleaseByteArrayElements(addressArray, addr, 0); env->ReleaseByteArrayElements(addressArray, addr, 0);
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
@ -842,7 +842,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processWirePacket(
uint64_t nextBackgroundTaskDeadline = 0; uint64_t nextBackgroundTaskDeadline = 0;
ZT1_ResultCode rc = ZT1_Node_processWirePacket( ZT_ResultCode rc = ZT_Node_processWirePacket(
node, node,
now, now,
&remoteAddress, &remoteAddress,
@ -872,23 +872,23 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_processBackgroundTasks(
jlongArray out_nextBackgroundTaskDeadline) jlongArray out_nextBackgroundTaskDeadline)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
unsigned int nbtd_len = env->GetArrayLength(out_nextBackgroundTaskDeadline); unsigned int nbtd_len = env->GetArrayLength(out_nextBackgroundTaskDeadline);
if(nbtd_len < 1) if(nbtd_len < 1)
{ {
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
uint64_t now = (uint64_t)in_now; uint64_t now = (uint64_t)in_now;
uint64_t nextBackgroundTaskDeadline = 0; uint64_t nextBackgroundTaskDeadline = 0;
ZT1_ResultCode rc = ZT1_Node_processBackgroundTasks(node, now, &nextBackgroundTaskDeadline); ZT_ResultCode rc = ZT_Node_processBackgroundTasks(node, now, &nextBackgroundTaskDeadline);
jlong *outDeadline = env->GetLongArrayElements(out_nextBackgroundTaskDeadline, NULL); jlong *outDeadline = env->GetLongArrayElements(out_nextBackgroundTaskDeadline, NULL);
outDeadline[0] = (jlong)nextBackgroundTaskDeadline; outDeadline[0] = (jlong)nextBackgroundTaskDeadline;
@ -906,16 +906,16 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_join(
JNIEnv *env, jobject obj, jlong id, jlong in_nwid) JNIEnv *env, jobject obj, jlong id, jlong in_nwid)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
uint64_t nwid = (uint64_t)in_nwid; uint64_t nwid = (uint64_t)in_nwid;
ZT1_ResultCode rc = ZT1_Node_join(node, nwid); ZT_ResultCode rc = ZT_Node_join(node, nwid);
return createResultObject(env, rc); return createResultObject(env, rc);
} }
@ -929,16 +929,16 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_leave(
JNIEnv *env, jobject obj, jlong id, jlong in_nwid) JNIEnv *env, jobject obj, jlong id, jlong in_nwid)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
uint64_t nwid = (uint64_t)in_nwid; uint64_t nwid = (uint64_t)in_nwid;
ZT1_ResultCode rc = ZT1_Node_leave(node, nwid); ZT_ResultCode rc = ZT_Node_leave(node, nwid);
return createResultObject(env, rc); return createResultObject(env, rc);
} }
@ -956,18 +956,18 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_multicastSubscribe(
jlong in_multicastAdi) jlong in_multicastAdi)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
uint64_t nwid = (uint64_t)in_nwid; uint64_t nwid = (uint64_t)in_nwid;
uint64_t multicastGroup = (uint64_t)in_multicastGroup; uint64_t multicastGroup = (uint64_t)in_multicastGroup;
unsigned long multicastAdi = (unsigned long)in_multicastAdi; unsigned long multicastAdi = (unsigned long)in_multicastAdi;
ZT1_ResultCode rc = ZT1_Node_multicastSubscribe( ZT_ResultCode rc = ZT_Node_multicastSubscribe(
node, nwid, multicastGroup, multicastAdi); node, nwid, multicastGroup, multicastAdi);
return createResultObject(env, rc); return createResultObject(env, rc);
@ -986,18 +986,18 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_multicastUnsubscribe(
jlong in_multicastAdi) jlong in_multicastAdi)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return createResultObject(env, ZT1_RESULT_FATAL_ERROR_INTERNAL); return createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL);
} }
uint64_t nwid = (uint64_t)in_nwid; uint64_t nwid = (uint64_t)in_nwid;
uint64_t multicastGroup = (uint64_t)in_multicastGroup; uint64_t multicastGroup = (uint64_t)in_multicastGroup;
unsigned long multicastAdi = (unsigned long)in_multicastAdi; unsigned long multicastAdi = (unsigned long)in_multicastAdi;
ZT1_ResultCode rc = ZT1_Node_multicastUnsubscribe( ZT_ResultCode rc = ZT_Node_multicastUnsubscribe(
node, nwid, multicastGroup, multicastAdi); node, nwid, multicastGroup, multicastAdi);
return createResultObject(env, rc); return createResultObject(env, rc);
@ -1012,14 +1012,14 @@ JNIEXPORT jlong JNICALL Java_com_zerotier_sdk_Node_address(
JNIEnv *env , jobject obj, jlong id) JNIEnv *env , jobject obj, jlong id)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return 0; return 0;
} }
uint64_t address = ZT1_Node_address(node); uint64_t address = ZT_Node_address(node);
return (jlong)address; return (jlong)address;
} }
@ -1032,7 +1032,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_status
(JNIEnv *env, jobject obj, jlong id) (JNIEnv *env, jobject obj, jlong id)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
@ -1062,8 +1062,8 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_status
return NULL; return NULL;
} }
ZT1_NodeStatus nodeStatus; ZT_NodeStatus nodeStatus;
ZT1_Node_status(node, &nodeStatus); ZT_Node_status(node, &nodeStatus);
jfieldID addressField = NULL; jfieldID addressField = NULL;
jfieldID publicIdentityField = NULL; jfieldID publicIdentityField = NULL;
@ -1124,18 +1124,18 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_networkConfig(
JNIEnv *env, jobject obj, jlong id, jlong nwid) JNIEnv *env, jobject obj, jlong id, jlong nwid)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return 0; return 0;
} }
ZT1_VirtualNetworkConfig *vnetConfig = ZT1_Node_networkConfig(node, nwid); ZT_VirtualNetworkConfig *vnetConfig = ZT_Node_networkConfig(node, nwid);
jobject vnetConfigObject = newNetworkConfig(env, *vnetConfig); jobject vnetConfigObject = newNetworkConfig(env, *vnetConfig);
ZT1_Node_freeQueryResult(node, vnetConfig); ZT_Node_freeQueryResult(node, vnetConfig);
return vnetConfigObject; return vnetConfigObject;
} }
@ -1153,7 +1153,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_version(
int revision = 0; int revision = 0;
unsigned long featureFlags = 0; unsigned long featureFlags = 0;
ZT1_version(&major, &minor, &revision, &featureFlags); ZT_version(&major, &minor, &revision, &featureFlags);
return newVersion(env, major, minor, revision, featureFlags); return newVersion(env, major, minor, revision, featureFlags);
} }
@ -1167,18 +1167,18 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_peers(
JNIEnv *env, jobject obj, jlong id) JNIEnv *env, jobject obj, jlong id)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return 0; return 0;
} }
ZT1_PeerList *peerList = ZT1_Node_peers(node); ZT_PeerList *peerList = ZT_Node_peers(node);
if(peerList == NULL) if(peerList == NULL)
{ {
LOGE("ZT1_Node_peers returned NULL"); LOGE("ZT_Node_peers returned NULL");
return NULL; return NULL;
} }
@ -1187,7 +1187,7 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_peers(
if(env->EnsureLocalCapacity(peerCount)) if(env->EnsureLocalCapacity(peerCount))
{ {
LOGE("EnsureLocalCapacity failed!!"); LOGE("EnsureLocalCapacity failed!!");
ZT1_Node_freeQueryResult(node, peerList); ZT_Node_freeQueryResult(node, peerList);
return NULL; return NULL;
} }
@ -1195,7 +1195,7 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_peers(
if(env->ExceptionCheck() || peerClass == NULL) if(env->ExceptionCheck() || peerClass == NULL)
{ {
LOGE("Error finding Peer class"); LOGE("Error finding Peer class");
ZT1_Node_freeQueryResult(node, peerList); ZT_Node_freeQueryResult(node, peerList);
return NULL; return NULL;
} }
@ -1205,7 +1205,7 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_peers(
if(env->ExceptionCheck() || peerArrayObj == NULL) if(env->ExceptionCheck() || peerArrayObj == NULL)
{ {
LOGE("Error creating Peer[] array"); LOGE("Error creating Peer[] array");
ZT1_Node_freeQueryResult(node, peerList); ZT_Node_freeQueryResult(node, peerList);
return NULL; return NULL;
} }
@ -1221,7 +1221,7 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_peers(
} }
} }
ZT1_Node_freeQueryResult(node, peerList); ZT_Node_freeQueryResult(node, peerList);
peerList = NULL; peerList = NULL;
return peerArrayObj; return peerArrayObj;
@ -1236,14 +1236,14 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_networks(
JNIEnv *env, jobject obj, jlong id) JNIEnv *env, jobject obj, jlong id)
{ {
uint64_t nodeId = (uint64_t) id; uint64_t nodeId = (uint64_t) id;
ZT1_Node *node = findNode(nodeId); ZT_Node *node = findNode(nodeId);
if(node == NULL) if(node == NULL)
{ {
// cannot find valid node. We should never get here. // cannot find valid node. We should never get here.
return 0; return 0;
} }
ZT1_VirtualNetworkList *networkList = ZT1_Node_networks(node); ZT_VirtualNetworkList *networkList = ZT_Node_networks(node);
if(networkList == NULL) if(networkList == NULL)
{ {
return NULL; return NULL;
@ -1253,7 +1253,7 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_networks(
if(env->ExceptionCheck() || vnetConfigClass == NULL) if(env->ExceptionCheck() || vnetConfigClass == NULL)
{ {
LOGE("Error finding VirtualNetworkConfig class"); LOGE("Error finding VirtualNetworkConfig class");
ZT1_Node_freeQueryResult(node, networkList); ZT_Node_freeQueryResult(node, networkList);
return NULL; return NULL;
} }
@ -1262,7 +1262,7 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_networks(
if(env->ExceptionCheck() || networkListObject == NULL) if(env->ExceptionCheck() || networkListObject == NULL)
{ {
LOGE("Error creating VirtualNetworkConfig[] array"); LOGE("Error creating VirtualNetworkConfig[] array");
ZT1_Node_freeQueryResult(node, networkList); ZT_Node_freeQueryResult(node, networkList);
return NULL; return NULL;
} }
@ -1277,7 +1277,7 @@ JNIEXPORT jobjectArray JNICALL Java_com_zerotier_sdk_Node_networks(
} }
} }
ZT1_Node_freeQueryResult(node, networkList); ZT_Node_freeQueryResult(node, networkList);
return networkListObject; return networkListObject;
} }

View file

@ -33,7 +33,7 @@ import java.net.InetSocketAddress;
public final class VirtualNetworkConfig { public final class VirtualNetworkConfig {
public static final int MAX_MULTICAST_SUBSCRIPTIONS = 4096; public static final int MAX_MULTICAST_SUBSCRIPTIONS = 4096;
public static final int ZT1_MAX_ZT_ASSIGNED_ADDRESSES = 16; public static final int ZT_MAX_ZT_ASSIGNED_ADDRESSES = 16;
private long nwid; private long nwid;
private long mac; private long mac;

View file

@ -161,7 +161,7 @@
/** /**
* Default MTU used for Ethernet tap device * Default MTU used for Ethernet tap device
*/ */
#define ZT_IF_MTU ZT1_MAX_MTU #define ZT_IF_MTU ZT_MAX_MTU
/** /**
* Maximum number of packet fragments we'll support * Maximum number of packet fragments we'll support

View file

@ -75,7 +75,7 @@ static inline std::map< Address,Identity > _mkRootTopologyAuth()
Defaults::Defaults() : Defaults::Defaults() :
defaultRootTopology((const char *)ZT_DEFAULT_ROOT_TOPOLOGY,ZT_DEFAULT_ROOT_TOPOLOGY_LEN), defaultRootTopology((const char *)ZT_DEFAULT_ROOT_TOPOLOGY,ZT_DEFAULT_ROOT_TOPOLOGY_LEN),
rootTopologyAuthorities(_mkRootTopologyAuth()), rootTopologyAuthorities(_mkRootTopologyAuth()),
v4Broadcast(((uint32_t)0xffffffff),ZT1_DEFAULT_PORT) v4Broadcast(((uint32_t)0xffffffff),ZT_DEFAULT_PORT)
{ {
} }

View file

@ -69,7 +69,7 @@ bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR)
switch(verb()) { switch(verb()) {
//case Packet::VERB_NOP: //case Packet::VERB_NOP:
default: // ignore unknown verbs, but if they pass auth check they are "received" default: // ignore unknown verbs, but if they pass auth check they are "received"
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),verb(),0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),verb(),0,Packet::VERB_NOP);
return true; return true;
case Packet::VERB_HELLO: return _doHELLO(RR); case Packet::VERB_HELLO: return _doHELLO(RR);
case Packet::VERB_ERROR: return _doERROR(RR,peer); case Packet::VERB_ERROR: return _doERROR(RR,peer);
@ -130,7 +130,7 @@ bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,const SharedPtr<Peer>
case Packet::ERROR_IDENTITY_COLLISION: case Packet::ERROR_IDENTITY_COLLISION:
if (RR->topology->isRoot(peer->identity())) if (RR->topology->isRoot(peer->identity()))
RR->node->postEvent(ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION); RR->node->postEvent(ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION);
break; break;
case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: { case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
@ -144,7 +144,7 @@ bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,const SharedPtr<Peer>
Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE); Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
nconf->com().serialize(outp); nconf->com().serialize(outp);
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} }
} }
} break; } break;
@ -165,7 +165,7 @@ bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,const SharedPtr<Peer>
default: break; default: break;
} }
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_ERROR,inRePacketId,inReVerb); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_ERROR,inRePacketId,inReVerb);
} catch (std::exception &ex) { } catch (std::exception &ex) {
TRACE("dropped ERROR from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what()); TRACE("dropped ERROR from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
} catch ( ... ) { } catch ( ... ) {
@ -224,20 +224,20 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR)
unsigned char key[ZT_PEER_SECRET_KEY_LENGTH]; unsigned char key[ZT_PEER_SECRET_KEY_LENGTH];
if (RR->identity.agree(id,key,ZT_PEER_SECRET_KEY_LENGTH)) { if (RR->identity.agree(id,key,ZT_PEER_SECRET_KEY_LENGTH)) {
if (dearmor(key)) { // ensure packet is authentic, otherwise drop if (dearmor(key)) { // ensure packet is authentic, otherwise drop
RR->node->postEvent(ZT1_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress); RR->node->postEvent(ZT_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress);
TRACE("rejected HELLO from %s(%s): address already claimed",id.address().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("rejected HELLO from %s(%s): address already claimed",id.address().toString().c_str(),_remoteAddress.toString().c_str());
Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR); Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
outp.append((unsigned char)Packet::VERB_HELLO); outp.append((unsigned char)Packet::VERB_HELLO);
outp.append(packetId()); outp.append(packetId());
outp.append((unsigned char)Packet::ERROR_IDENTITY_COLLISION); outp.append((unsigned char)Packet::ERROR_IDENTITY_COLLISION);
outp.armor(key,true); outp.armor(key,true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} else { } else {
RR->node->postEvent(ZT1_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress); RR->node->postEvent(ZT_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress);
TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str());
} }
} else { } else {
RR->node->postEvent(ZT1_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress); RR->node->postEvent(ZT_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress);
TRACE("rejected HELLO from %s(%s): key agreement failed",id.address().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("rejected HELLO from %s(%s): key agreement failed",id.address().toString().c_str(),_remoteAddress.toString().c_str());
} }
@ -246,7 +246,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR)
// Identity is the same as the one we already have -- check packet integrity // Identity is the same as the one we already have -- check packet integrity
if (!dearmor(peer->key())) { if (!dearmor(peer->key())) {
RR->node->postEvent(ZT1_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress); RR->node->postEvent(ZT_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress);
TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str());
return true; return true;
} }
@ -258,7 +258,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR)
// Check identity proof of work // Check identity proof of work
if (!id.locallyValidate()) { if (!id.locallyValidate()) {
RR->node->postEvent(ZT1_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress); RR->node->postEvent(ZT_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress);
TRACE("dropped HELLO from %s(%s): identity invalid",id.address().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("dropped HELLO from %s(%s): identity invalid",id.address().toString().c_str(),_remoteAddress.toString().c_str());
return true; return true;
} }
@ -266,7 +266,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR)
// Check packet integrity and authentication // Check packet integrity and authentication
SharedPtr<Peer> newPeer(new Peer(RR->identity,id)); SharedPtr<Peer> newPeer(new Peer(RR->identity,id));
if (!dearmor(newPeer->key())) { if (!dearmor(newPeer->key())) {
RR->node->postEvent(ZT1_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress); RR->node->postEvent(ZT_EVENT_AUTHENTICATION_FAILURE,(const void *)&_remoteAddress);
TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str());
return true; return true;
} }
@ -278,7 +278,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR)
// VALID -- continues here // VALID -- continues here
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_HELLO,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_HELLO,0,Packet::VERB_NOP);
peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision);
bool trusted = false; bool trusted = false;
@ -316,7 +316,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR)
} }
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} catch (std::exception &ex) { } catch (std::exception &ex) {
TRACE("dropped HELLO from %s(%s): %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what()); TRACE("dropped HELLO from %s(%s): %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
} catch ( ... ) { } catch ( ... ) {
@ -436,7 +436,7 @@ bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,const SharedPtr<Peer> &p
default: break; default: break;
} }
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_OK,inRePacketId,inReVerb); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_OK,inRePacketId,inReVerb);
} catch (std::exception &ex) { } catch (std::exception &ex) {
TRACE("dropped OK from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what()); TRACE("dropped OK from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
} catch ( ... ) { } catch ( ... ) {
@ -456,7 +456,7 @@ bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,const SharedPtr<Peer>
outp.append(packetId()); outp.append(packetId());
queried->identity().serialize(outp,false); queried->identity().serialize(outp,false);
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} else { } else {
Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR); Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
outp.append((unsigned char)Packet::VERB_WHOIS); outp.append((unsigned char)Packet::VERB_WHOIS);
@ -464,12 +464,12 @@ bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,const SharedPtr<Peer>
outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND); outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
outp.append(payload(),ZT_ADDRESS_LENGTH); outp.append(payload(),ZT_ADDRESS_LENGTH);
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} }
} else { } else {
TRACE("dropped WHOIS from %s(%s): missing or invalid address",source().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("dropped WHOIS from %s(%s): missing or invalid address",source().toString().c_str(),_remoteAddress.toString().c_str());
} }
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_WHOIS,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_WHOIS,0,Packet::VERB_NOP);
} catch ( ... ) { } catch ( ... ) {
TRACE("dropped WHOIS from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("dropped WHOIS from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
} }
@ -487,8 +487,8 @@ bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,const SharedPtr<
if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) { if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port); InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
TRACE("RENDEZVOUS from %s says %s might be at %s, starting NAT-t",peer->address().toString().c_str(),with.toString().c_str(),atAddr.toString().c_str()); TRACE("RENDEZVOUS from %s says %s might be at %s, starting NAT-t",peer->address().toString().c_str(),with.toString().c_str(),atAddr.toString().c_str());
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP);
RR->sw->rendezvous(withPeer,_localInterfaceId,atAddr); RR->sw->rendezvous(withPeer,_localAddress,atAddr);
} else { } else {
TRACE("dropped corrupt RENDEZVOUS from %s(%s) (bad address or port)",peer->address().toString().c_str(),_remoteAddress.toString().c_str()); TRACE("dropped corrupt RENDEZVOUS from %s(%s) (bad address or port)",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
} }
@ -525,7 +525,7 @@ bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,const SharedPtr<Peer>
RR->node->putFrame(network->id(),MAC(peer->address(),network->id()),network->mac(),etherType,0,field(ZT_PROTO_VERB_FRAME_IDX_PAYLOAD,payloadLen),payloadLen); RR->node->putFrame(network->id(),MAC(peer->address(),network->id()),network->mac(),etherType,0,field(ZT_PROTO_VERB_FRAME_IDX_PAYLOAD,payloadLen),payloadLen);
} }
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_FRAME,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_FRAME,0,Packet::VERB_NOP);
} else { } else {
TRACE("dropped FRAME from %s(%s): we are not connected to network %.16llx",source().toString().c_str(),_remoteAddress.toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID)); TRACE("dropped FRAME from %s(%s): we are not connected to network %.16llx",source().toString().c_str(),_remoteAddress.toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID));
} }
@ -602,7 +602,7 @@ bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,const SharedPtr<P
RR->node->putFrame(network->id(),from,to,etherType,0,field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,payloadLen),payloadLen); RR->node->putFrame(network->id(),from,to,etherType,0,field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,payloadLen),payloadLen);
} }
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP);
} else { } else {
TRACE("dropped EXT_FRAME from %s(%s): we are not connected to network %.16llx",source().toString().c_str(),_remoteAddress.toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID)); TRACE("dropped EXT_FRAME from %s(%s): we are not connected to network %.16llx",source().toString().c_str(),_remoteAddress.toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID));
} }
@ -623,7 +623,7 @@ bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,const Shared
for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18)
RR->mc->add(now,at<uint64_t>(ptr),MulticastGroup(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14)),peer->address()); RR->mc->add(now,at<uint64_t>(ptr),MulticastGroup(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14)),peer->address());
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP);
} catch (std::exception &ex) { } catch (std::exception &ex) {
TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what()); TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
} catch ( ... ) { } catch ( ... ) {
@ -647,7 +647,7 @@ bool IncomingPacket::_doNETWORK_MEMBERSHIP_CERTIFICATE(const RuntimeEnvironment
} }
} }
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE,0,Packet::VERB_NOP);
} catch (std::exception &ex) { } catch (std::exception &ex) {
TRACE("dropped NETWORK_MEMBERSHIP_CERTIFICATE from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what()); TRACE("dropped NETWORK_MEMBERSHIP_CERTIFICATE from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
} catch ( ... ) { } catch ( ... ) {
@ -666,7 +666,7 @@ bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,cons
const unsigned int h = hops(); const unsigned int h = hops();
const uint64_t pid = packetId(); const uint64_t pid = packetId();
peer->received(RR,_localInterfaceId,_remoteAddress,h,pid,Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,h,pid,Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP);
if (RR->localNetworkController) { if (RR->localNetworkController) {
Dictionary netconf; Dictionary netconf;
@ -688,7 +688,7 @@ bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,cons
if (outp.size() > ZT_PROTO_MAX_PACKET_LENGTH) { if (outp.size() > ZT_PROTO_MAX_PACKET_LENGTH) {
TRACE("NETWORK_CONFIG_REQUEST failed: internal error: netconf size %u is too large",(unsigned int)netconfStr.length()); TRACE("NETWORK_CONFIG_REQUEST failed: internal error: netconf size %u is too large",(unsigned int)netconfStr.length());
} else { } else {
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} }
} }
} break; } break;
@ -700,7 +700,7 @@ bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,cons
outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND); outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
outp.append(nwid); outp.append(nwid);
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} break; } break;
case NetworkController::NETCONF_QUERY_ACCESS_DENIED: { case NetworkController::NETCONF_QUERY_ACCESS_DENIED: {
@ -710,7 +710,7 @@ bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,cons
outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_); outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
outp.append(nwid); outp.append(nwid);
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} break; } break;
case NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR: case NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR:
@ -732,7 +732,7 @@ bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,cons
outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION); outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
outp.append(nwid); outp.append(nwid);
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} }
} catch (std::exception &exc) { } catch (std::exception &exc) {
TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what()); TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
@ -753,7 +753,7 @@ bool IncomingPacket::_doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *RR,cons
nw->requestConfiguration(); nw->requestConfiguration();
ptr += 8; ptr += 8;
} }
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_NETWORK_CONFIG_REFRESH,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_NETWORK_CONFIG_REFRESH,0,Packet::VERB_NOP);
} catch (std::exception &exc) { } catch (std::exception &exc) {
TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what()); TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
} catch ( ... ) { } catch ( ... ) {
@ -780,11 +780,11 @@ bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,const Shar
outp.append((uint32_t)mg.adi()); outp.append((uint32_t)mg.adi());
if (RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit)) { if (RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit)) {
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} }
} }
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP);
} catch (std::exception &exc) { } catch (std::exception &exc) {
TRACE("dropped MULTICAST_GATHER from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what()); TRACE("dropped MULTICAST_GATHER from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
} catch ( ... ) { } catch ( ... ) {
@ -871,12 +871,12 @@ bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,const Share
outp.append((unsigned char)0x02); // flag 0x02 = contains gather results outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) { if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} }
} }
} // else ignore -- not a member of this network } // else ignore -- not a member of this network
peer->received(RR,_localInterfaceId,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP); peer->received(RR,_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP);
} catch (std::exception &exc) { } catch (std::exception &exc) {
TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what()); TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
} catch ( ... ) { } catch ( ... ) {
@ -905,14 +905,14 @@ bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const Sha
InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4)); InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
if ( ((flags & (0x01 | 0x02)) == 0) && (Path::isAddressValidForPath(a)) ) { if ( ((flags & (0x01 | 0x02)) == 0) && (Path::isAddressValidForPath(a)) ) {
TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str()); TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
peer->attemptToContactAt(RR,_localInterfaceId,a,RR->node->now()); peer->attemptToContactAt(RR,_localAddress,a,RR->node->now());
} }
} break; } break;
case 6: { case 6: {
InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16)); InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
if ( ((flags & (0x01 | 0x02)) == 0) && (Path::isAddressValidForPath(a)) ) { if ( ((flags & (0x01 | 0x02)) == 0) && (Path::isAddressValidForPath(a)) ) {
TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str()); TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
peer->attemptToContactAt(RR,_localInterfaceId,a,RR->node->now()); peer->attemptToContactAt(RR,_localAddress,a,RR->node->now());
} }
} break; } break;
} }
@ -934,7 +934,7 @@ void IncomingPacket::_sendErrorNeedCertificate(const RuntimeEnvironment *RR,cons
outp.append((unsigned char)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE); outp.append((unsigned char)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
outp.append(nwid); outp.append(nwid);
outp.armor(peer->key(),true); outp.armor(peer->key(),true);
RR->node->putPacket(_localInterfaceId,_remoteAddress,outp.data(),outp.size()); RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
} }
} // namespace ZeroTier } // namespace ZeroTier

View file

@ -72,16 +72,16 @@ public:
* *
* @param data Packet data * @param data Packet data
* @param len Packet length * @param len Packet length
* @param localInterfaceId Local interface ID * @param localAddress Local interface address
* @param remoteAddress Address from which packet came * @param remoteAddress Address from which packet came
* @param now Current time * @param now Current time
* @throws std::out_of_range Range error processing packet * @throws std::out_of_range Range error processing packet
*/ */
IncomingPacket(const void *data,unsigned int len,int localInterfaceId,const InetAddress &remoteAddress,uint64_t now) : IncomingPacket(const void *data,unsigned int len,const InetAddress &localAddress,const InetAddress &remoteAddress,uint64_t now) :
Packet(data,len), Packet(data,len),
_receiveTime(now), _receiveTime(now),
_localAddress(localAddress),
_remoteAddress(remoteAddress), _remoteAddress(remoteAddress),
_localInterfaceId(localInterfaceId),
__refCount() __refCount()
{ {
} }
@ -129,8 +129,8 @@ private:
void _sendErrorNeedCertificate(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer,uint64_t nwid); void _sendErrorNeedCertificate(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer,uint64_t nwid);
uint64_t _receiveTime; uint64_t _receiveTime;
InetAddress _localAddress;
InetAddress _remoteAddress; InetAddress _remoteAddress;
int _localInterfaceId;
AtomicCounter __refCount; AtomicCounter __refCount;
}; };

View file

@ -100,28 +100,28 @@ Network::Network(const RuntimeEnvironment *renv,uint64_t nwid) :
} }
if (!_portInitialized) { if (!_portInitialized) {
ZT1_VirtualNetworkConfig ctmp; ZT_VirtualNetworkConfig ctmp;
_externalConfig(&ctmp); _externalConfig(&ctmp);
_portError = RR->node->configureVirtualNetworkPort(_id,ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp); _portError = RR->node->configureVirtualNetworkPort(_id,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
_portInitialized = true; _portInitialized = true;
} }
} }
Network::~Network() Network::~Network()
{ {
ZT1_VirtualNetworkConfig ctmp; ZT_VirtualNetworkConfig ctmp;
_externalConfig(&ctmp); _externalConfig(&ctmp);
char n[128]; char n[128];
if (_destroyed) { if (_destroyed) {
RR->node->configureVirtualNetworkPort(_id,ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp); RR->node->configureVirtualNetworkPort(_id,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id); Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
RR->node->dataStoreDelete(n); RR->node->dataStoreDelete(n);
Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.mcerts",_id); Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.mcerts",_id);
RR->node->dataStoreDelete(n); RR->node->dataStoreDelete(n);
} else { } else {
RR->node->configureVirtualNetworkPort(_id,ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp); RR->node->configureVirtualNetworkPort(_id,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
clean(); clean();
@ -184,7 +184,7 @@ bool Network::applyConfiguration(const SharedPtr<NetworkConfig> &conf)
return false; return false;
try { try {
if ((conf->networkId() == _id)&&(conf->issuedTo() == RR->identity.address())) { if ((conf->networkId() == _id)&&(conf->issuedTo() == RR->identity.address())) {
ZT1_VirtualNetworkConfig ctmp; ZT_VirtualNetworkConfig ctmp;
bool portInitialized; bool portInitialized;
{ {
Mutex::Lock _l(_lock); Mutex::Lock _l(_lock);
@ -195,7 +195,7 @@ bool Network::applyConfiguration(const SharedPtr<NetworkConfig> &conf)
portInitialized = _portInitialized; portInitialized = _portInitialized;
_portInitialized = true; _portInitialized = true;
} }
_portError = RR->node->configureVirtualNetworkPort(_id,(portInitialized) ? ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp); _portError = RR->node->configureVirtualNetworkPort(_id,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
return true; return true;
} else { } else {
TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id); TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
@ -431,9 +431,9 @@ void Network::setEnabled(bool enabled)
Mutex::Lock _l(_lock); Mutex::Lock _l(_lock);
if (_enabled != enabled) { if (_enabled != enabled) {
_enabled = enabled; _enabled = enabled;
ZT1_VirtualNetworkConfig ctmp; ZT_VirtualNetworkConfig ctmp;
_externalConfig(&ctmp); _externalConfig(&ctmp);
_portError = RR->node->configureVirtualNetworkPort(_id,ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE,&ctmp); _portError = RR->node->configureVirtualNetworkPort(_id,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE,&ctmp);
} }
} }
@ -444,24 +444,24 @@ void Network::destroy()
_destroyed = true; _destroyed = true;
} }
ZT1_VirtualNetworkStatus Network::_status() const ZT_VirtualNetworkStatus Network::_status() const
{ {
// assumes _lock is locked // assumes _lock is locked
if (_portError) if (_portError)
return ZT1_NETWORK_STATUS_PORT_ERROR; return ZT_NETWORK_STATUS_PORT_ERROR;
switch(_netconfFailure) { switch(_netconfFailure) {
case NETCONF_FAILURE_ACCESS_DENIED: case NETCONF_FAILURE_ACCESS_DENIED:
return ZT1_NETWORK_STATUS_ACCESS_DENIED; return ZT_NETWORK_STATUS_ACCESS_DENIED;
case NETCONF_FAILURE_NOT_FOUND: case NETCONF_FAILURE_NOT_FOUND:
return ZT1_NETWORK_STATUS_NOT_FOUND; return ZT_NETWORK_STATUS_NOT_FOUND;
case NETCONF_FAILURE_NONE: case NETCONF_FAILURE_NONE:
return ((_config) ? ZT1_NETWORK_STATUS_OK : ZT1_NETWORK_STATUS_REQUESTING_CONFIGURATION); return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
default: default:
return ZT1_NETWORK_STATUS_PORT_ERROR; return ZT_NETWORK_STATUS_PORT_ERROR;
} }
} }
void Network::_externalConfig(ZT1_VirtualNetworkConfig *ec) const void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
{ {
// assumes _lock is locked // assumes _lock is locked
ec->nwid = _id; ec->nwid = _id;
@ -470,7 +470,7 @@ void Network::_externalConfig(ZT1_VirtualNetworkConfig *ec) const
Utils::scopy(ec->name,sizeof(ec->name),_config->name().c_str()); Utils::scopy(ec->name,sizeof(ec->name),_config->name().c_str());
else ec->name[0] = (char)0; else ec->name[0] = (char)0;
ec->status = _status(); ec->status = _status();
ec->type = (_config) ? (_config->isPrivate() ? ZT1_NETWORK_TYPE_PRIVATE : ZT1_NETWORK_TYPE_PUBLIC) : ZT1_NETWORK_TYPE_PRIVATE; ec->type = (_config) ? (_config->isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
ec->mtu = ZT_IF_MTU; ec->mtu = ZT_IF_MTU;
ec->dhcp = 0; ec->dhcp = 0;
ec->bridge = (_config) ? ((_config->allowPassiveBridging() || (std::find(_config->activeBridges().begin(),_config->activeBridges().end(),RR->identity.address()) != _config->activeBridges().end())) ? 1 : 0) : 0; ec->bridge = (_config) ? ((_config->allowPassiveBridging() || (std::find(_config->activeBridges().begin(),_config->activeBridges().end(),RR->identity.address()) != _config->activeBridges().end())) ? 1 : 0) : 0;
@ -479,7 +479,7 @@ void Network::_externalConfig(ZT1_VirtualNetworkConfig *ec) const
ec->enabled = (_enabled) ? 1 : 0; ec->enabled = (_enabled) ? 1 : 0;
ec->netconfRevision = (_config) ? (unsigned long)_config->revision() : 0; ec->netconfRevision = (_config) ? (unsigned long)_config->revision() : 0;
ec->multicastSubscriptionCount = std::min((unsigned int)_myMulticastGroups.size(),(unsigned int)ZT1_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS); ec->multicastSubscriptionCount = std::min((unsigned int)_myMulticastGroups.size(),(unsigned int)ZT_MAX_NETWORK_MULTICAST_SUBSCRIPTIONS);
for(unsigned int i=0;i<ec->multicastSubscriptionCount;++i) { for(unsigned int i=0;i<ec->multicastSubscriptionCount;++i) {
ec->multicastSubscriptions[i].mac = _myMulticastGroups[i].mac().toInt(); ec->multicastSubscriptions[i].mac = _myMulticastGroups[i].mac().toInt();
ec->multicastSubscriptions[i].adi = _myMulticastGroups[i].adi(); ec->multicastSubscriptions[i].adi = _myMulticastGroups[i].adi();
@ -487,7 +487,7 @@ void Network::_externalConfig(ZT1_VirtualNetworkConfig *ec) const
if (_config) { if (_config) {
ec->assignedAddressCount = (unsigned int)_config->staticIps().size(); ec->assignedAddressCount = (unsigned int)_config->staticIps().size();
for(unsigned long i=0;i<ZT1_MAX_ZT_ASSIGNED_ADDRESSES;++i) { for(unsigned long i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
if (i < _config->staticIps().size()) if (i < _config->staticIps().size())
memcpy(&(ec->assignedAddresses[i]),&(_config->staticIps()[i]),sizeof(struct sockaddr_storage)); memcpy(&(ec->assignedAddresses[i]),&(_config->staticIps()[i]),sizeof(struct sockaddr_storage));
} }

View file

@ -222,7 +222,7 @@ public:
/** /**
* @return Status of this network * @return Status of this network
*/ */
inline ZT1_VirtualNetworkStatus status() const inline ZT_VirtualNetworkStatus status() const
{ {
Mutex::Lock _l(_lock); Mutex::Lock _l(_lock);
return _status(); return _status();
@ -231,7 +231,7 @@ public:
/** /**
* @param ec Buffer to fill with externally-visible network configuration * @param ec Buffer to fill with externally-visible network configuration
*/ */
inline void externalConfig(ZT1_VirtualNetworkConfig *ec) const inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
{ {
Mutex::Lock _l(_lock); Mutex::Lock _l(_lock);
_externalConfig(ec); _externalConfig(ec);
@ -354,8 +354,8 @@ private:
uint64_t lastPushed; // when did we last push ours to them? uint64_t lastPushed; // when did we last push ours to them?
}; };
ZT1_VirtualNetworkStatus _status() const; ZT_VirtualNetworkStatus _status() const;
void _externalConfig(ZT1_VirtualNetworkConfig *ec) const; // assumes _lock is locked void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
bool _isAllowed(const Address &peer) const; bool _isAllowed(const Address &peer) const;
void _announceMulticastGroups(); void _announceMulticastGroups();
std::vector<MulticastGroup> _allMulticastGroups() const; std::vector<MulticastGroup> _allMulticastGroups() const;

View file

@ -108,7 +108,7 @@ void NetworkConfig::_fromDictionary(const Dictionary &d)
_private = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE,one).c_str()) != 0); _private = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE,one).c_str()) != 0);
_enableBroadcast = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST,one).c_str()) != 0); _enableBroadcast = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST,one).c_str()) != 0);
_name = d.get(ZT_NETWORKCONFIG_DICT_KEY_NAME); _name = d.get(ZT_NETWORKCONFIG_DICT_KEY_NAME);
if (_name.length() > ZT1_MAX_NETWORK_SHORT_NAME_LENGTH) if (_name.length() > ZT_MAX_NETWORK_SHORT_NAME_LENGTH)
throw std::invalid_argument("network short name too long (max: 255 characters)"); throw std::invalid_argument("network short name too long (max: 255 characters)");
// In dictionary IPs are split into V4 and V6 addresses, but we don't really // In dictionary IPs are split into V4 and V6 addresses, but we don't really
@ -142,8 +142,8 @@ void NetworkConfig::_fromDictionary(const Dictionary &d)
_localRoutes.push_back(addr); _localRoutes.push_back(addr);
else _staticIps.push_back(addr); else _staticIps.push_back(addr);
} }
if (_localRoutes.size() > ZT1_MAX_ZT_ASSIGNED_ADDRESSES) throw std::invalid_argument("too many ZT-assigned routes"); if (_localRoutes.size() > ZT_MAX_ZT_ASSIGNED_ADDRESSES) throw std::invalid_argument("too many ZT-assigned routes");
if (_staticIps.size() > ZT1_MAX_ZT_ASSIGNED_ADDRESSES) throw std::invalid_argument("too many ZT-assigned IP addresses"); if (_staticIps.size() > ZT_MAX_ZT_ASSIGNED_ADDRESSES) throw std::invalid_argument("too many ZT-assigned IP addresses");
std::sort(_localRoutes.begin(),_localRoutes.end()); std::sort(_localRoutes.begin(),_localRoutes.end());
_localRoutes.erase(std::unique(_localRoutes.begin(),_localRoutes.end()),_localRoutes.end()); _localRoutes.erase(std::unique(_localRoutes.begin(),_localRoutes.end()),_localRoutes.end());
std::sort(_staticIps.begin(),_staticIps.end()); std::sort(_staticIps.begin(),_staticIps.end());

View file

@ -48,6 +48,8 @@
#include "SelfAwareness.hpp" #include "SelfAwareness.hpp"
#include "Defaults.hpp" #include "Defaults.hpp"
const struct sockaddr_storage ZT_SOCKADDR_NULL = {0};
namespace ZeroTier { namespace ZeroTier {
/****************************************************************************/ /****************************************************************************/
@ -57,12 +59,12 @@ namespace ZeroTier {
Node::Node( Node::Node(
uint64_t now, uint64_t now,
void *uptr, void *uptr,
ZT1_DataStoreGetFunction dataStoreGetFunction, ZT_DataStoreGetFunction dataStoreGetFunction,
ZT1_DataStorePutFunction dataStorePutFunction, ZT_DataStorePutFunction dataStorePutFunction,
ZT1_WirePacketSendFunction wirePacketSendFunction, ZT_WirePacketSendFunction wirePacketSendFunction,
ZT1_VirtualNetworkFrameFunction virtualNetworkFrameFunction, ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
ZT1_VirtualNetworkConfigFunction virtualNetworkConfigFunction, ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
ZT1_EventCallback eventCallback, ZT_EventCallback eventCallback,
const char *overrideRootTopology) : const char *overrideRootTopology) :
_RR(this), _RR(this),
RR(&_RR), RR(&_RR),
@ -141,7 +143,7 @@ Node::Node(
} }
RR->topology->setRootServers(Dictionary(rt.get("rootservers",""))); RR->topology->setRootServers(Dictionary(rt.get("rootservers","")));
postEvent(ZT1_EVENT_UP); postEvent(ZT_EVENT_UP);
} }
Node::~Node() Node::~Node()
@ -155,20 +157,20 @@ Node::~Node()
delete RR->sw; delete RR->sw;
} }
ZT1_ResultCode Node::processWirePacket( ZT_ResultCode Node::processWirePacket(
uint64_t now, uint64_t now,
int localInterfaceId, const struct sockaddr_storage *localAddress,
const struct sockaddr_storage *remoteAddress, const struct sockaddr_storage *remoteAddress,
const void *packetData, const void *packetData,
unsigned int packetLength, unsigned int packetLength,
volatile uint64_t *nextBackgroundTaskDeadline) volatile uint64_t *nextBackgroundTaskDeadline)
{ {
_now = now; _now = now;
RR->sw->onRemotePacket(localInterfaceId,*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength); RR->sw->onRemotePacket(*(reinterpret_cast<const InetAddress *>(localAddress)),*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} }
ZT1_ResultCode Node::processVirtualNetworkFrame( ZT_ResultCode Node::processVirtualNetworkFrame(
uint64_t now, uint64_t now,
uint64_t nwid, uint64_t nwid,
uint64_t sourceMac, uint64_t sourceMac,
@ -183,8 +185,8 @@ ZT1_ResultCode Node::processVirtualNetworkFrame(
SharedPtr<Network> nw(this->network(nwid)); SharedPtr<Network> nw(this->network(nwid));
if (nw) { if (nw) {
RR->sw->onLocalEthernet(nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength); RR->sw->onLocalEthernet(nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} else return ZT1_RESULT_ERROR_NETWORK_NOT_FOUND; } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
} }
class _PingPeersThatNeedPing class _PingPeersThatNeedPing
@ -228,7 +230,7 @@ private:
std::vector<Address> _rootAddresses; std::vector<Address> _rootAddresses;
}; };
ZT1_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline) ZT_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
{ {
_now = now; _now = now;
Mutex::Lock bl(_backgroundTasksLock); Mutex::Lock bl(_backgroundTasksLock);
@ -264,7 +266,7 @@ ZT1_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *next
if (nr->second) { if (nr->second) {
SharedPtr<Peer> rp(RR->topology->getPeer(nr->first)); SharedPtr<Peer> rp(RR->topology->getPeer(nr->first));
if ((rp)&&(!rp->hasActiveDirectPath(now))) if ((rp)&&(!rp->hasActiveDirectPath(now)))
rp->attemptToContactAt(RR,-1,nr->second,now); rp->attemptToContactAt(RR,InetAddress(),nr->second,now);
} }
} }
@ -276,9 +278,9 @@ ZT1_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *next
bool oldOnline = _online; bool oldOnline = _online;
_online = ((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT); _online = ((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT);
if (oldOnline != _online) if (oldOnline != _online)
postEvent(_online ? ZT1_EVENT_ONLINE : ZT1_EVENT_OFFLINE); postEvent(_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} else { } else {
timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck; timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
@ -291,30 +293,30 @@ ZT1_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *next
RR->sa->clean(now); RR->sa->clean(now);
RR->mc->clean(now); RR->mc->clean(now);
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} }
try { try {
*nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY); *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} }
ZT1_ResultCode Node::join(uint64_t nwid) ZT_ResultCode Node::join(uint64_t nwid)
{ {
Mutex::Lock _l(_networks_m); Mutex::Lock _l(_networks_m);
SharedPtr<Network> nw = _network(nwid); SharedPtr<Network> nw = _network(nwid);
if(!nw) if(!nw)
_networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid)))); _networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid))));
std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<> std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<>
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} }
ZT1_ResultCode Node::leave(uint64_t nwid) ZT_ResultCode Node::leave(uint64_t nwid)
{ {
std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn; std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
Mutex::Lock _l(_networks_m); Mutex::Lock _l(_networks_m);
@ -324,25 +326,25 @@ ZT1_ResultCode Node::leave(uint64_t nwid)
else n->second->destroy(); else n->second->destroy();
} }
_networks.swap(newn); _networks.swap(newn);
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} }
ZT1_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi) ZT_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
{ {
SharedPtr<Network> nw(this->network(nwid)); SharedPtr<Network> nw(this->network(nwid));
if (nw) { if (nw) {
nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff))); nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} else return ZT1_RESULT_ERROR_NETWORK_NOT_FOUND; } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
} }
ZT1_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi) ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
{ {
SharedPtr<Network> nw(this->network(nwid)); SharedPtr<Network> nw(this->network(nwid));
if (nw) { if (nw) {
nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff))); nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} else return ZT1_RESULT_ERROR_NETWORK_NOT_FOUND; } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
} }
uint64_t Node::address() const uint64_t Node::address() const
@ -350,7 +352,7 @@ uint64_t Node::address() const
return RR->identity.address().toInt(); return RR->identity.address().toInt();
} }
void Node::status(ZT1_NodeStatus *status) const void Node::status(ZT_NodeStatus *status) const
{ {
status->address = RR->identity.address().toInt(); status->address = RR->identity.address().toInt();
status->publicIdentity = RR->publicIdentityStr.c_str(); status->publicIdentity = RR->publicIdentityStr.c_str();
@ -358,20 +360,20 @@ void Node::status(ZT1_NodeStatus *status) const
status->online = _online ? 1 : 0; status->online = _online ? 1 : 0;
} }
ZT1_PeerList *Node::peers() const ZT_PeerList *Node::peers() const
{ {
std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers()); std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
std::sort(peers.begin(),peers.end()); std::sort(peers.begin(),peers.end());
char *buf = (char *)::malloc(sizeof(ZT1_PeerList) + (sizeof(ZT1_Peer) * peers.size())); char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
if (!buf) if (!buf)
return (ZT1_PeerList *)0; return (ZT_PeerList *)0;
ZT1_PeerList *pl = (ZT1_PeerList *)buf; ZT_PeerList *pl = (ZT_PeerList *)buf;
pl->peers = (ZT1_Peer *)(buf + sizeof(ZT1_PeerList)); pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
pl->peerCount = 0; pl->peerCount = 0;
for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) { for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
ZT1_Peer *p = &(pl->peers[pl->peerCount++]); ZT_Peer *p = &(pl->peers[pl->peerCount++]);
p->address = pi->second->address().toInt(); p->address = pi->second->address().toInt();
p->lastUnicastFrame = pi->second->lastUnicastFrame(); p->lastUnicastFrame = pi->second->lastUnicastFrame();
p->lastMulticastFrame = pi->second->lastMulticastFrame(); p->lastMulticastFrame = pi->second->lastMulticastFrame();
@ -385,7 +387,7 @@ ZT1_PeerList *Node::peers() const
p->versionRev = -1; p->versionRev = -1;
} }
p->latency = pi->second->latency(); p->latency = pi->second->latency();
p->role = RR->topology->isRoot(pi->second->identity()) ? ZT1_PEER_ROLE_ROOT : ZT1_PEER_ROLE_LEAF; p->role = RR->topology->isRoot(pi->second->identity()) ? ZT_PEER_ROLE_ROOT : ZT_PEER_ROLE_LEAF;
std::vector<RemotePath> paths(pi->second->paths()); std::vector<RemotePath> paths(pi->second->paths());
RemotePath *bestPath = pi->second->getBestPath(_now); RemotePath *bestPath = pi->second->getBestPath(_now);
@ -404,27 +406,27 @@ ZT1_PeerList *Node::peers() const
return pl; return pl;
} }
ZT1_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
{ {
Mutex::Lock _l(_networks_m); Mutex::Lock _l(_networks_m);
SharedPtr<Network> nw = _network(nwid); SharedPtr<Network> nw = _network(nwid);
if(nw) { if(nw) {
ZT1_VirtualNetworkConfig *nc = (ZT1_VirtualNetworkConfig *)::malloc(sizeof(ZT1_VirtualNetworkConfig)); ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
nw->externalConfig(nc); nw->externalConfig(nc);
return nc; return nc;
} }
return (ZT1_VirtualNetworkConfig *)0; return (ZT_VirtualNetworkConfig *)0;
} }
ZT1_VirtualNetworkList *Node::networks() const ZT_VirtualNetworkList *Node::networks() const
{ {
Mutex::Lock _l(_networks_m); Mutex::Lock _l(_networks_m);
char *buf = (char *)::malloc(sizeof(ZT1_VirtualNetworkList) + (sizeof(ZT1_VirtualNetworkConfig) * _networks.size())); char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
if (!buf) if (!buf)
return (ZT1_VirtualNetworkList *)0; return (ZT_VirtualNetworkList *)0;
ZT1_VirtualNetworkList *nl = (ZT1_VirtualNetworkList *)buf; ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
nl->networks = (ZT1_VirtualNetworkConfig *)(buf + sizeof(ZT1_VirtualNetworkList)); nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
nl->networkCount = 0; nl->networkCount = 0;
for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
@ -439,7 +441,7 @@ void Node::freeQueryResult(void *qr)
::free(qr); ::free(qr);
} }
int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr,int metric,ZT1_LocalInterfaceAddressTrust trust) int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr,int metric,ZT_LocalInterfaceAddressTrust trust)
{ {
if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) { if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
Mutex::Lock _l(_directPaths_m); Mutex::Lock _l(_directPaths_m);
@ -472,7 +474,7 @@ std::string Node::dataStoreGet(const char *name)
std::string r; std::string r;
unsigned long olen = 0; unsigned long olen = 0;
do { do {
long n = _dataStoreGetFunction(reinterpret_cast<ZT1_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen); long n = _dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
if (n <= 0) if (n <= 0)
return std::string(); return std::string();
r.append(buf,n); r.append(buf,n);
@ -486,7 +488,7 @@ void Node::postNewerVersionIfNewer(unsigned int major,unsigned int minor,unsigne
_newestVersionSeen[0] = major; _newestVersionSeen[0] = major;
_newestVersionSeen[1] = minor; _newestVersionSeen[1] = minor;
_newestVersionSeen[2] = rev; _newestVersionSeen[2] = rev;
this->postEvent(ZT1_EVENT_SAW_MORE_RECENT_VERSION,(const void *)_newestVersionSeen); this->postEvent(ZT_EVENT_SAW_MORE_RECENT_VERSION,(const void *)_newestVersionSeen);
} }
} }
@ -519,7 +521,7 @@ void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
tmp2[sizeof(tmp2)-1] = (char)0; tmp2[sizeof(tmp2)-1] = (char)0;
Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2); Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
postEvent(ZT1_EVENT_TRACE,tmp1); postEvent(ZT_EVENT_TRACE,tmp1);
} }
#endif // ZT_TRACE #endif // ZT_TRACE
@ -539,59 +541,59 @@ uint64_t Node::prng()
extern "C" { extern "C" {
enum ZT1_ResultCode ZT1_Node_new( enum ZT_ResultCode ZT_Node_new(
ZT1_Node **node, ZT_Node **node,
void *uptr, void *uptr,
uint64_t now, uint64_t now,
ZT1_DataStoreGetFunction dataStoreGetFunction, ZT_DataStoreGetFunction dataStoreGetFunction,
ZT1_DataStorePutFunction dataStorePutFunction, ZT_DataStorePutFunction dataStorePutFunction,
ZT1_WirePacketSendFunction wirePacketSendFunction, ZT_WirePacketSendFunction wirePacketSendFunction,
ZT1_VirtualNetworkFrameFunction virtualNetworkFrameFunction, ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
ZT1_VirtualNetworkConfigFunction virtualNetworkConfigFunction, ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
ZT1_EventCallback eventCallback, ZT_EventCallback eventCallback,
const char *overrideRootTopology) const char *overrideRootTopology)
{ {
*node = (ZT1_Node *)0; *node = (ZT_Node *)0;
try { try {
*node = reinterpret_cast<ZT1_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,eventCallback,overrideRootTopology)); *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,eventCallback,overrideRootTopology));
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
} catch (std::runtime_error &exc) { } catch (std::runtime_error &exc) {
return ZT1_RESULT_FATAL_ERROR_DATA_STORE_FAILED; return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} }
void ZT1_Node_delete(ZT1_Node *node) void ZT_Node_delete(ZT_Node *node)
{ {
try { try {
delete (reinterpret_cast<ZeroTier::Node *>(node)); delete (reinterpret_cast<ZeroTier::Node *>(node));
} catch ( ... ) {} } catch ( ... ) {}
} }
enum ZT1_ResultCode ZT1_Node_processWirePacket( enum ZT_ResultCode ZT_Node_processWirePacket(
ZT1_Node *node, ZT_Node *node,
uint64_t now, uint64_t now,
int localInterfaceId, const struct sockaddr_storage *localAddress,
const struct sockaddr_storage *remoteAddress, const struct sockaddr_storage *remoteAddress,
const void *packetData, const void *packetData,
unsigned int packetLength, unsigned int packetLength,
volatile uint64_t *nextBackgroundTaskDeadline) volatile uint64_t *nextBackgroundTaskDeadline)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localInterfaceId,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline); return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
} catch ( ... ) { } catch ( ... ) {
reinterpret_cast<ZeroTier::Node *>(node)->postEvent(ZT1_EVENT_INVALID_PACKET,(const void *)remoteAddress); reinterpret_cast<ZeroTier::Node *>(node)->postEvent(ZT_EVENT_INVALID_PACKET,(const void *)remoteAddress);
return ZT1_RESULT_OK; return ZT_RESULT_OK;
} }
} }
enum ZT1_ResultCode ZT1_Node_processVirtualNetworkFrame( enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
ZT1_Node *node, ZT_Node *node,
uint64_t now, uint64_t now,
uint64_t nwid, uint64_t nwid,
uint64_t sourceMac, uint64_t sourceMac,
@ -605,121 +607,121 @@ enum ZT1_ResultCode ZT1_Node_processVirtualNetworkFrame(
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline); return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} }
enum ZT1_ResultCode ZT1_Node_processBackgroundTasks(ZT1_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline) enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline); return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} }
enum ZT1_ResultCode ZT1_Node_join(ZT1_Node *node,uint64_t nwid) enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid); return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} }
enum ZT1_ResultCode ZT1_Node_leave(ZT1_Node *node,uint64_t nwid) enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid); return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} }
enum ZT1_ResultCode ZT1_Node_multicastSubscribe(ZT1_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi) enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi); return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} }
enum ZT1_ResultCode ZT1_Node_multicastUnsubscribe(ZT1_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi) enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi); return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
} catch (std::bad_alloc &exc) { } catch (std::bad_alloc &exc) {
return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY; return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
} catch ( ... ) { } catch ( ... ) {
return ZT1_RESULT_FATAL_ERROR_INTERNAL; return ZT_RESULT_FATAL_ERROR_INTERNAL;
} }
} }
uint64_t ZT1_Node_address(ZT1_Node *node) uint64_t ZT_Node_address(ZT_Node *node)
{ {
return reinterpret_cast<ZeroTier::Node *>(node)->address(); return reinterpret_cast<ZeroTier::Node *>(node)->address();
} }
void ZT1_Node_status(ZT1_Node *node,ZT1_NodeStatus *status) void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
{ {
try { try {
reinterpret_cast<ZeroTier::Node *>(node)->status(status); reinterpret_cast<ZeroTier::Node *>(node)->status(status);
} catch ( ... ) {} } catch ( ... ) {}
} }
ZT1_PeerList *ZT1_Node_peers(ZT1_Node *node) ZT_PeerList *ZT_Node_peers(ZT_Node *node)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->peers(); return reinterpret_cast<ZeroTier::Node *>(node)->peers();
} catch ( ... ) { } catch ( ... ) {
return (ZT1_PeerList *)0; return (ZT_PeerList *)0;
} }
} }
ZT1_VirtualNetworkConfig *ZT1_Node_networkConfig(ZT1_Node *node,uint64_t nwid) ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid); return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
} catch ( ... ) { } catch ( ... ) {
return (ZT1_VirtualNetworkConfig *)0; return (ZT_VirtualNetworkConfig *)0;
} }
} }
ZT1_VirtualNetworkList *ZT1_Node_networks(ZT1_Node *node) ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->networks(); return reinterpret_cast<ZeroTier::Node *>(node)->networks();
} catch ( ... ) { } catch ( ... ) {
return (ZT1_VirtualNetworkList *)0; return (ZT_VirtualNetworkList *)0;
} }
} }
void ZT1_Node_freeQueryResult(ZT1_Node *node,void *qr) void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
{ {
try { try {
reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr); reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
} catch ( ... ) {} } catch ( ... ) {}
} }
void ZT1_Node_setNetconfMaster(ZT1_Node *node,void *networkControllerInstance) void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
{ {
try { try {
reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance); reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
} catch ( ... ) {} } catch ( ... ) {}
} }
int ZT1_Node_addLocalInterfaceAddress(ZT1_Node *node,const struct sockaddr_storage *addr,int metric,ZT1_LocalInterfaceAddressTrust trust) int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr,int metric,ZT_LocalInterfaceAddressTrust trust)
{ {
try { try {
return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr,metric,trust); return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr,metric,trust);
@ -728,21 +730,21 @@ int ZT1_Node_addLocalInterfaceAddress(ZT1_Node *node,const struct sockaddr_stora
} }
} }
void ZT1_Node_clearLocalInterfaceAddresses(ZT1_Node *node) void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
{ {
try { try {
reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses(); reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
} catch ( ... ) {} } catch ( ... ) {}
} }
void ZT1_version(int *major,int *minor,int *revision,unsigned long *featureFlags) void ZT_version(int *major,int *minor,int *revision,unsigned long *featureFlags)
{ {
if (major) *major = ZEROTIER_ONE_VERSION_MAJOR; if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR; if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION; if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
if (featureFlags) { if (featureFlags) {
*featureFlags = ( *featureFlags = (
ZT1_FEATURE_FLAG_THREAD_SAFE ZT_FEATURE_FLAG_THREAD_SAFE
); );
} }
} }

View file

@ -58,7 +58,7 @@ namespace ZeroTier {
/** /**
* Implementation of Node object as defined in CAPI * Implementation of Node object as defined in CAPI
* *
* The pointer returned by ZT1_Node_new() is an instance of this class. * The pointer returned by ZT_Node_new() is an instance of this class.
*/ */
class Node class Node
{ {
@ -66,26 +66,26 @@ public:
Node( Node(
uint64_t now, uint64_t now,
void *uptr, void *uptr,
ZT1_DataStoreGetFunction dataStoreGetFunction, ZT_DataStoreGetFunction dataStoreGetFunction,
ZT1_DataStorePutFunction dataStorePutFunction, ZT_DataStorePutFunction dataStorePutFunction,
ZT1_WirePacketSendFunction wirePacketSendFunction, ZT_WirePacketSendFunction wirePacketSendFunction,
ZT1_VirtualNetworkFrameFunction virtualNetworkFrameFunction, ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
ZT1_VirtualNetworkConfigFunction virtualNetworkConfigFunction, ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
ZT1_EventCallback eventCallback, ZT_EventCallback eventCallback,
const char *overrideRootTopology); const char *overrideRootTopology);
~Node(); ~Node();
// Public API Functions ---------------------------------------------------- // Public API Functions ----------------------------------------------------
ZT1_ResultCode processWirePacket( ZT_ResultCode processWirePacket(
uint64_t now, uint64_t now,
int localInterfaceId, const struct sockaddr_storage *localAddress,
const struct sockaddr_storage *remoteAddress, const struct sockaddr_storage *remoteAddress,
const void *packetData, const void *packetData,
unsigned int packetLength, unsigned int packetLength,
volatile uint64_t *nextBackgroundTaskDeadline); volatile uint64_t *nextBackgroundTaskDeadline);
ZT1_ResultCode processVirtualNetworkFrame( ZT_ResultCode processVirtualNetworkFrame(
uint64_t now, uint64_t now,
uint64_t nwid, uint64_t nwid,
uint64_t sourceMac, uint64_t sourceMac,
@ -95,18 +95,18 @@ public:
const void *frameData, const void *frameData,
unsigned int frameLength, unsigned int frameLength,
volatile uint64_t *nextBackgroundTaskDeadline); volatile uint64_t *nextBackgroundTaskDeadline);
ZT1_ResultCode processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline); ZT_ResultCode processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline);
ZT1_ResultCode join(uint64_t nwid); ZT_ResultCode join(uint64_t nwid);
ZT1_ResultCode leave(uint64_t nwid); ZT_ResultCode leave(uint64_t nwid);
ZT1_ResultCode multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi); ZT_ResultCode multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
ZT1_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi); ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
uint64_t address() const; uint64_t address() const;
void status(ZT1_NodeStatus *status) const; void status(ZT_NodeStatus *status) const;
ZT1_PeerList *peers() const; ZT_PeerList *peers() const;
ZT1_VirtualNetworkConfig *networkConfig(uint64_t nwid) const; ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
ZT1_VirtualNetworkList *networks() const; ZT_VirtualNetworkList *networks() const;
void freeQueryResult(void *qr); void freeQueryResult(void *qr);
int addLocalInterfaceAddress(const struct sockaddr_storage *addr,int metric,ZT1_LocalInterfaceAddressTrust trust); int addLocalInterfaceAddress(const struct sockaddr_storage *addr,int metric,ZT_LocalInterfaceAddressTrust trust);
void clearLocalInterfaceAddresses(); void clearLocalInterfaceAddresses();
void setNetconfMaster(void *networkControllerInstance); void setNetconfMaster(void *networkControllerInstance);
@ -120,18 +120,18 @@ public:
/** /**
* Enqueue a ZeroTier message to be sent * Enqueue a ZeroTier message to be sent
* *
* @param localInterfaceId Local interface ID, -1 for unspecified/random * @param localAddress Local address
* @param addr Destination address * @param addr Destination address
* @param data Packet data * @param data Packet data
* @param len Packet length * @param len Packet length
* @return True if packet appears to have been sent * @return True if packet appears to have been sent
*/ */
inline bool putPacket(int localInterfaceId,const InetAddress &addr,const void *data,unsigned int len) inline bool putPacket(const InetAddress &localAddress,const InetAddress &addr,const void *data,unsigned int len)
{ {
return (_wirePacketSendFunction( return (_wirePacketSendFunction(
reinterpret_cast<ZT1_Node *>(this), reinterpret_cast<ZT_Node *>(this),
_uPtr, _uPtr,
localInterfaceId, reinterpret_cast<const struct sockaddr_storage *>(&localAddress),
reinterpret_cast<const struct sockaddr_storage *>(&addr), reinterpret_cast<const struct sockaddr_storage *>(&addr),
data, data,
len) == 0); len) == 0);
@ -151,7 +151,7 @@ public:
inline void putFrame(uint64_t nwid,const MAC &source,const MAC &dest,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len) inline void putFrame(uint64_t nwid,const MAC &source,const MAC &dest,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
{ {
_virtualNetworkFrameFunction( _virtualNetworkFrameFunction(
reinterpret_cast<ZT1_Node *>(this), reinterpret_cast<ZT_Node *>(this),
_uPtr, _uPtr,
nwid, nwid,
source.toInt(), source.toInt(),
@ -187,9 +187,9 @@ public:
return _directPaths; return _directPaths;
} }
inline bool dataStorePut(const char *name,const void *data,unsigned int len,bool secure) { return (_dataStorePutFunction(reinterpret_cast<ZT1_Node *>(this),_uPtr,name,data,len,(int)secure) == 0); } inline bool dataStorePut(const char *name,const void *data,unsigned int len,bool secure) { return (_dataStorePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,data,len,(int)secure) == 0); }
inline bool dataStorePut(const char *name,const std::string &data,bool secure) { return dataStorePut(name,(const void *)data.data(),(unsigned int)data.length(),secure); } inline bool dataStorePut(const char *name,const std::string &data,bool secure) { return dataStorePut(name,(const void *)data.data(),(unsigned int)data.length(),secure); }
inline void dataStoreDelete(const char *name) { _dataStorePutFunction(reinterpret_cast<ZT1_Node *>(this),_uPtr,name,(const void *)0,0,0); } inline void dataStoreDelete(const char *name) { _dataStorePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,(const void *)0,0,0); }
std::string dataStoreGet(const char *name); std::string dataStoreGet(const char *name);
/** /**
@ -198,7 +198,7 @@ public:
* @param ev Event type * @param ev Event type
* @param md Meta-data (default: NULL/none) * @param md Meta-data (default: NULL/none)
*/ */
inline void postEvent(ZT1_Event ev,const void *md = (const void *)0) { _eventCallback(reinterpret_cast<ZT1_Node *>(this),_uPtr,ev,md); } inline void postEvent(ZT_Event ev,const void *md = (const void *)0) { _eventCallback(reinterpret_cast<ZT_Node *>(this),_uPtr,ev,md); }
/** /**
* Update virtual network port configuration * Update virtual network port configuration
@ -207,7 +207,7 @@ public:
* @param op Configuration operation * @param op Configuration operation
* @param nc Network configuration * @param nc Network configuration
*/ */
inline int configureVirtualNetworkPort(uint64_t nwid,ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nc) { return _virtualNetworkConfigFunction(reinterpret_cast<ZT1_Node *>(this),_uPtr,nwid,op,nc); } inline int configureVirtualNetworkPort(uint64_t nwid,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc) { return _virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,nwid,op,nc); }
/** /**
* @return True if we appear to be online * @return True if we appear to be online
@ -244,12 +244,12 @@ private:
void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
ZT1_DataStoreGetFunction _dataStoreGetFunction; ZT_DataStoreGetFunction _dataStoreGetFunction;
ZT1_DataStorePutFunction _dataStorePutFunction; ZT_DataStorePutFunction _dataStorePutFunction;
ZT1_WirePacketSendFunction _wirePacketSendFunction; ZT_WirePacketSendFunction _wirePacketSendFunction;
ZT1_VirtualNetworkFrameFunction _virtualNetworkFrameFunction; ZT_VirtualNetworkFrameFunction _virtualNetworkFrameFunction;
ZT1_VirtualNetworkConfigFunction _virtualNetworkConfigFunction; ZT_VirtualNetworkConfigFunction _virtualNetworkConfigFunction;
ZT1_EventCallback _eventCallback; ZT_EventCallback _eventCallback;
std::vector< std::pair< uint64_t, SharedPtr<Network> > > _networks; std::vector< std::pair< uint64_t, SharedPtr<Network> > > _networks;
Mutex _networks_m; Mutex _networks_m;

View file

@ -57,7 +57,7 @@ public:
* Nearly all paths will be normal trust. The other levels are for high * Nearly all paths will be normal trust. The other levels are for high
* performance local SDN use only. * performance local SDN use only.
* *
* These values MUST match ZT1_LocalInterfaceAddressTrust in ZeroTierOne.h * These values MUST match ZT_LocalInterfaceAddressTrust in ZeroTierOne.h
*/ */
enum Trust enum Trust
{ {

View file

@ -64,7 +64,7 @@ Peer::Peer(const Identity &myIdentity,const Identity &peerIdentity)
void Peer::received( void Peer::received(
const RuntimeEnvironment *RR, const RuntimeEnvironment *RR,
int localInterfaceId, const InetAddress &localAddr,
const InetAddress &remoteAddr, const InetAddress &remoteAddr,
unsigned int hops, unsigned int hops,
uint64_t packetId, uint64_t packetId,
@ -82,7 +82,7 @@ void Peer::received(
{ {
unsigned int np = _numPaths; unsigned int np = _numPaths;
for(unsigned int p=0;p<np;++p) { for(unsigned int p=0;p<np;++p) {
if ((_paths[p].address() == remoteAddr)&&(_paths[p].localInterfaceId() == localInterfaceId)) { if ((_paths[p].address() == remoteAddr)&&(_paths[p].localAddress() == localAddr)) {
_paths[p].received(now); _paths[p].received(now);
pathIsConfirmed = true; pathIsConfirmed = true;
break; break;
@ -93,13 +93,13 @@ void Peer::received(
if ((verb == Packet::VERB_OK)&&(inReVerb == Packet::VERB_HELLO)) { if ((verb == Packet::VERB_OK)&&(inReVerb == Packet::VERB_HELLO)) {
// Learn paths if they've been confirmed via a HELLO // Learn paths if they've been confirmed via a HELLO
RemotePath *slot = (RemotePath *)0; RemotePath *slot = (RemotePath *)0;
if (np < ZT1_MAX_PEER_NETWORK_PATHS) { if (np < ZT_MAX_PEER_NETWORK_PATHS) {
// Add new path // Add new path
slot = &(_paths[np++]); slot = &(_paths[np++]);
} else { } else {
// Replace oldest non-fixed path // Replace oldest non-fixed path
uint64_t slotLRmin = 0xffffffffffffffffULL; uint64_t slotLRmin = 0xffffffffffffffffULL;
for(unsigned int p=0;p<ZT1_MAX_PEER_NETWORK_PATHS;++p) { for(unsigned int p=0;p<ZT_MAX_PEER_NETWORK_PATHS;++p) {
if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) { if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) {
slotLRmin = _paths[p].lastReceived(); slotLRmin = _paths[p].lastReceived();
slot = &(_paths[p]); slot = &(_paths[p]);
@ -107,7 +107,7 @@ void Peer::received(
} }
} }
if (slot) { if (slot) {
*slot = RemotePath(localInterfaceId,remoteAddr,false); *slot = RemotePath(localAddr,remoteAddr,false);
slot->received(now); slot->received(now);
_numPaths = np; _numPaths = np;
pathIsConfirmed = true; pathIsConfirmed = true;
@ -120,7 +120,7 @@ void Peer::received(
if ((now - _lastPathConfirmationSent) >= ZT_MIN_PATH_CONFIRMATION_INTERVAL) { if ((now - _lastPathConfirmationSent) >= ZT_MIN_PATH_CONFIRMATION_INTERVAL) {
_lastPathConfirmationSent = now; _lastPathConfirmationSent = now;
TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),remoteAddr.toString().c_str()); TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),remoteAddr.toString().c_str());
attemptToContactAt(RR,localInterfaceId,remoteAddr,now); attemptToContactAt(RR,localAddr,remoteAddr,now);
} }
} }
} }
@ -142,7 +142,7 @@ void Peer::received(
for(std::vector<MulticastGroup>::const_iterator mg(mgs.begin());mg!=mgs.end();++mg) { for(std::vector<MulticastGroup>::const_iterator mg(mgs.begin());mg!=mgs.end();++mg) {
if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) { if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
outp.armor(_key,true); outp.armor(_key,true);
RR->node->putPacket(localInterfaceId,remoteAddr,outp.data(),outp.size()); RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
outp.reset(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE); outp.reset(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
} }
@ -155,7 +155,7 @@ void Peer::received(
} }
if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) { if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
outp.armor(_key,true); outp.armor(_key,true);
RR->node->putPacket(localInterfaceId,remoteAddr,outp.data(),outp.size()); RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
} }
} }
} }
@ -181,7 +181,7 @@ RemotePath *Peer::getBestPath(uint64_t now)
return bestPath; return bestPath;
} }
void Peer::attemptToContactAt(const RuntimeEnvironment *RR,int localInterfaceId,const InetAddress &atAddress,uint64_t now) void Peer::attemptToContactAt(const RuntimeEnvironment *RR,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now)
{ {
Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO); Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
outp.append((unsigned char)ZT_PROTO_VERSION); outp.append((unsigned char)ZT_PROTO_VERSION);
@ -209,7 +209,7 @@ void Peer::attemptToContactAt(const RuntimeEnvironment *RR,int localInterfaceId,
} }
outp.armor(_key,false); // HELLO is sent in the clear outp.armor(_key,false); // HELLO is sent in the clear
RR->node->putPacket(localInterfaceId,atAddress,outp.data(),outp.size()); RR->node->putPacket(localAddr,atAddress,outp.data(),outp.size());
} }
void Peer::doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now) void Peer::doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now)
@ -218,12 +218,12 @@ void Peer::doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now)
if (bestPath) { if (bestPath) {
if ((now - bestPath->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) { if ((now - bestPath->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) {
TRACE("PING %s(%s)",_id.address().toString().c_str(),bestPath->address().toString().c_str()); TRACE("PING %s(%s)",_id.address().toString().c_str(),bestPath->address().toString().c_str());
attemptToContactAt(RR,bestPath->localInterfaceId(),bestPath->address(),now); attemptToContactAt(RR,bestPath->localAddress(),bestPath->address(),now);
bestPath->sent(now); bestPath->sent(now);
} else if (((now - bestPath->lastSend()) >= ZT_NAT_KEEPALIVE_DELAY)&&(!bestPath->reliable())) { } else if (((now - bestPath->lastSend()) >= ZT_NAT_KEEPALIVE_DELAY)&&(!bestPath->reliable())) {
_natKeepaliveBuf += (uint32_t)((now * 0x9e3779b1) >> 1); // tumble this around to send constantly varying (meaningless) payloads _natKeepaliveBuf += (uint32_t)((now * 0x9e3779b1) >> 1); // tumble this around to send constantly varying (meaningless) payloads
TRACE("NAT keepalive %s(%s)",_id.address().toString().c_str(),bestPath->address().toString().c_str()); TRACE("NAT keepalive %s(%s)",_id.address().toString().c_str(),bestPath->address().toString().c_str());
RR->node->putPacket(bestPath->localInterfaceId(),bestPath->address(),&_natKeepaliveBuf,sizeof(_natKeepaliveBuf)); RR->node->putPacket(bestPath->localAddress(),bestPath->address(),&_natKeepaliveBuf,sizeof(_natKeepaliveBuf));
bestPath->sent(now); bestPath->sent(now);
} }
} }
@ -311,13 +311,13 @@ void Peer::addPath(const RemotePath &newp)
} }
RemotePath *slot = (RemotePath *)0; RemotePath *slot = (RemotePath *)0;
if (np < ZT1_MAX_PEER_NETWORK_PATHS) { if (np < ZT_MAX_PEER_NETWORK_PATHS) {
// Add new path // Add new path
slot = &(_paths[np++]); slot = &(_paths[np++]);
} else { } else {
// Replace oldest non-fixed path // Replace oldest non-fixed path
uint64_t slotLRmin = 0xffffffffffffffffULL; uint64_t slotLRmin = 0xffffffffffffffffULL;
for(unsigned int p=0;p<ZT1_MAX_PEER_NETWORK_PATHS;++p) { for(unsigned int p=0;p<ZT_MAX_PEER_NETWORK_PATHS;++p) {
if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) { if ((!_paths[p].fixed())&&(_paths[p].lastReceived() <= slotLRmin)) {
slotLRmin = _paths[p].lastReceived(); slotLRmin = _paths[p].lastReceived();
slot = &(_paths[p]); slot = &(_paths[p]);
@ -355,7 +355,7 @@ bool Peer::resetWithinScope(const RuntimeEnvironment *RR,InetAddress::IpScope sc
while (x < np) { while (x < np) {
if (_paths[x].address().ipScope() == scope) { if (_paths[x].address().ipScope() == scope) {
if (_paths[x].fixed()) { if (_paths[x].fixed()) {
attemptToContactAt(RR,_paths[x].localInterfaceId(),_paths[x].address(),now); attemptToContactAt(RR,_paths[x].localAddress(),_paths[x].address(),now);
_paths[y++] = _paths[x]; // keep fixed paths _paths[y++] = _paths[x]; // keep fixed paths
} }
} else { } else {

View file

@ -105,7 +105,7 @@ public:
* and appears to be valid. * and appears to be valid.
* *
* @param RR Runtime environment * @param RR Runtime environment
* @param localInterfaceId Local interface ID or -1 if unspecified * @param localAddr Local address
* @param remoteAddr Internet address of sender * @param remoteAddr Internet address of sender
* @param hops ZeroTier (not IP) hops * @param hops ZeroTier (not IP) hops
* @param packetId Packet ID * @param packetId Packet ID
@ -115,7 +115,7 @@ public:
*/ */
void received( void received(
const RuntimeEnvironment *RR, const RuntimeEnvironment *RR,
int localInterfaceId, const InetAddress &localAddr,
const InetAddress &remoteAddr, const InetAddress &remoteAddr,
unsigned int hops, unsigned int hops,
uint64_t packetId, uint64_t packetId,
@ -157,11 +157,11 @@ public:
* for NAT traversal and path verification. * for NAT traversal and path verification.
* *
* @param RR Runtime environment * @param RR Runtime environment
* @param localInterfaceId Local interface ID or -1 for unspecified * @param localAddr Local address
* @param atAddress Destination address * @param atAddress Destination address
* @param now Current time * @param now Current time
*/ */
void attemptToContactAt(const RuntimeEnvironment *RR,int localInterfaceId,const InetAddress &atAddress,uint64_t now); void attemptToContactAt(const RuntimeEnvironment *RR,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now);
/** /**
* Send pings or keepalives depending on configured timeouts * Send pings or keepalives depending on configured timeouts
@ -417,7 +417,7 @@ private:
uint16_t _vMinor; uint16_t _vMinor;
uint16_t _vRevision; uint16_t _vRevision;
Identity _id; Identity _id;
RemotePath _paths[ZT1_MAX_PEER_NETWORK_PATHS]; RemotePath _paths[ZT_MAX_PEER_NETWORK_PATHS];
unsigned int _numPaths; unsigned int _numPaths;
unsigned int _latency; unsigned int _latency;

View file

@ -53,17 +53,17 @@ public:
Path(), Path(),
_lastSend(0), _lastSend(0),
_lastReceived(0), _lastReceived(0),
_localInterfaceId(-1), _localAddress(),
_fixed(false) {} _fixed(false) {}
RemotePath(int localInterfaceId,const InetAddress &addr,bool fixed) : RemotePath(const InetAddress &localAddress,const InetAddress &addr,bool fixed) :
Path(addr,0,TRUST_NORMAL), Path(addr,0,TRUST_NORMAL),
_lastSend(0), _lastSend(0),
_lastReceived(0), _lastReceived(0),
_localInterfaceId(localInterfaceId), _localAddress(localAddress),
_fixed(fixed) {} _fixed(fixed) {}
inline int localInterfaceId() const throw() { return _localInterfaceId; } inline const InetAddress &localAddress() const throw() { return _localAddress; }
inline uint64_t lastSend() const throw() { return _lastSend; } inline uint64_t lastSend() const throw() { return _lastSend; }
inline uint64_t lastReceived() const throw() { return _lastReceived; } inline uint64_t lastReceived() const throw() { return _lastReceived; }
@ -127,7 +127,7 @@ public:
*/ */
inline bool send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now) inline bool send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now)
{ {
if (RR->node->putPacket(_localInterfaceId,address(),data,len)) { if (RR->node->putPacket(_localAddress,address(),data,len)) {
sent(now); sent(now);
RR->antiRec->logOutgoingZT(data,len); RR->antiRec->logOutgoingZT(data,len);
return true; return true;
@ -138,7 +138,7 @@ public:
private: private:
uint64_t _lastSend; uint64_t _lastSend;
uint64_t _lastReceived; uint64_t _lastReceived;
int _localInterfaceId; InetAddress _localAddress;
bool _fixed; bool _fixed;
}; };

View file

@ -78,11 +78,8 @@ Switch::~Switch()
{ {
} }
void Switch::onRemotePacket(int localInterfaceId,const InetAddress &fromAddr,const void *data,unsigned int len) void Switch::onRemotePacket(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
{ {
if (localInterfaceId < 0)
localInterfaceId = 0;
try { try {
if (len == 13) { if (len == 13) {
/* LEGACY: before VERB_PUSH_DIRECT_PATHS, peers used broadcast /* LEGACY: before VERB_PUSH_DIRECT_PATHS, peers used broadcast
@ -99,14 +96,14 @@ void Switch::onRemotePacket(int localInterfaceId,const InetAddress &fromAddr,con
_lastBeaconResponse = now; _lastBeaconResponse = now;
Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NOP); Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NOP);
outp.armor(peer->key(),false); outp.armor(peer->key(),false);
RR->node->putPacket(localInterfaceId,fromAddr,outp.data(),outp.size()); RR->node->putPacket(localAddr,fromAddr,outp.data(),outp.size());
} }
} }
} else if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) { } else if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) {
if (((const unsigned char *)data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) { if (((const unsigned char *)data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
_handleRemotePacketFragment(localInterfaceId,fromAddr,data,len); _handleRemotePacketFragment(localAddr,fromAddr,data,len);
} else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) { } else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) {
_handleRemotePacketHead(localInterfaceId,fromAddr,data,len); _handleRemotePacketHead(localAddr,fromAddr,data,len);
} }
} }
} catch (std::exception &ex) { } catch (std::exception &ex) {
@ -379,14 +376,14 @@ bool Switch::unite(const Address &p1,const Address &p2,bool force)
return true; return true;
} }
void Switch::rendezvous(const SharedPtr<Peer> &peer,int localInterfaceId,const InetAddress &atAddr) void Switch::rendezvous(const SharedPtr<Peer> &peer,const InetAddress &localAddr,const InetAddress &atAddr)
{ {
TRACE("sending NAT-t message to %s(%s)",peer->address().toString().c_str(),atAddr.toString().c_str()); TRACE("sending NAT-t message to %s(%s)",peer->address().toString().c_str(),atAddr.toString().c_str());
const uint64_t now = RR->node->now(); const uint64_t now = RR->node->now();
peer->attemptToContactAt(RR,localInterfaceId,atAddr,now); peer->attemptToContactAt(RR,localAddr,atAddr,now);
{ {
Mutex::Lock _l(_contactQueue_m); Mutex::Lock _l(_contactQueue_m);
_contactQueue.push_back(ContactQueueEntry(peer,now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY,localInterfaceId,atAddr)); _contactQueue.push_back(ContactQueueEntry(peer,now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY,localAddr,atAddr));
} }
} }
@ -456,14 +453,14 @@ unsigned long Switch::doTimerTasks(uint64_t now)
} else { } else {
if (qi->strategyIteration == 0) { if (qi->strategyIteration == 0) {
// First strategy: send packet directly to destination // First strategy: send packet directly to destination
qi->peer->attemptToContactAt(RR,qi->localInterfaceId,qi->inaddr,now); qi->peer->attemptToContactAt(RR,qi->localAddr,qi->inaddr,now);
} else if (qi->strategyIteration <= 4) { } else if (qi->strategyIteration <= 4) {
// Strategies 1-4: try escalating ports for symmetric NATs that remap sequentially // Strategies 1-4: try escalating ports for symmetric NATs that remap sequentially
InetAddress tmpaddr(qi->inaddr); InetAddress tmpaddr(qi->inaddr);
int p = (int)qi->inaddr.port() + qi->strategyIteration; int p = (int)qi->inaddr.port() + qi->strategyIteration;
if (p < 0xffff) { if (p < 0xffff) {
tmpaddr.setPort((unsigned int)p); tmpaddr.setPort((unsigned int)p);
qi->peer->attemptToContactAt(RR,qi->localInterfaceId,tmpaddr,now); qi->peer->attemptToContactAt(RR,qi->localAddr,tmpaddr,now);
} else qi->strategyIteration = 5; } else qi->strategyIteration = 5;
} else { } else {
// All strategies tried, expire entry // All strategies tried, expire entry
@ -554,7 +551,7 @@ unsigned long Switch::doTimerTasks(uint64_t now)
return nextDelay; return nextDelay;
} }
void Switch::_handleRemotePacketFragment(int localInterfaceId,const InetAddress &fromAddr,const void *data,unsigned int len) void Switch::_handleRemotePacketFragment(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
{ {
Packet::Fragment fragment(data,len); Packet::Fragment fragment(data,len);
Address destination(fragment.destination()); Address destination(fragment.destination());
@ -625,9 +622,9 @@ void Switch::_handleRemotePacketFragment(int localInterfaceId,const InetAddress
} }
} }
void Switch::_handleRemotePacketHead(int localInterfaceId,const InetAddress &fromAddr,const void *data,unsigned int len) void Switch::_handleRemotePacketHead(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
{ {
SharedPtr<IncomingPacket> packet(new IncomingPacket(data,len,localInterfaceId,fromAddr,RR->node->now())); SharedPtr<IncomingPacket> packet(new IncomingPacket(data,len,localAddr,fromAddr,RR->node->now()));
Address source(packet->source()); Address source(packet->source());
Address destination(packet->destination()); Address destination(packet->destination());

View file

@ -79,12 +79,12 @@ public:
/** /**
* Called when a packet is received from the real network * Called when a packet is received from the real network
* *
* @param localInterfaceId Local interface ID or -1 for unspecified * @param localAddr Local interface address
* @param fromAddr Internet IP address of origin * @param fromAddr Internet IP address of origin
* @param data Packet data * @param data Packet data
* @param len Packet length * @param len Packet length
*/ */
void onRemotePacket(int localInterfaceId,const InetAddress &fromAddr,const void *data,unsigned int len); void onRemotePacket(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
/** /**
* Called when a packet comes from a local Ethernet tap * Called when a packet comes from a local Ethernet tap
@ -141,10 +141,10 @@ public:
* Attempt NAT traversal to peer at a given physical address * Attempt NAT traversal to peer at a given physical address
* *
* @param peer Peer to contact * @param peer Peer to contact
* @param localInterfaceId Local interface ID or -1 if unspecified * @param localAddr Local interface address
* @param atAddr Address of peer * @param atAddr Address of peer
*/ */
void rendezvous(const SharedPtr<Peer> &peer,int localInterfaceId,const InetAddress &atAddr); void rendezvous(const SharedPtr<Peer> &peer,const InetAddress &localAddr,const InetAddress &atAddr);
/** /**
* Request WHOIS on a given address * Request WHOIS on a given address
@ -181,8 +181,8 @@ public:
unsigned long doTimerTasks(uint64_t now); unsigned long doTimerTasks(uint64_t now);
private: private:
void _handleRemotePacketFragment(int localInterfaceId,const InetAddress &fromAddr,const void *data,unsigned int len); void _handleRemotePacketFragment(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
void _handleRemotePacketHead(int localInterfaceId,const InetAddress &fromAddr,const void *data,unsigned int len); void _handleRemotePacketHead(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
Address _sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted); Address _sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted);
bool _trySend(const Packet &packet,bool encrypt,uint64_t nwid); bool _trySend(const Packet &packet,bool encrypt,uint64_t nwid);
@ -262,17 +262,17 @@ private:
struct ContactQueueEntry struct ContactQueueEntry
{ {
ContactQueueEntry() {} ContactQueueEntry() {}
ContactQueueEntry(const SharedPtr<Peer> &p,uint64_t ft,int liid,const InetAddress &a) : ContactQueueEntry(const SharedPtr<Peer> &p,uint64_t ft,const InetAddress &laddr,const InetAddress &a) :
peer(p), peer(p),
fireAtTime(ft), fireAtTime(ft),
inaddr(a), inaddr(a),
localInterfaceId(liid), localAddr(laddr),
strategyIteration(0) {} strategyIteration(0) {}
SharedPtr<Peer> peer; SharedPtr<Peer> peer;
uint64_t fireAtTime; uint64_t fireAtTime;
InetAddress inaddr; InetAddress inaddr;
int localInterfaceId; InetAddress localAddr;
unsigned int strategyIteration; unsigned int strategyIteration;
}; };
std::list<ContactQueueEntry> _contactQueue; std::list<ContactQueueEntry> _contactQueue;

View file

@ -62,7 +62,7 @@ void Topology::setRootServers(const std::map< Identity,std::vector<InetAddress>
if (!p) if (!p)
p = SharedPtr<Peer>(new Peer(RR->identity,i->first)); p = SharedPtr<Peer>(new Peer(RR->identity,i->first));
for(std::vector<InetAddress>::const_iterator j(i->second.begin());j!=i->second.end();++j) for(std::vector<InetAddress>::const_iterator j(i->second.begin());j!=i->second.end();++j)
p->addPath(RemotePath(0,*j,true)); p->addPath(RemotePath(InetAddress(),*j,true));
p->use(now); p->use(now);
_rootPeers.push_back(p); _rootPeers.push_back(p);
} }

View file

@ -73,7 +73,7 @@
#include "service/OneService.hpp" #include "service/OneService.hpp"
#define ZT1_PID_PATH "zerotier-one.pid" #define ZT_PID_PATH "zerotier-one.pid"
using namespace ZeroTier; using namespace ZeroTier;
@ -976,7 +976,7 @@ int main(int argc,char **argv)
std::string overrideRootTopology; std::string overrideRootTopology;
std::string homeDir; std::string homeDir;
unsigned int port = ZT1_DEFAULT_PORT; unsigned int port = ZT_DEFAULT_PORT;
bool skipRootCheck = false; bool skipRootCheck = false;
for(int i=1;i<argc;++i) { for(int i=1;i<argc;++i) {
@ -1154,7 +1154,7 @@ int main(int argc,char **argv)
#endif // __WINDOWS__ #endif // __WINDOWS__
#ifdef __UNIX_LIKE__ #ifdef __UNIX_LIKE__
std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT1_PID_PATH); std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
{ {
// Write .pid file to home folder // Write .pid file to home folder
FILE *pf = fopen(pidPath.c_str(),"w"); FILE *pf = fopen(pidPath.c_str(),"w");

View file

@ -64,7 +64,7 @@ static std::string _jsonEscape(const char *s)
} }
static std::string _jsonEscape(const std::string &s) { return _jsonEscape(s.c_str()); } static std::string _jsonEscape(const std::string &s) { return _jsonEscape(s.c_str()); }
static std::string _jsonEnumerate(const ZT1_MulticastGroup *mg,unsigned int count) static std::string _jsonEnumerate(const ZT_MulticastGroup *mg,unsigned int count)
{ {
std::string buf; std::string buf;
char tmp[128]; char tmp[128];
@ -101,7 +101,7 @@ static std::string _jsonEnumerate(const struct sockaddr_storage *ss,unsigned int
return buf; return buf;
} }
static void _jsonAppend(unsigned int depth,std::string &buf,const ZT1_VirtualNetworkConfig *nc,const std::string &portDeviceName) static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName)
{ {
char json[4096]; char json[4096];
char prefix[32]; char prefix[32];
@ -114,16 +114,16 @@ static void _jsonAppend(unsigned int depth,std::string &buf,const ZT1_VirtualNet
const char *nstatus = "",*ntype = ""; const char *nstatus = "",*ntype = "";
switch(nc->status) { switch(nc->status) {
case ZT1_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break; case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
case ZT1_NETWORK_STATUS_OK: nstatus = "OK"; break; case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
case ZT1_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break; case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
case ZT1_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break; case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
case ZT1_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break; case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
case ZT1_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break; case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
} }
switch(nc->type) { switch(nc->type) {
case ZT1_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break; case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
case ZT1_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break; case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
} }
Utils::snprintf(json,sizeof(json), Utils::snprintf(json,sizeof(json),
@ -162,7 +162,7 @@ static void _jsonAppend(unsigned int depth,std::string &buf,const ZT1_VirtualNet
buf.append(json); buf.append(json);
} }
static std::string _jsonEnumerate(unsigned int depth,const ZT1_PeerPhysicalPath *pp,unsigned int count) static std::string _jsonEnumerate(unsigned int depth,const ZT_PeerPhysicalPath *pp,unsigned int count)
{ {
char json[1024]; char json[1024];
char prefix[32]; char prefix[32];
@ -198,7 +198,7 @@ static std::string _jsonEnumerate(unsigned int depth,const ZT1_PeerPhysicalPath
return buf; return buf;
} }
static void _jsonAppend(unsigned int depth,std::string &buf,const ZT1_Peer *peer) static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_Peer *peer)
{ {
char json[1024]; char json[1024];
char prefix[32]; char prefix[32];
@ -211,9 +211,9 @@ static void _jsonAppend(unsigned int depth,std::string &buf,const ZT1_Peer *peer
const char *prole = ""; const char *prole = "";
switch(peer->role) { switch(peer->role) {
case ZT1_PEER_ROLE_LEAF: prole = "LEAF"; break; case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
case ZT1_PEER_ROLE_RELAY: prole = "RELAY"; break; case ZT_PEER_ROLE_RELAY: prole = "RELAY"; break;
case ZT1_PEER_ROLE_ROOT: prole = "ROOT"; break; case ZT_PEER_ROLE_ROOT: prole = "ROOT"; break;
} }
Utils::snprintf(json,sizeof(json), Utils::snprintf(json,sizeof(json),
@ -356,7 +356,7 @@ unsigned int ControlPlane::handleRequest(
if (ps[0] == "status") { if (ps[0] == "status") {
responseContentType = "application/json"; responseContentType = "application/json";
ZT1_NodeStatus status; ZT_NodeStatus status;
_node->status(&status); _node->status(&status);
Utils::snprintf(json,sizeof(json), Utils::snprintf(json,sizeof(json),
"{\n" "{\n"
@ -386,7 +386,7 @@ unsigned int ControlPlane::handleRequest(
responseBody = "{}"; // TODO responseBody = "{}"; // TODO
scode = 200; scode = 200;
} else if (ps[0] == "network") { } else if (ps[0] == "network") {
ZT1_VirtualNetworkList *nws = _node->networks(); ZT_VirtualNetworkList *nws = _node->networks();
if (nws) { if (nws) {
if (ps.size() == 1) { if (ps.size() == 1) {
// Return [array] of all networks // Return [array] of all networks
@ -415,7 +415,7 @@ unsigned int ControlPlane::handleRequest(
_node->freeQueryResult((void *)nws); _node->freeQueryResult((void *)nws);
} else scode = 500; } else scode = 500;
} else if (ps[0] == "peer") { } else if (ps[0] == "peer") {
ZT1_PeerList *pl = _node->peers(); ZT_PeerList *pl = _node->peers();
if (pl) { if (pl) {
if (ps.size() == 1) { if (ps.size() == 1) {
// Return [array] of all peers // Return [array] of all peers
@ -473,7 +473,7 @@ unsigned int ControlPlane::handleRequest(
if (ps.size() == 2) { if (ps.size() == 2) {
uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str()); uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
_node->join(wantnw); // does nothing if we are a member _node->join(wantnw); // does nothing if we are a member
ZT1_VirtualNetworkList *nws = _node->networks(); ZT_VirtualNetworkList *nws = _node->networks();
if (nws) { if (nws) {
for(unsigned long i=0;i<nws->networkCount;++i) { for(unsigned long i=0;i<nws->networkCount;++i) {
if (nws->networks[i].nwid == wantnw) { if (nws->networks[i].nwid == wantnw) {
@ -506,7 +506,7 @@ unsigned int ControlPlane::handleRequest(
if (ps[0] == "config") { if (ps[0] == "config") {
// TODO // TODO
} else if (ps[0] == "network") { } else if (ps[0] == "network") {
ZT1_VirtualNetworkList *nws = _node->networks(); ZT_VirtualNetworkList *nws = _node->networks();
if (nws) { if (nws) {
if (ps.size() == 2) { if (ps.size() == 2) {
uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str()); uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());

View file

@ -118,20 +118,20 @@ namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
#define ZT_TAP_CHECK_MULTICAST_INTERVAL 30000 #define ZT_TAP_CHECK_MULTICAST_INTERVAL 30000
// Path under ZT1 home for controller database if controller is enabled // Path under ZT1 home for controller database if controller is enabled
#define ZT1_CONTROLLER_DB_PATH "controller.db" #define ZT_CONTROLLER_DB_PATH "controller.db"
// TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS // TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
#define ZT1_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com" #define ZT_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
#define ZT1_TCP_FALLBACK_RELAY_PORT 443 #define ZT_TCP_FALLBACK_RELAY_PORT 443
// Frequency at which we re-resolve the TCP fallback relay // Frequency at which we re-resolve the TCP fallback relay
#define ZT1_TCP_FALLBACK_RERESOLVE_DELAY 86400000 #define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
// Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs // Attempt to engage TCP fallback after this many ms of no reply to packets sent to global-scope IPs
#define ZT1_TCP_FALLBACK_AFTER 60000 #define ZT_TCP_FALLBACK_AFTER 60000
// How often to check for local interface addresses // How often to check for local interface addresses
#define ZT1_LOCAL_INTERFACE_CHECK_INTERVAL 300000 #define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 300000
namespace ZeroTier { namespace ZeroTier {
@ -340,12 +340,12 @@ static BackgroundSoftwareUpdateChecker backgroundSoftwareUpdateChecker;
class OneServiceImpl; class OneServiceImpl;
static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf); static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData); static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData);
static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize); static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize);
static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure); static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,int localInterfaceId,const struct sockaddr_storage *addr,const void *data,unsigned int len); static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len);
static void SnodeVirtualNetworkFrameFunction(ZT1_Node *node,void *uptr,uint64_t nwid,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,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
static void StapFrameHandler(void *uptr,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,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
@ -396,18 +396,14 @@ struct TcpConnection
Mutex writeBuf_m; Mutex writeBuf_m;
}; };
// Interface IDs -- the uptr for UDP sockets is set to point to one of these
static const int ZT1_INTERFACE_ID_DEFAULT = 0; // default, usually port 9993
static const int ZT1_INTERFACE_ID_UPNP = 1; // a randomly chosen UDP socket used with uPnP mappings, if enabled
class OneServiceImpl : public OneService class OneServiceImpl : public OneService
{ {
public: public:
OneServiceImpl(const char *hp,unsigned int port,const char *overrideRootTopology) : OneServiceImpl(const char *hp,unsigned int port,const char *overrideRootTopology) :
_homePath((hp) ? hp : "."), _homePath((hp) ? hp : "."),
_tcpFallbackResolver(ZT1_TCP_FALLBACK_RELAY), _tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY),
#ifdef ZT_ENABLE_NETWORK_CONTROLLER #ifdef ZT_ENABLE_NETWORK_CONTROLLER
_controller((_homePath + ZT_PATH_SEPARATOR_S + ZT1_CONTROLLER_DB_PATH).c_str()), _controller((_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str()),
#endif #endif
_phy(this,false,true), _phy(this,false,true),
_overrideRootTopology((overrideRootTopology) ? overrideRootTopology : ""), _overrideRootTopology((overrideRootTopology) ? overrideRootTopology : ""),
@ -426,9 +422,6 @@ public:
#endif #endif
_run(true) _run(true)
{ {
struct sockaddr_in in4;
struct sockaddr_in6 in6;
const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
for(int k=0;k<portTrials;++k) { for(int k=0;k<portTrials;++k) {
if (port == 0) { if (port == 0) {
@ -437,24 +430,26 @@ public:
port = 40000 + (randp % 25500); port = 40000 + (randp % 25500);
} }
memset((void *)&in4,0,sizeof(in4)); _v4LocalAddress = InetAddress((uint32_t)0,port);
in4.sin_family = AF_INET; _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&_v4LocalAddress,reinterpret_cast<void *>(&_v4LocalAddress),131072);
in4.sin_port = Utils::hton((uint16_t)port);
_v4UdpSocket = _phy.udpBind((const struct sockaddr *)&in4,reinterpret_cast<void *>(const_cast<int *>(&ZT1_INTERFACE_ID_DEFAULT)),131072);
if (_v4UdpSocket) { if (_v4UdpSocket) {
struct sockaddr_in in4;
memset(&in4,0,sizeof(in4));
in4.sin_family = AF_INET;
in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost
in4.sin_port = Utils::hton((uint16_t)port);
_v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this); _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
if (_v4TcpListenSocket) { if (_v4TcpListenSocket) {
_v6LocalAddress = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port);
_v6UdpSocket = _phy.udpBind((const struct sockaddr *)&_v6LocalAddress,reinterpret_cast<void *>(&_v6LocalAddress),131072);
struct sockaddr_in6 in6;
memset((void *)&in6,0,sizeof(in6)); memset((void *)&in6,0,sizeof(in6));
in6.sin6_family = AF_INET6; in6.sin6_family = AF_INET6;
in6.sin6_port = in4.sin_port; in6.sin6_port = in4.sin_port;
in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
_v6UdpSocket = _phy.udpBind((const struct sockaddr *)&in6,reinterpret_cast<void *>(const_cast<int *>(&ZT1_INTERFACE_ID_DEFAULT)),131072);
in6.sin6_addr.s6_addr[15] = 1; // listen for TCP only at localhost
_v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this); _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
_port = port; _port = port;
@ -484,11 +479,8 @@ public:
Utils::getSecureRandom(&randp,sizeof(randp)); Utils::getSecureRandom(&randp,sizeof(randp));
unsigned int upnport = 40000 + (randp % 25500); unsigned int upnport = 40000 + (randp % 25500);
memset((void *)&in4,0,sizeof(in4)); _v4UpnpLocalAddress = InetAddress(0,upnport);
in4.sin_family = AF_INET; _v4UpnpUdpSocket = _phy.udpBind((const struct sockaddr *)&_v4UpnpLocalAddress,reinterpret_cast<void *>(&_v4UpnpLocalAddress),131072);
in4.sin_port = Utils::hton((uint16_t)upnport);
_v4UpnpUdpSocket = _phy.udpBind((const struct sockaddr *)&in4,reinterpret_cast<void *>(const_cast<int *>(&ZT1_INTERFACE_ID_UPNP)),131072);
if (_v4UpnpUdpSocket) { if (_v4UpnpUdpSocket) {
_upnpClient = new UPNPClient(upnport); _upnpClient = new UPNPClient(upnport);
break; break;
@ -567,7 +559,7 @@ public:
_lastRestart = clockShouldBe; _lastRestart = clockShouldBe;
uint64_t lastTapMulticastGroupCheck = 0; uint64_t lastTapMulticastGroupCheck = 0;
uint64_t lastTcpFallbackResolve = 0; uint64_t lastTcpFallbackResolve = 0;
uint64_t lastLocalInterfaceAddressCheck = (OSUtils::now() - ZT1_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give UPnP time to configure and other things time to settle uint64_t lastLocalInterfaceAddressCheck = (OSUtils::now() - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give UPnP time to configure and other things time to settle
#ifdef ZT_AUTO_UPDATE #ifdef ZT_AUTO_UPDATE
uint64_t lastSoftwareUpdateCheck = 0; uint64_t lastSoftwareUpdateCheck = 0;
#endif // ZT_AUTO_UPDATE #endif // ZT_AUTO_UPDATE
@ -600,12 +592,12 @@ public:
} }
#endif // ZT_AUTO_UPDATE #endif // ZT_AUTO_UPDATE
if ((now - lastTcpFallbackResolve) >= ZT1_TCP_FALLBACK_RERESOLVE_DELAY) { if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
lastTcpFallbackResolve = now; lastTcpFallbackResolve = now;
_tcpFallbackResolver.resolveNow(); _tcpFallbackResolver.resolveNow();
} }
if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT1_TCP_FALLBACK_AFTER / 2))) if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
_phy.close(_tcpFallbackTunnel->sock); _phy.close(_tcpFallbackTunnel->sock);
if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) { if ((now - lastTapMulticastGroupCheck) >= ZT_TAP_CHECK_MULTICAST_INTERVAL) {
@ -621,7 +613,7 @@ public:
} }
} }
if ((now - lastLocalInterfaceAddressCheck) >= ZT1_LOCAL_INTERFACE_CHECK_INTERVAL) { if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
lastLocalInterfaceAddressCheck = now; lastLocalInterfaceAddressCheck = now;
#ifdef __UNIX_LIKE__ #ifdef __UNIX_LIKE__
@ -637,7 +629,7 @@ public:
#ifdef ZT_USE_MINIUPNPC #ifdef ZT_USE_MINIUPNPC
std::vector<InetAddress> upnpAddresses(_upnpClient->get()); std::vector<InetAddress> upnpAddresses(_upnpClient->get());
for(std::vector<InetAddress>::const_iterator ext(upnpAddresses.begin());ext!=upnpAddresses.end();++ext) for(std::vector<InetAddress>::const_iterator ext(upnpAddresses.begin());ext!=upnpAddresses.end();++ext)
_node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)),0,ZT1_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL); _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)),0,ZT_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL);
#endif #endif
struct ifaddrs *ifatbl = (struct ifaddrs *)0; struct ifaddrs *ifatbl = (struct ifaddrs *)0;
@ -655,7 +647,7 @@ public:
if (!isZT) { if (!isZT) {
InetAddress ip(ifa->ifa_addr); InetAddress ip(ifa->ifa_addr);
ip.setPort(_port); ip.setPort(_port);
_node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip),0,ZT1_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL); _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip),0,ZT_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL);
} }
} }
ifa = ifa->ifa_next; ifa = ifa->ifa_next;
@ -689,7 +681,7 @@ public:
while (ua) { while (ua) {
InetAddress ip(ua->Address.lpSockaddr); InetAddress ip(ua->Address.lpSockaddr);
ip.setPort(_port); ip.setPort(_port);
_node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip),0,ZT1_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL); _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip),0,ZT_LOCAL_INTERFACE_ADDRESS_TRUST_NORMAL);
ua = ua->Next; ua = ua->Next;
} }
} }
@ -777,14 +769,14 @@ public:
#endif #endif
if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
_lastDirectReceiveFromGlobal = OSUtils::now(); _lastDirectReceiveFromGlobal = OSUtils::now();
ZT1_ResultCode rc = _node->processWirePacket( ZT_ResultCode rc = _node->processWirePacket(
OSUtils::now(), OSUtils::now(),
*(reinterpret_cast<const int *>(*uptr)), // for UDP sockets, we set uptr to point to their interface ID reinterpret_cast<const struct sockaddr_storage *>(*uptr),
(const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big (const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
data, data,
len, len,
&_nextBackgroundTaskDeadline); &_nextBackgroundTaskDeadline);
if (ZT1_ResultCode_isFatal(rc)) { if (ZT_ResultCode_isFatal(rc)) {
char tmp[256]; char tmp[256];
Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc); Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
Mutex::Lock _l(_termReason_m); Mutex::Lock _l(_termReason_m);
@ -926,14 +918,14 @@ public:
} }
if (from) { if (from) {
ZT1_ResultCode rc = _node->processWirePacket( ZT_ResultCode rc = _node->processWirePacket(
OSUtils::now(), OSUtils::now(),
0, 0,
reinterpret_cast<struct sockaddr_storage *>(&from), reinterpret_cast<struct sockaddr_storage *>(&from),
data, data,
plen, plen,
&_nextBackgroundTaskDeadline); &_nextBackgroundTaskDeadline);
if (ZT1_ResultCode_isFatal(rc)) { if (ZT_ResultCode_isFatal(rc)) {
char tmp[256]; char tmp[256];
Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc); Utils::snprintf(tmp,sizeof(tmp),"fatal error code from processWirePacket: %d",(int)rc);
Mutex::Lock _l(_termReason_m); Mutex::Lock _l(_termReason_m);
@ -986,12 +978,12 @@ public:
inline void phyOnSocketPairEndpointData(PhySocket *sock,void **uptr,void *data,unsigned long len) {} inline void phyOnSocketPairEndpointData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
inline void phyOnSocketPairEndpointWritable(PhySocket *sock,void **uptr) {} inline void phyOnSocketPairEndpointWritable(PhySocket *sock,void **uptr) {}
inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwc) inline int nodeVirtualNetworkConfigFunction(uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwc)
{ {
Mutex::Lock _l(_taps_m); Mutex::Lock _l(_taps_m);
std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid)); std::map< uint64_t,EthernetTap * >::iterator t(_taps.find(nwid));
switch(op) { switch(op) {
case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_UP: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
if (t == _taps.end()) { if (t == _taps.end()) {
try { try {
char friendlyName[1024]; char friendlyName[1024];
@ -1021,7 +1013,7 @@ public:
} }
} }
// fall through... // fall through...
case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
if (t != _taps.end()) { if (t != _taps.end()) {
t->second->setEnabled(nwc->enabled != 0); t->second->setEnabled(nwc->enabled != 0);
@ -1044,8 +1036,8 @@ public:
return -999; // tap init failed return -999; // tap init failed
} }
break; break;
case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN:
case ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY: case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY:
if (t != _taps.end()) { if (t != _taps.end()) {
#ifdef __WINDOWS__ #ifdef __WINDOWS__
std::string winInstanceId(t->second->instanceId()); std::string winInstanceId(t->second->instanceId());
@ -1054,7 +1046,7 @@ public:
_taps.erase(t); _taps.erase(t);
_tapAssignedIps.erase(nwid); _tapAssignedIps.erase(nwid);
#ifdef __WINDOWS__ #ifdef __WINDOWS__
if ((op == ZT1_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0)) if ((op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY)&&(winInstanceId.length() > 0))
WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str()); WindowsEthernetTap::deletePersistentTapDevice(winInstanceId.c_str());
#endif #endif
} }
@ -1063,17 +1055,17 @@ public:
return 0; return 0;
} }
inline void nodeEventCallback(enum ZT1_Event event,const void *metaData) inline void nodeEventCallback(enum ZT_Event event,const void *metaData)
{ {
switch(event) { switch(event) {
case ZT1_EVENT_FATAL_ERROR_IDENTITY_COLLISION: { case ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION: {
Mutex::Lock _l(_termReason_m); Mutex::Lock _l(_termReason_m);
_termReason = ONE_IDENTITY_COLLISION; _termReason = ONE_IDENTITY_COLLISION;
_fatalErrorMessage = "identity/address collision"; _fatalErrorMessage = "identity/address collision";
this->terminate(); this->terminate();
} break; } break;
case ZT1_EVENT_TRACE: { case ZT_EVENT_TRACE: {
if (metaData) { if (metaData) {
::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData); ::fprintf(stderr,"%s"ZT_EOL_S,(const char *)metaData);
::fflush(stderr); ::fflush(stderr);
@ -1139,10 +1131,10 @@ public:
} }
} }
inline int nodeWirePacketSendFunction(int localInterfaceId,const struct sockaddr_storage *addr,const void *data,unsigned int len) inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len)
{ {
#ifdef ZT_USE_MINIUPNPC #ifdef ZT_USE_MINIUPNPC
if (localInterfaceId == ZT1_INTERFACE_ID_UPNP) { if ((localAddr->ss_family == AF_INET)&&(reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == reinterpret_cast<const struct sockaddr_in *>(&_v4UpnpLocalAddress)->sin_port)) {
#ifdef ZT_BREAK_UDP #ifdef ZT_BREAK_UDP
if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) { if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
#endif #endif
@ -1167,15 +1159,15 @@ public:
} }
#endif #endif
#ifdef ZT1_TCP_FALLBACK_RELAY #ifdef ZT_TCP_FALLBACK_RELAY
// TCP fallback tunnel support // TCP fallback tunnel support
if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) { if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
uint64_t now = OSUtils::now(); uint64_t now = OSUtils::now();
// Engage TCP tunnel fallback if we haven't received anything valid from a global // Engage TCP tunnel fallback if we haven't received anything valid from a global
// IP address in ZT1_TCP_FALLBACK_AFTER milliseconds. If we do start getting // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
// valid direct traffic we'll stop using it and close the socket after a while. // valid direct traffic we'll stop using it and close the socket after a while.
if (((now - _lastDirectReceiveFromGlobal) > ZT1_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT1_TCP_FALLBACK_AFTER)) { if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
if (_tcpFallbackTunnel) { if (_tcpFallbackTunnel) {
Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m); Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
if (!_tcpFallbackTunnel->writeBuf.length()) if (!_tcpFallbackTunnel->writeBuf.length())
@ -1191,7 +1183,7 @@ public:
_tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2); _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
_tcpFallbackTunnel->writeBuf.append((const char *)data,len); _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
result = 0; result = 0;
} else if (((now - _lastSendToGlobal) < ZT1_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobal) > (ZT_PING_CHECK_INVERVAL / 2))) { } else if (((now - _lastSendToGlobal) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobal) > (ZT_PING_CHECK_INVERVAL / 2))) {
std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get()); std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
if (tunnelIps.empty()) { if (tunnelIps.empty()) {
if (!_tcpFallbackResolver.running()) if (!_tcpFallbackResolver.running())
@ -1199,7 +1191,7 @@ public:
} else { } else {
bool connected = false; bool connected = false;
InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]); InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
addr.setPort(ZT1_TCP_FALLBACK_RELAY_PORT); addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
_phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected); _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
} }
} }
@ -1207,7 +1199,7 @@ public:
_lastSendToGlobal = now; _lastSendToGlobal = now;
} }
#endif // ZT1_TCP_FALLBACK_RELAY #endif // ZT_TCP_FALLBACK_RELAY
break; break;
@ -1319,6 +1311,7 @@ private:
Phy<OneServiceImpl *> _phy; Phy<OneServiceImpl *> _phy;
std::string _overrideRootTopology; std::string _overrideRootTopology;
Node *_node; Node *_node;
InetAddress _v4LocalAddress,_v6LocalAddress;
PhySocket *_v4UdpSocket; PhySocket *_v4UdpSocket;
PhySocket *_v6UdpSocket; PhySocket *_v6UdpSocket;
PhySocket *_v4TcpListenSocket; PhySocket *_v4TcpListenSocket;
@ -1343,6 +1336,7 @@ private:
unsigned int _port; unsigned int _port;
#ifdef ZT_USE_MINIUPNPC #ifdef ZT_USE_MINIUPNPC
InetAddress _v4UpnpLocalAddress;
PhySocket *_v4UpnpUdpSocket; PhySocket *_v4UpnpUdpSocket;
UPNPClient *_upnpClient; UPNPClient *_upnpClient;
#endif #endif
@ -1351,17 +1345,17 @@ private:
Mutex _run_m; Mutex _run_m;
}; };
static int SnodeVirtualNetworkConfigFunction(ZT1_Node *node,void *uptr,uint64_t nwid,enum ZT1_VirtualNetworkConfigOperation op,const ZT1_VirtualNetworkConfig *nwconf) static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); } { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkConfigFunction(nwid,op,nwconf); }
static void SnodeEventCallback(ZT1_Node *node,void *uptr,enum ZT1_Event event,const void *metaData) static void SnodeEventCallback(ZT_Node *node,void *uptr,enum ZT_Event event,const void *metaData)
{ reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); } { reinterpret_cast<OneServiceImpl *>(uptr)->nodeEventCallback(event,metaData); }
static long SnodeDataStoreGetFunction(ZT1_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize) static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,void *buf,unsigned long bufSize,unsigned long readIndex,unsigned long *totalSize)
{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); } { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStoreGetFunction(name,buf,bufSize,readIndex,totalSize); }
static int SnodeDataStorePutFunction(ZT1_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure) static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure)
{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); } { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeDataStorePutFunction(name,data,len,secure); }
static int SnodeWirePacketSendFunction(ZT1_Node *node,void *uptr,int localInterfaceId,const struct sockaddr_storage *addr,const void *data,unsigned int len) static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len)
{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localInterfaceId,addr,data,len); } { return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len); }
static void SnodeVirtualNetworkFrameFunction(ZT1_Node *node,void *uptr,uint64_t nwid,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,uint64_t nwid,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
{ reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); } { reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,sourceMac,destMac,etherType,vlanId,data,len); }
static void StapFrameHandler(void *uptr,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,uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)

View file

@ -90,7 +90,7 @@ restart_node:
_service = (ZeroTier::OneService *)0; // in case newInstance() fails _service = (ZeroTier::OneService *)0; // in case newInstance() fails
_service = ZeroTier::OneService::newInstance( _service = ZeroTier::OneService::newInstance(
ZeroTier::OneService::platformDefaultHomePath().c_str(), ZeroTier::OneService::platformDefaultHomePath().c_str(),
ZT1_DEFAULT_PORT); ZT_DEFAULT_PORT);
} }
switch(_service->run()) { switch(_service->run()) {
case ZeroTier::OneService::ONE_UNRECOVERABLE_ERROR: { case ZeroTier::OneService::ONE_UNRECOVERABLE_ERROR: {