diff --git a/java/jni/ZT_jniarray.cpp b/java/jni/ZT_jniarray.cpp
deleted file mode 100644
index a1cae76ed..000000000
--- a/java/jni/ZT_jniarray.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-//
-// Created by Grant Limberg on 10/21/20.
-//
-
-#include "ZT_jniarray.h"
-#include
-#include
-#include
-
-jclass java_util_ArrayList;
-jmethodID java_util_ArrayList_;
-jmethodID java_util_ArrayList_size;
-jmethodID java_util_ArrayList_get;
-jmethodID java_util_ArrayList_add;
-
-void InitListJNI(JNIEnv* env) {
- java_util_ArrayList = static_cast(env->NewGlobalRef(env->FindClass("java/util/ArrayList")));
- java_util_ArrayList_ = env->GetMethodID(java_util_ArrayList, "", "(I)V");
- java_util_ArrayList_size = env->GetMethodID (java_util_ArrayList, "size", "()I");
- java_util_ArrayList_get = env->GetMethodID(java_util_ArrayList, "get", "(I)Ljava/lang/Object;");
- java_util_ArrayList_add = env->GetMethodID(java_util_ArrayList, "add", "(Ljava/lang/Object;)Z");
-}
-
-jclass ListJNI::getListClass(JNIEnv* env) {
- jclass jclazz = env->FindClass("java/util/List");
- assert(jclazz != nullptr);
- return jclazz;
-}
-
-jclass ListJNI::getArrayListClass(JNIEnv* env) {
- jclass jclazz = env->FindClass("java/util/ArrayList");
- assert(jclazz != nullptr);
- return jclazz;
-}
-
-jclass ListJNI::getIteratorClass(JNIEnv* env) {
- jclass jclazz = env->FindClass("java/util/Iterator");
- assert(jclazz != nullptr);
- return jclazz;
-}
-
-jmethodID ListJNI::getIteratorMethod(JNIEnv* env) {
- static jmethodID mid = env->GetMethodID(
- getListClass(env), "iterator", "()Ljava/util/Iterator;");
- assert(mid != nullptr);
- return mid;
-}
-
-jmethodID ListJNI::getHasNextMethod(JNIEnv* env) {
- static jmethodID mid = env->GetMethodID(
- getIteratorClass(env), "hasNext", "()Z");
- assert(mid != nullptr);
- return mid;
-}
-
-jmethodID ListJNI::getNextMethod(JNIEnv* env) {
- static jmethodID mid = env->GetMethodID(
- getIteratorClass(env), "next", "()Ljava/lang/Object;");
- assert(mid != nullptr);
- return mid;
-}
-
-jmethodID ListJNI::getArrayListConstructorMethodId(JNIEnv* env, jclass jclazz) {
- static jmethodID mid = env->GetMethodID(
- jclazz, "", "(I)V");
- assert(mid != nullptr);
- return mid;
-}
-
-jmethodID ListJNI::getListAddMethodId(JNIEnv* env) {
- static jmethodID mid = env->GetMethodID(
- getListClass(env), "add", "(Ljava/lang/Object;)Z");
- assert(mid != nullptr);
- return mid;
-}
-
-jclass ByteJNI::getByteClass(JNIEnv* env) {
- jclass jclazz = env->FindClass("java/lang/Byte");
- assert(jclazz != nullptr);
- return jclazz;
-}
-
-jmethodID ByteJNI::getByteValueMethod(JNIEnv* env) {
- static jmethodID mid = env->GetMethodID(
- getByteClass(env), "byteValue", "()B");
- assert(mid != nullptr);
- return mid;
-}
-
-jobject cppToJava(JNIEnv* env, std::vector vector) {
- jobject result = env->NewObject(java_util_ArrayList, java_util_ArrayList_, vector.size());
- for (std::string s: vector) {
- jstring element = env->NewStringUTF(s.c_str());
- env->CallBooleanMethod(result, java_util_ArrayList_add, element);
- env->DeleteLocalRef(element);
- }
- return result;
-}
-
-std::vector javaToCpp(JNIEnv* env, jobject arrayList) {
- jint len = env->CallIntMethod(arrayList, java_util_ArrayList_size);
- std::vector result;
- result.reserve(len);
- for (jint i=0; i(env->CallObjectMethod(arrayList, java_util_ArrayList_get, i));
- const char* pchars = env->GetStringUTFChars(element, nullptr);
- result.emplace_back(pchars);
- env->ReleaseStringUTFChars(element, pchars);
- env->DeleteLocalRef(element);
- }
- return result;
-}
diff --git a/java/jni/ZT_jniarray.h b/java/jni/ZT_jniarray.h
deleted file mode 100644
index d93c87b9c..000000000
--- a/java/jni/ZT_jniarray.h
+++ /dev/null
@@ -1,60 +0,0 @@
-//
-// Created by Grant Limberg on 10/21/20.
-//
-
-#ifndef ZEROTIERANDROID_ZT_JNIARRAY_H
-#define ZEROTIERANDROID_ZT_JNIARRAY_H
-
-#include
-#include
-#include
-
-extern jclass java_util_ArrayList;
-extern jmethodID java_util_ArrayList_;
-extern jmethodID java_util_ArrayList_size;
-extern jmethodID java_util_ArrayList_get;
-extern jmethodID java_util_ArrayList_add;
-
-void InitListJNI(JNIEnv* env);
-
-class ListJNI {
-public:
- // Get the java class id of java.util.List.
- static jclass getListClass(JNIEnv* env);
-
- // Get the java class id of java.util.ArrayList.
- static jclass getArrayListClass(JNIEnv* env);
-
- // Get the java class id of java.util.Iterator.
- static jclass getIteratorClass(JNIEnv* env);
-
- // Get the java method id of java.util.List.iterator().
- static jmethodID getIteratorMethod(JNIEnv* env);
-
- // Get the java method id of java.util.Iterator.hasNext().
- static jmethodID getHasNextMethod(JNIEnv* env);
-
- // Get the java method id of java.util.Iterator.next().
- static jmethodID getNextMethod(JNIEnv* env);
-
- // Get the java method id of arrayList constructor.
- static jmethodID getArrayListConstructorMethodId(JNIEnv* env, jclass jclazz);
-
- // Get the java method id of java.util.List.add().
- static jmethodID getListAddMethodId(JNIEnv* env);
-};
-
-class ByteJNI {
-public:
- // Get the java class id of java.lang.Byte.
- static jclass getByteClass(JNIEnv* env);
-
- // Get the java method id of java.lang.Byte.byteValue.
- static jmethodID getByteValueMethod(JNIEnv* env);
-};
-
-jobject cppToJava(JNIEnv* env, std::vector vector);
-
-std::vector javaToCpp(JNIEnv* env, jobject arrayList);
-
-#endif //ZEROTIERANDROID_ZT_JNIARRAY_H
diff --git a/java/jni/ZT_jnicache.cpp b/java/jni/ZT_jnicache.cpp
new file mode 100644
index 000000000..c721a9ee1
--- /dev/null
+++ b/java/jni/ZT_jnicache.cpp
@@ -0,0 +1,236 @@
+//
+// Created by Brenton Bostick on 1/18/23.
+//
+
+#include "ZT_jnicache.h"
+
+#include "ZT_jniutils.h"
+
+#include
+
+#define LOG_TAG "Cache"
+
+#define EXCEPTIONANDNULLCHECK(var) \
+ do { \
+ if (env->ExceptionCheck()) { \
+ assert(false && "Exception"); \
+ } \
+ if ((var) == NULL) { \
+ assert(false && #var " is NULL"); \
+ } \
+ } while (false)
+
+#define SETCLASS(classVar, classNameString) \
+ do { \
+ jclass classVar ## _local = env->FindClass(classNameString); \
+ EXCEPTIONANDNULLCHECK(classVar ## _local); \
+ classVar = reinterpret_cast(env->NewGlobalRef(classVar ## _local)); \
+ EXCEPTIONANDNULLCHECK(classVar); \
+ env->DeleteLocalRef(classVar ## _local); \
+ } while (false)
+
+#define SETOBJECT(objectVar, code) \
+ do { \
+ jobject objectVar ## _local = code; \
+ EXCEPTIONANDNULLCHECK(objectVar ## _local); \
+ objectVar = env->NewGlobalRef(objectVar ## _local); \
+ EXCEPTIONANDNULLCHECK(objectVar); \
+ env->DeleteLocalRef(objectVar ## _local); \
+ } while (false)
+
+
+//
+// Classes
+//
+
+jclass ArrayList_class;
+jclass DataStoreGetListener_class;
+jclass DataStorePutListener_class;
+jclass EventListener_class;
+jclass Event_class;
+jclass Inet4Address_class;
+jclass Inet6Address_class;
+jclass InetAddress_class;
+jclass InetSocketAddress_class;
+jclass NodeStatus_class;
+jclass Node_class;
+jclass PacketSender_class;
+jclass PathChecker_class;
+jclass PeerPhysicalPath_class;
+jclass PeerRole_class;
+jclass Peer_class;
+jclass ResultCode_class;
+jclass Version_class;
+jclass VirtualNetworkConfigListener_class;
+jclass VirtualNetworkConfigOperation_class;
+jclass VirtualNetworkConfig_class;
+jclass VirtualNetworkDNS_class;
+jclass VirtualNetworkFrameListener_class;
+jclass VirtualNetworkRoute_class;
+jclass VirtualNetworkStatus_class;
+jclass VirtualNetworkType_class;
+
+//
+// Instance methods
+//
+
+jmethodID ArrayList_add_method;
+jmethodID ArrayList_ctor;
+jmethodID DataStoreGetListener_onDataStoreGet_method;
+jmethodID DataStorePutListener_onDataStorePut_method;
+jmethodID DataStorePutListener_onDelete_method;
+jmethodID EventListener_onEvent_method;
+jmethodID EventListener_onTrace_method;
+jmethodID InetAddress_getAddress_method;
+jmethodID InetSocketAddress_ctor;
+jmethodID InetSocketAddress_getAddress_method;
+jmethodID InetSocketAddress_getPort_method;
+jmethodID NodeStatus_ctor;
+jmethodID PacketSender_onSendPacketRequested_method;
+jmethodID PathChecker_onPathCheck_method;
+jmethodID PathChecker_onPathLookup_method;
+jmethodID PeerPhysicalPath_ctor;
+jmethodID Peer_ctor;
+jmethodID Version_ctor;
+jmethodID VirtualNetworkConfigListener_onNetworkConfigurationUpdated_method;
+jmethodID VirtualNetworkConfig_ctor;
+jmethodID VirtualNetworkDNS_ctor;
+jmethodID VirtualNetworkFrameListener_onVirtualNetworkFrame_method;
+jmethodID VirtualNetworkRoute_ctor;
+
+//
+// Static methods
+//
+
+jmethodID Event_fromInt_method;
+jmethodID InetAddress_getByAddress_method;
+jmethodID PeerRole_fromInt_method;
+jmethodID ResultCode_fromInt_method;
+jmethodID VirtualNetworkConfigOperation_fromInt_method;
+jmethodID VirtualNetworkStatus_fromInt_method;
+jmethodID VirtualNetworkType_fromInt_method;
+
+//
+// Enums
+//
+
+jobject ResultCode_RESULT_FATAL_ERROR_INTERNAL_enum;
+jobject ResultCode_RESULT_OK_enum;
+
+void setupJNICache(JavaVM *vm) {
+
+ JNIEnv *env;
+ GETENV(env, vm);
+
+ //
+ // Classes
+ //
+
+ SETCLASS(ArrayList_class, "java/util/ArrayList");
+ SETCLASS(DataStoreGetListener_class, "com/zerotier/sdk/DataStoreGetListener");
+ SETCLASS(DataStorePutListener_class, "com/zerotier/sdk/DataStorePutListener");
+ SETCLASS(EventListener_class, "com/zerotier/sdk/EventListener");
+ SETCLASS(Event_class, "com/zerotier/sdk/Event");
+ SETCLASS(Inet4Address_class, "java/net/Inet4Address");
+ SETCLASS(Inet6Address_class, "java/net/Inet6Address");
+ SETCLASS(InetAddress_class, "java/net/InetAddress");
+ SETCLASS(InetSocketAddress_class, "java/net/InetSocketAddress");
+ SETCLASS(NodeStatus_class, "com/zerotier/sdk/NodeStatus");
+ SETCLASS(Node_class, "com/zerotier/sdk/Node");
+ SETCLASS(PacketSender_class, "com/zerotier/sdk/PacketSender");
+ SETCLASS(PathChecker_class, "com/zerotier/sdk/PathChecker");
+ SETCLASS(PeerPhysicalPath_class, "com/zerotier/sdk/PeerPhysicalPath");
+ SETCLASS(PeerRole_class, "com/zerotier/sdk/PeerRole");
+ SETCLASS(Peer_class, "com/zerotier/sdk/Peer");
+ SETCLASS(ResultCode_class, "com/zerotier/sdk/ResultCode");
+ SETCLASS(Version_class, "com/zerotier/sdk/Version");
+ SETCLASS(VirtualNetworkConfigListener_class, "com/zerotier/sdk/VirtualNetworkConfigListener");
+ SETCLASS(VirtualNetworkConfigOperation_class, "com/zerotier/sdk/VirtualNetworkConfigOperation");
+ SETCLASS(VirtualNetworkConfig_class, "com/zerotier/sdk/VirtualNetworkConfig");
+ SETCLASS(VirtualNetworkDNS_class, "com/zerotier/sdk/VirtualNetworkDNS");
+ SETCLASS(VirtualNetworkFrameListener_class, "com/zerotier/sdk/VirtualNetworkFrameListener");
+ SETCLASS(VirtualNetworkRoute_class, "com/zerotier/sdk/VirtualNetworkRoute");
+ SETCLASS(VirtualNetworkStatus_class, "com/zerotier/sdk/VirtualNetworkStatus");
+ SETCLASS(VirtualNetworkType_class, "com/zerotier/sdk/VirtualNetworkType");
+
+ //
+ // Instance methods
+ //
+
+ EXCEPTIONANDNULLCHECK(ArrayList_add_method = env->GetMethodID(ArrayList_class, "add", "(Ljava/lang/Object;)Z"));
+ EXCEPTIONANDNULLCHECK(ArrayList_ctor = env->GetMethodID(ArrayList_class, "", "(I)V"));
+ EXCEPTIONANDNULLCHECK(DataStoreGetListener_onDataStoreGet_method = env->GetMethodID(DataStoreGetListener_class, "onDataStoreGet", "(Ljava/lang/String;[B)J"));
+ EXCEPTIONANDNULLCHECK(DataStorePutListener_onDataStorePut_method = env->GetMethodID(DataStorePutListener_class, "onDataStorePut", "(Ljava/lang/String;[BZ)I"));
+ EXCEPTIONANDNULLCHECK(DataStorePutListener_onDelete_method = env->GetMethodID(DataStorePutListener_class, "onDelete", "(Ljava/lang/String;)I"));
+ EXCEPTIONANDNULLCHECK(EventListener_onEvent_method = env->GetMethodID(EventListener_class, "onEvent", "(Lcom/zerotier/sdk/Event;)V"));
+ EXCEPTIONANDNULLCHECK(EventListener_onTrace_method = env->GetMethodID(EventListener_class, "onTrace", "(Ljava/lang/String;)V"));
+ EXCEPTIONANDNULLCHECK(InetAddress_getAddress_method = env->GetMethodID(InetAddress_class, "getAddress", "()[B"));
+ EXCEPTIONANDNULLCHECK(InetSocketAddress_ctor = env->GetMethodID(InetSocketAddress_class, "", "(Ljava/net/InetAddress;I)V"));
+ EXCEPTIONANDNULLCHECK(InetSocketAddress_getAddress_method = env->GetMethodID(InetSocketAddress_class, "getAddress", "()Ljava/net/InetAddress;"));
+ EXCEPTIONANDNULLCHECK(InetSocketAddress_getPort_method = env->GetMethodID(InetSocketAddress_class, "getPort", "()I"));
+ EXCEPTIONANDNULLCHECK(NodeStatus_ctor = env->GetMethodID(NodeStatus_class, "", "(JLjava/lang/String;Ljava/lang/String;Z)V"));
+ EXCEPTIONANDNULLCHECK(PacketSender_onSendPacketRequested_method = env->GetMethodID(PacketSender_class, "onSendPacketRequested", "(JLjava/net/InetSocketAddress;[BI)I"));
+ EXCEPTIONANDNULLCHECK(PathChecker_onPathCheck_method = env->GetMethodID(PathChecker_class, "onPathCheck", "(JJLjava/net/InetSocketAddress;)Z"));
+ EXCEPTIONANDNULLCHECK(PathChecker_onPathLookup_method = env->GetMethodID(PathChecker_class, "onPathLookup", "(JI)Ljava/net/InetSocketAddress;"));
+ EXCEPTIONANDNULLCHECK(PeerPhysicalPath_ctor = env->GetMethodID(PeerPhysicalPath_class, "", "(Ljava/net/InetSocketAddress;JJZ)V"));
+ EXCEPTIONANDNULLCHECK(Peer_ctor = env->GetMethodID(Peer_class, "", "(JIIIILcom/zerotier/sdk/PeerRole;[Lcom/zerotier/sdk/PeerPhysicalPath;)V"));
+ EXCEPTIONANDNULLCHECK(Version_ctor = env->GetMethodID(Version_class, "", "(III)V"));
+ EXCEPTIONANDNULLCHECK(VirtualNetworkConfigListener_onNetworkConfigurationUpdated_method = env->GetMethodID(VirtualNetworkConfigListener_class, "onNetworkConfigurationUpdated", "(JLcom/zerotier/sdk/VirtualNetworkConfigOperation;Lcom/zerotier/sdk/VirtualNetworkConfig;)I"));
+ EXCEPTIONANDNULLCHECK(VirtualNetworkConfig_ctor = env->GetMethodID(VirtualNetworkConfig_class, "", "(JJLjava/lang/String;Lcom/zerotier/sdk/VirtualNetworkStatus;Lcom/zerotier/sdk/VirtualNetworkType;IZZZIJ[Ljava/net/InetSocketAddress;[Lcom/zerotier/sdk/VirtualNetworkRoute;Lcom/zerotier/sdk/VirtualNetworkDNS;)V"));
+ EXCEPTIONANDNULLCHECK(VirtualNetworkDNS_ctor = env->GetMethodID(VirtualNetworkDNS_class, "", "(Ljava/lang/String;Ljava/util/ArrayList;)V"));
+ EXCEPTIONANDNULLCHECK(VirtualNetworkFrameListener_onVirtualNetworkFrame_method = env->GetMethodID(VirtualNetworkFrameListener_class, "onVirtualNetworkFrame", "(JJJJJ[B)V"));
+ EXCEPTIONANDNULLCHECK(VirtualNetworkRoute_ctor = env->GetMethodID(VirtualNetworkRoute_class, "", "(Ljava/net/InetSocketAddress;Ljava/net/InetSocketAddress;II)V"));
+
+ //
+ // Static methods
+ //
+
+ EXCEPTIONANDNULLCHECK(Event_fromInt_method = env->GetStaticMethodID(Event_class, "fromInt", "(I)Lcom/zerotier/sdk/Event;"));
+ EXCEPTIONANDNULLCHECK(InetAddress_getByAddress_method = env->GetStaticMethodID(InetAddress_class, "getByAddress", "([B)Ljava/net/InetAddress;"));
+ EXCEPTIONANDNULLCHECK(PeerRole_fromInt_method = env->GetStaticMethodID(PeerRole_class, "fromInt", "(I)Lcom/zerotier/sdk/PeerRole;"));
+ EXCEPTIONANDNULLCHECK(ResultCode_fromInt_method = env->GetStaticMethodID(ResultCode_class, "fromInt", "(I)Lcom/zerotier/sdk/ResultCode;"));
+ EXCEPTIONANDNULLCHECK(VirtualNetworkConfigOperation_fromInt_method = env->GetStaticMethodID(VirtualNetworkConfigOperation_class, "fromInt", "(I)Lcom/zerotier/sdk/VirtualNetworkConfigOperation;"));
+ EXCEPTIONANDNULLCHECK(VirtualNetworkStatus_fromInt_method = env->GetStaticMethodID(VirtualNetworkStatus_class, "fromInt", "(I)Lcom/zerotier/sdk/VirtualNetworkStatus;"));
+ EXCEPTIONANDNULLCHECK(VirtualNetworkType_fromInt_method = env->GetStaticMethodID(VirtualNetworkType_class, "fromInt", "(I)Lcom/zerotier/sdk/VirtualNetworkType;"));
+
+ //
+ // Enums
+ //
+
+ SETOBJECT(ResultCode_RESULT_FATAL_ERROR_INTERNAL_enum, createResultObject(env, ZT_RESULT_FATAL_ERROR_INTERNAL));
+ SETOBJECT(ResultCode_RESULT_OK_enum, createResultObject(env, ZT_RESULT_OK));
+}
+
+void teardownJNICache(JavaVM *vm) {
+
+ JNIEnv *env;
+ GETENV(env, vm);
+
+ env->DeleteGlobalRef(ArrayList_class);
+ env->DeleteGlobalRef(DataStoreGetListener_class);
+ env->DeleteGlobalRef(DataStorePutListener_class);
+ env->DeleteGlobalRef(EventListener_class);
+ env->DeleteGlobalRef(Event_class);
+ env->DeleteGlobalRef(InetAddress_class);
+ env->DeleteGlobalRef(InetSocketAddress_class);
+ env->DeleteGlobalRef(NodeStatus_class);
+ env->DeleteGlobalRef(Node_class);
+ env->DeleteGlobalRef(PacketSender_class);
+ env->DeleteGlobalRef(PathChecker_class);
+ env->DeleteGlobalRef(PeerPhysicalPath_class);
+ env->DeleteGlobalRef(PeerRole_class);
+ env->DeleteGlobalRef(Peer_class);
+ env->DeleteGlobalRef(ResultCode_class);
+ env->DeleteGlobalRef(Version_class);
+ env->DeleteGlobalRef(VirtualNetworkConfigListener_class);
+ env->DeleteGlobalRef(VirtualNetworkConfigOperation_class);
+ env->DeleteGlobalRef(VirtualNetworkConfig_class);
+ env->DeleteGlobalRef(VirtualNetworkDNS_class);
+ env->DeleteGlobalRef(VirtualNetworkFrameListener_class);
+ env->DeleteGlobalRef(VirtualNetworkRoute_class);
+ env->DeleteGlobalRef(VirtualNetworkStatus_class);
+ env->DeleteGlobalRef(VirtualNetworkType_class);
+
+ env->DeleteGlobalRef(ResultCode_RESULT_FATAL_ERROR_INTERNAL_enum);
+ env->DeleteGlobalRef(ResultCode_RESULT_OK_enum);
+}
diff --git a/java/jni/ZT_jnicache.h b/java/jni/ZT_jnicache.h
new file mode 100644
index 000000000..c5cc9cb2f
--- /dev/null
+++ b/java/jni/ZT_jnicache.h
@@ -0,0 +1,92 @@
+//
+// Created by Brenton Bostick on 1/18/23.
+//
+
+#ifndef ZEROTIERANDROID_JNICACHE_H
+#define ZEROTIERANDROID_JNICACHE_H
+
+#include
+
+
+//
+// Classes
+//
+
+extern jclass ArrayList_class;
+extern jclass DataStoreGetListener_class;
+extern jclass DataStorePutListener_class;
+extern jclass EventListener_class;
+extern jclass Event_class;
+extern jclass Inet4Address_class;
+extern jclass Inet6Address_class;
+extern jclass InetAddress_class;
+extern jclass InetSocketAddress_class;
+extern jclass NodeStatus_class;
+extern jclass Node_class;
+extern jclass PacketSender_class;
+extern jclass PathChecker_class;
+extern jclass PeerPhysicalPath_class;
+extern jclass PeerRole_class;
+extern jclass Peer_class;
+extern jclass ResultCode_class;
+extern jclass Version_class;
+extern jclass VirtualNetworkConfigListener_class;
+extern jclass VirtualNetworkConfigOperation_class;
+extern jclass VirtualNetworkConfig_class;
+extern jclass VirtualNetworkDNS_class;
+extern jclass VirtualNetworkFrameListener_class;
+extern jclass VirtualNetworkRoute_class;
+extern jclass VirtualNetworkStatus_class;
+extern jclass VirtualNetworkType_class;
+
+//
+// Instance methods
+//
+
+extern jmethodID ArrayList_add_method;
+extern jmethodID ArrayList_ctor;
+extern jmethodID DataStoreGetListener_onDataStoreGet_method;
+extern jmethodID DataStorePutListener_onDataStorePut_method;
+extern jmethodID DataStorePutListener_onDelete_method;
+extern jmethodID EventListener_onEvent_method;
+extern jmethodID EventListener_onTrace_method;
+extern jmethodID InetAddress_getAddress_method;
+extern jmethodID InetSocketAddress_ctor;
+extern jmethodID InetSocketAddress_getAddress_method;
+extern jmethodID InetSocketAddress_getPort_method;
+extern jmethodID NodeStatus_ctor;
+extern jmethodID PacketSender_onSendPacketRequested_method;
+extern jmethodID PathChecker_onPathCheck_method;
+extern jmethodID PathChecker_onPathLookup_method;
+extern jmethodID PeerPhysicalPath_ctor;
+extern jmethodID Peer_ctor;
+extern jmethodID Version_ctor;
+extern jmethodID VirtualNetworkConfigListener_onNetworkConfigurationUpdated_method;
+extern jmethodID VirtualNetworkConfig_ctor;
+extern jmethodID VirtualNetworkDNS_ctor;
+extern jmethodID VirtualNetworkFrameListener_onVirtualNetworkFrame_method;
+extern jmethodID VirtualNetworkRoute_ctor;
+
+//
+// Static methods
+//
+
+extern jmethodID Event_fromInt_method;
+extern jmethodID InetAddress_getByAddress_method;
+extern jmethodID PeerRole_fromInt_method;
+extern jmethodID ResultCode_fromInt_method;
+extern jmethodID VirtualNetworkConfigOperation_fromInt_method;
+extern jmethodID VirtualNetworkStatus_fromInt_method;
+extern jmethodID VirtualNetworkType_fromInt_method;
+
+//
+// Enums
+//
+
+extern jobject ResultCode_RESULT_FATAL_ERROR_INTERNAL_enum;
+extern jobject ResultCode_RESULT_OK_enum;
+
+void setupJNICache(JavaVM *vm);
+void teardownJNICache(JavaVM *vm);
+
+#endif // ZEROTIERANDROID_JNICACHE_H
diff --git a/java/jni/ZT_jnilookup.cpp b/java/jni/ZT_jnilookup.cpp
deleted file mode 100644
index 4d867a35c..000000000
--- a/java/jni/ZT_jnilookup.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * ZeroTier One - Network Virtualization Everywhere
- * Copyright (C) 2011-2015 ZeroTier, Inc.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- *
- * --
- *
- * ZeroTier may be used and distributed under the terms of the GPLv3, which
- * are available at: http://www.gnu.org/licenses/gpl-3.0.html
- *
- * If you would like to embed ZeroTier into a commercial application or
- * redistribute it in a modified binary form, please contact ZeroTier Networks
- * LLC. Start here: http://www.zerotier.com/
- */
-
-#include "ZT_jnilookup.h"
-#include "ZT_jniutils.h"
-
-JniLookup::JniLookup()
- : m_jvm(NULL)
-{
- LOGV("JNI Cache Created");
-}
-
-JniLookup::JniLookup(JavaVM *jvm)
- : m_jvm(jvm)
-{
- LOGV("JNI Cache Created");
-}
-
-JniLookup::~JniLookup()
-{
- LOGV("JNI Cache Destroyed");
-}
-
-
-void JniLookup::setJavaVM(JavaVM *jvm)
-{
- LOGV("Assigned JVM to object");
- m_jvm = jvm;
-}
-
-
-jclass JniLookup::findClass(const std::string &name)
-{
- if(!m_jvm)
- return NULL;
-
- // get the class from the JVM
- JNIEnv *env = NULL;
- if(m_jvm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)
- {
- LOGE("Error retrieving JNI Environment");
- return NULL;
- }
- const char *c = name.c_str();
- jclass cls = env->FindClass(c);
- if(env->ExceptionCheck())
- {
- LOGE("Error finding class: %s", name.c_str());
- return NULL;
- }
-
- return cls;
-}
-
-
-jmethodID JniLookup::findMethod(jclass cls, const std::string &methodName, const std::string &methodSig)
-{
- if(!m_jvm)
- return NULL;
-
- JNIEnv *env = NULL;
- if(m_jvm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)
- {
- return NULL;
- }
-
- jmethodID mid = env->GetMethodID(cls, methodName.c_str(), methodSig.c_str());
- if(env->ExceptionCheck())
- {
- return NULL;
- }
-
- return mid;
-}
-
-jmethodID JniLookup::findStaticMethod(jclass cls, const std::string &methodName, const std::string &methodSig)
-{
- if(!m_jvm)
- return NULL;
-
- JNIEnv *env = NULL;
- if(m_jvm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)
- {
- return NULL;
- }
-
- jmethodID mid = env->GetStaticMethodID(cls, methodName.c_str(), methodSig.c_str());
- if(env->ExceptionCheck())
- {
- return NULL;
- }
-
- return mid;
-}
-
-jfieldID JniLookup::findField(jclass cls, const std::string &fieldName, const std::string &typeStr)
-{
- if(!m_jvm)
- return NULL;
-
- JNIEnv *env = NULL;
- if(m_jvm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)
- {
- return NULL;
- }
-
- jfieldID fid = env->GetFieldID(cls, fieldName.c_str(), typeStr.c_str());
- if(env->ExceptionCheck())
- {
- return NULL;
- }
-
- return fid;
-}
-
-jfieldID JniLookup::findStaticField(jclass cls, const std::string &fieldName, const std::string &typeStr)
-{
- if(!m_jvm)
- return NULL;
-
- JNIEnv *env = NULL;
- if(m_jvm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)
- {
- return NULL;
- }
-
- jfieldID fid = env->GetStaticFieldID(cls, fieldName.c_str(), typeStr.c_str());
- if(env->ExceptionCheck())
- {
- return NULL;
- }
-
- return fid;
-}
\ No newline at end of file
diff --git a/java/jni/ZT_jnilookup.h b/java/jni/ZT_jnilookup.h
deleted file mode 100644
index f5bd97d7d..000000000
--- a/java/jni/ZT_jnilookup.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * ZeroTier One - Network Virtualization Everywhere
- * Copyright (C) 2011-2015 ZeroTier, Inc.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- *
- * --
- *
- * ZeroTier may be used and distributed under the terms of the GPLv3, which
- * are available at: http://www.gnu.org/licenses/gpl-3.0.html
- *
- * If you would like to embed ZeroTier into a commercial application or
- * redistribute it in a modified binary form, please contact ZeroTier Networks
- * LLC. Start here: http://www.zerotier.com/
- */
-
-#ifndef ZT_JNILOOKUP_H_
-#define ZT_JNILOOKUP_H_
-
-#include
-#include
*/
- EVENT_DOWN,
+ EVENT_DOWN(3),
/**
* Your identity has collided with another node's ZeroTier address
@@ -85,7 +91,7 @@ public enum Event {
* condition is a good way to make sure it never arises. It's like how
* umbrellas prevent rain and smoke detectors prevent fires. They do, right?
*/
- EVENT_FATAL_ERROR_IDENTITY_COLLISION,
+ EVENT_FATAL_ERROR_IDENTITY_COLLISION(4),
/**
* Trace (debugging) message
@@ -94,5 +100,55 @@ public enum Event {
*
* Meta-data: {@link String}, TRACE message
*/
- EVENT_TRACE
-}
\ No newline at end of file
+ EVENT_TRACE(5),
+
+ /**
+ * VERB_USER_MESSAGE received
+ *
+ * These are generated when a VERB_USER_MESSAGE packet is received via
+ * ZeroTier VL1.
+ */
+ EVENT_USER_MESSAGE(6),
+
+ /**
+ * Remote trace received
+ *
+ * These are generated when a VERB_REMOTE_TRACE is received. Note
+ * that any node can fling one of these at us. It is your responsibility
+ * to filter and determine if it's worth paying attention to. If it's
+ * not just drop it. Most nodes that are not active controllers ignore
+ * these, and controllers only save them if they pertain to networks
+ * with remote tracing enabled.
+ */
+ EVENT_REMOTE_TRACE(7);
+
+ @SuppressWarnings({"FieldCanBeLocal", "unused"})
+ private final int id;
+
+ Event(int id) {
+ this.id = id;
+ }
+
+ public static Event fromInt(int id) {
+ switch (id) {
+ case 0:
+ return EVENT_UP;
+ case 1:
+ return EVENT_OFFLINE;
+ case 2:
+ return EVENT_ONLINE;
+ case 3:
+ return EVENT_DOWN;
+ case 4:
+ return EVENT_FATAL_ERROR_IDENTITY_COLLISION;
+ case 5:
+ return EVENT_TRACE;
+ case 6:
+ return EVENT_USER_MESSAGE;
+ case 7:
+ return EVENT_REMOTE_TRACE;
+ default:
+ throw new RuntimeException("Unhandled value: " + id);
+ }
+ }
+}
diff --git a/java/src/com/zerotier/sdk/EventListener.java b/java/src/com/zerotier/sdk/EventListener.java
index 91050aaa9..88fb8afc3 100644
--- a/java/src/com/zerotier/sdk/EventListener.java
+++ b/java/src/com/zerotier/sdk/EventListener.java
@@ -27,19 +27,17 @@
package com.zerotier.sdk;
-import java.net.InetSocketAddress;
-import java.lang.String;
-
/**
* Interface to handle callbacks for ZeroTier One events.
*/
public interface EventListener {
+
/**
* Callback for events with no other associated metadata
*
* @param event {@link Event} enum
*/
- public void onEvent(Event event);
+ void onEvent(Event event);
/**
* Trace messages
@@ -48,5 +46,5 @@ public interface EventListener {
*
* @param message the trace message
*/
- public void onTrace(String message);
+ void onTrace(String message);
}
diff --git a/java/src/com/zerotier/sdk/NativeUtils.java b/java/src/com/zerotier/sdk/NativeUtils.java
deleted file mode 100644
index 4932a6c71..000000000
--- a/java/src/com/zerotier/sdk/NativeUtils.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package com.zerotier.sdk;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * Simple library class for working with JNI (Java Native Interface)
- *
- * @see http://adamheinrich.com/2012/how-to-load-native-jni-library-from-jar
- *
- * @author Adam Heirnich , http://www.adamh.cz
- */
-public class NativeUtils {
-
- /**
- * Private constructor - this class will never be instanced
- */
- private NativeUtils() {
- }
-
- /**
- * Loads library from current JAR archive
- *
- * The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after exiting.
- * Method uses String as filename because the pathname is "abstract", not system-dependent.
- *
- * @param filename The filename inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext
- * @throws IOException If temporary file creation or read/write operation fails
- * @throws IllegalArgumentException If source file (param path) does not exist
- * @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters (restriction of {@see File#createTempFile(java.lang.String, java.lang.String)}).
- */
- public static void loadLibraryFromJar(String path) throws IOException {
-
- if (!path.startsWith("/")) {
- throw new IllegalArgumentException("The path has to be absolute (start with '/').");
- }
-
- // Obtain filename from path
- String[] parts = path.split("/");
- String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
-
- // Split filename to prefix and suffix (extension)
- String prefix = "";
- String suffix = null;
- if (filename != null) {
- parts = filename.split("\\.", 2);
- prefix = parts[0];
- suffix = (parts.length > 1) ? "."+parts[parts.length - 1] : null; // Thanks, davs! :-)
- }
-
- // Check if the filename is okay
- if (filename == null || prefix.length() < 3) {
- throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
- }
-
- // Prepare temporary file
- File temp = File.createTempFile(prefix, suffix);
- temp.deleteOnExit();
-
- if (!temp.exists()) {
- throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist.");
- }
-
- // Prepare buffer for data copying
- byte[] buffer = new byte[1024];
- int readBytes;
-
- // Open and check input stream
- InputStream is = NativeUtils.class.getResourceAsStream(path);
- if (is == null) {
- throw new FileNotFoundException("File " + path + " was not found inside JAR.");
- }
-
- // Open output stream and copy data between source file in JAR and the temporary file
- OutputStream os = new FileOutputStream(temp);
- try {
- while ((readBytes = is.read(buffer)) != -1) {
- os.write(buffer, 0, readBytes);
- }
- } finally {
- // If read/write fails, close streams safely before throwing an exception
- os.close();
- is.close();
- }
-
- // Finally, load the library
- System.load(temp.getAbsolutePath());
- }
-}
\ No newline at end of file
diff --git a/java/src/com/zerotier/sdk/Node.java b/java/src/com/zerotier/sdk/Node.java
index 1b3a4901f..a3f3ab470 100644
--- a/java/src/com/zerotier/sdk/Node.java
+++ b/java/src/com/zerotier/sdk/Node.java
@@ -28,95 +28,72 @@
package com.zerotier.sdk;
import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.io.IOException;
/**
* A ZeroTier One node
*/
public class Node {
- static {
- try {
- System.loadLibrary("ZeroTierOneJNI");
- } catch (UnsatisfiedLinkError e) {
- try {
- if(System.getProperty("os.name").startsWith("Windows")) {
- System.out.println("Arch: " + System.getProperty("sun.arch.data.model"));
- if(System.getProperty("sun.arch.data.model").equals("64")) {
- NativeUtils.loadLibraryFromJar("/lib/ZeroTierOneJNI_win64.dll");
- } else {
- NativeUtils.loadLibraryFromJar("/lib/ZeroTierOneJNI_win32.dll");
- }
- } else if(System.getProperty("os.name").startsWith("Mac")) {
- NativeUtils.loadLibraryFromJar("/lib/libZeroTierOneJNI.jnilib");
- } else {
- // TODO: Linux
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }
+ static {
+ System.loadLibrary("ZeroTierOneJNI");
+ }
private static final String TAG = "NODE";
/**
* Node ID for JNI purposes.
* Currently set to the now value passed in at the constructor
- *
- * -1 if the node has already been closed
*/
- private long nodeId;
-
- private final DataStoreGetListener getListener;
- private final DataStorePutListener putListener;
- private final PacketSender sender;
- private final EventListener eventListener;
- private final VirtualNetworkFrameListener frameListener;
- private final VirtualNetworkConfigListener configListener;
- private final PathChecker pathChecker;
+ private final long nodeId;
/**
* Create a new ZeroTier One node
*
+ * @param now Current clock in milliseconds
+ */
+ public Node(long now) {
+ this.nodeId = now;
+ }
+
+ /**
+ * Init a new ZeroTier One node
+ *
* Note that this can take a few seconds the first time it's called, as it
* will generate an identity.
*
- * @param now Current clock in milliseconds
* @param getListener User written instance of the {@link DataStoreGetListener} interface called to get objects from persistent storage. This instance must be unique per Node object.
* @param putListener User written instance of the {@link DataStorePutListener} interface called to put objects in persistent storage. This instance must be unique per Node object.
- * @param sender
+ * @param sender User written instance of the {@link PacketSender} interface to send ZeroTier packets out over the wire.
* @param eventListener User written instance of the {@link EventListener} interface to receive status updates and non-fatal error notices. This instance must be unique per Node object.
- * @param frameListener
+ * @param frameListener User written instance of the {@link VirtualNetworkFrameListener} interface to send a frame out to a virtual network port.
* @param configListener User written instance of the {@link VirtualNetworkConfigListener} interface to be called when virtual LANs are created, deleted, or their config parameters change. This instance must be unique per Node object.
* @param pathChecker User written instance of the {@link PathChecker} interface. Not required and can be null.
*/
- public Node(long now,
- DataStoreGetListener getListener,
- DataStorePutListener putListener,
- PacketSender sender,
- EventListener eventListener,
- VirtualNetworkFrameListener frameListener,
- VirtualNetworkConfigListener configListener,
- PathChecker pathChecker) throws NodeException
- {
- this.nodeId = now;
-
- this.getListener = getListener;
- this.putListener = putListener;
- this.sender = sender;
- this.eventListener = eventListener;
- this.frameListener = frameListener;
- this.configListener = configListener;
- this.pathChecker = pathChecker;
-
- ResultCode rc = node_init(now);
- if(rc != ResultCode.RESULT_OK)
- {
- // TODO: Throw Exception
+ public ResultCode init(
+ DataStoreGetListener getListener,
+ DataStorePutListener putListener,
+ PacketSender sender,
+ EventListener eventListener,
+ VirtualNetworkFrameListener frameListener,
+ VirtualNetworkConfigListener configListener,
+ PathChecker pathChecker) throws NodeException {
+ ResultCode rc = node_init(
+ nodeId,
+ getListener,
+ putListener,
+ sender,
+ eventListener,
+ frameListener,
+ configListener,
+ pathChecker);
+ if(rc != ResultCode.RESULT_OK) {
throw new NodeException(rc.toString());
}
- }
+ return rc;
+ }
+
+ public boolean isInited() {
+ return node_isInited(nodeId);
+ }
/**
* Close this Node.
@@ -124,15 +101,12 @@ public class Node {
* The Node object can no longer be used once this method is called.
*/
public void close() {
- if(nodeId != -1) {
- node_delete(nodeId);
- nodeId = -1;
- }
+ node_delete(nodeId);
}
@Override
- protected void finalize() {
- close();
+ public String toString() {
+ return "Node(" + nodeId + ")";
}
/**
@@ -166,6 +140,7 @@ public class Node {
* Process a packet received from the physical wire
*
* @param now Current clock in milliseconds
+ * @param localSocket Local socket or -1
* @param remoteAddress Origin of packet
* @param packetData Packet data
* @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks()
@@ -392,8 +367,8 @@ public class Node {
*
* @return List of networks or NULL on failure
*/
- public VirtualNetworkConfig[] networks() {
- return networks(nodeId);
+ public VirtualNetworkConfig[] networkConfigs() {
+ return networkConfigs(nodeId);
}
/**
@@ -408,7 +383,17 @@ public class Node {
//
// function declarations for JNI
//
- private native ResultCode node_init(long now);
+ private native ResultCode node_init(
+ long nodeId,
+ DataStoreGetListener dataStoreGetListener,
+ DataStorePutListener dataStorePutListener,
+ PacketSender packetSender,
+ EventListener eventListener,
+ VirtualNetworkFrameListener virtualNetworkFrameListener,
+ VirtualNetworkConfigListener virtualNetworkConfigListener,
+ PathChecker pathChecker);
+
+ private native boolean node_isInited(long nodeId);
private native void node_delete(long nodeId);
@@ -471,5 +456,5 @@ public class Node {
private native Peer[] peers(long nodeId);
- private native VirtualNetworkConfig[] networks(long nodeId);
-}
\ No newline at end of file
+ private native VirtualNetworkConfig[] networkConfigs(long nodeId);
+}
diff --git a/java/src/com/zerotier/sdk/NodeException.java b/java/src/com/zerotier/sdk/NodeException.java
index 1fdef72f8..beeb06063 100644
--- a/java/src/com/zerotier/sdk/NodeException.java
+++ b/java/src/com/zerotier/sdk/NodeException.java
@@ -27,10 +27,11 @@
package com.zerotier.sdk;
-import java.lang.RuntimeException;
+public class NodeException extends Exception {
-public class NodeException extends RuntimeException {
+ private static final long serialVersionUID = 6268040509883125819L;
+
public NodeException(String message) {
super(message);
}
-}
\ No newline at end of file
+}
diff --git a/java/src/com/zerotier/sdk/NodeStatus.java b/java/src/com/zerotier/sdk/NodeStatus.java
index 11e49ade1..1172650b1 100644
--- a/java/src/com/zerotier/sdk/NodeStatus.java
+++ b/java/src/com/zerotier/sdk/NodeStatus.java
@@ -27,43 +27,64 @@
package com.zerotier.sdk;
-public final class NodeStatus {
- private long address;
- private String publicIdentity;
- private String secretIdentity;
- private boolean online;
+import com.zerotier.sdk.util.StringUtils;
- private NodeStatus() {}
+/**
+ * Current node status
+ *
+ * Defined in ZeroTierOne.h as ZT_NodeStatus
+ */
+public class NodeStatus {
+
+ private final long address;
+
+ private final String publicIdentity;
+
+ private final String secretIdentity;
+
+ private final boolean online;
+
+ public NodeStatus(long address, String publicIdentity, String secretIdentity, boolean online) {
+ this.address = address;
+ this.publicIdentity = publicIdentity;
+ this.secretIdentity = secretIdentity;
+ this.online = online;
+ }
+
+ @Override
+ public String toString() {
+ return "NodeStatus(" + StringUtils.addressToString(address) + ", " + publicIdentity + ", " + secretIdentity + ", " + online + ")";
+ }
/**
* 40-bit ZeroTier address of this node
*/
- public final long getAddress() {
- return address;
- }
+ public long getAddress() {
+ return address;
+ }
/**
* Public identity in string-serialized form (safe to send to others)
*
* This identity will remain valid as long as the node exists.
*/
- public final String getPublicIdentity() {
- return publicIdentity;
- }
+ public String getPublicIdentity() {
+ return publicIdentity;
+ }
/**
* Full identity including secret key in string-serialized form
*
* This identity will remain valid as long as the node exists.
*/
- public final String getSecretIdentity() {
- return secretIdentity;
- }
+ public String getSecretIdentity() {
+ return secretIdentity;
+ }
/**
* True if some kind of connectivity appears available
*/
- public final boolean isOnline() {
- return online;
- }
-}
\ No newline at end of file
+ public boolean isOnline() {
+ return online;
+ }
+}
diff --git a/java/src/com/zerotier/sdk/PacketSender.java b/java/src/com/zerotier/sdk/PacketSender.java
index 06ec01bcc..893824a08 100644
--- a/java/src/com/zerotier/sdk/PacketSender.java
+++ b/java/src/com/zerotier/sdk/PacketSender.java
@@ -24,12 +24,14 @@
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
+
package com.zerotier.sdk;
import java.net.InetSocketAddress;
public interface PacketSender {
+
/**
* Function to send a ZeroTier packet out over the wire
*
@@ -40,9 +42,10 @@ public interface PacketSender {
* @param localSocket socket file descriptor to send from. Set to -1 if not specified.
* @param remoteAddr {@link InetSocketAddress} to send to
* @param packetData data to send
+ * @param ttl TTL is ignored
* @return 0 on success, any error code on failure.
*/
- public int onSendPacketRequested(
+ int onSendPacketRequested(
long localSocket,
InetSocketAddress remoteAddr,
byte[] packetData,
diff --git a/java/src/com/zerotier/sdk/PathChecker.java b/java/src/com/zerotier/sdk/PathChecker.java
index 6bf31df2b..cfc97d60e 100644
--- a/java/src/com/zerotier/sdk/PathChecker.java
+++ b/java/src/com/zerotier/sdk/PathChecker.java
@@ -8,6 +8,7 @@ package com.zerotier.sdk;
import java.net.InetSocketAddress;
public interface PathChecker {
+
/**
* Callback to check whether a path should be used for ZeroTier traffic
*
@@ -28,6 +29,7 @@ public interface PathChecker {
* @param ztAddress ZeroTier address or 0 for none/any
* @param localSocket Local interface socket. -1 if unspecified
* @param remoteAddress remote address
+ * @return true if the path should be used
*/
boolean onPathCheck(long ztAddress, long localSocket, InetSocketAddress remoteAddress);
diff --git a/java/src/com/zerotier/sdk/Peer.java b/java/src/com/zerotier/sdk/Peer.java
index eb3d71300..e3d544381 100644
--- a/java/src/com/zerotier/sdk/Peer.java
+++ b/java/src/com/zerotier/sdk/Peer.java
@@ -27,68 +27,92 @@
package com.zerotier.sdk;
-import java.util.ArrayList;
+import com.zerotier.sdk.util.StringUtils;
+
+import java.util.Arrays;
/**
- * Peer status result
+ * Peer status result buffer
+ *
+ * Defined in ZeroTierOne.h as ZT_Peer
*/
-public final class Peer {
- private long address;
- private int versionMajor;
- private int versionMinor;
- private int versionRev;
- private int latency;
- private PeerRole role;
- private PeerPhysicalPath[] paths;
+public class Peer {
- private Peer() {}
+ private final long address;
+
+ private final int versionMajor;
+
+ private final int versionMinor;
+
+ private final int versionRev;
+
+ private final int latency;
+
+ private final PeerRole role;
+
+ private final PeerPhysicalPath[] paths;
+
+ public Peer(long address, int versionMajor, int versionMinor, int versionRev, int latency, PeerRole role, PeerPhysicalPath[] paths) {
+ this.address = address;
+ this.versionMajor = versionMajor;
+ this.versionMinor = versionMinor;
+ this.versionRev = versionRev;
+ this.latency = latency;
+ this.role = role;
+ this.paths = paths;
+ }
+
+ @Override
+ public String toString() {
+ return "Peer(" + StringUtils.addressToString(address) + ", " + versionMajor + ", " + versionMinor + ", " + versionRev + ", " + latency + ", " + role + ", " + Arrays.toString(paths) + ")";
+ }
/**
* ZeroTier address (40 bits)
*/
- public final long address() {
+ public long getAddress() {
return address;
}
/**
* Remote major version or -1 if not known
*/
- public final int versionMajor() {
+ public int getVersionMajor() {
return versionMajor;
}
/**
* Remote minor version or -1 if not known
*/
- public final int versionMinor() {
+ public int getVersionMinor() {
return versionMinor;
}
/**
* Remote revision or -1 if not known
*/
- public final int versionRev() {
+ public int getVersionRev() {
return versionRev;
}
/**
* Last measured latency in milliseconds or zero if unknown
*/
- public final int latency() {
+ public int getLatency() {
return latency;
}
/**
* What trust hierarchy role does this device have?
*/
- public final PeerRole role() {
+ public PeerRole getRole() {
return role;
}
/**
* Known network paths to peer
*/
- public final PeerPhysicalPath[] paths() {
+ public PeerPhysicalPath[] getPaths() {
return paths;
}
-}
\ No newline at end of file
+}
diff --git a/java/src/com/zerotier/sdk/PeerPhysicalPath.java b/java/src/com/zerotier/sdk/PeerPhysicalPath.java
index 3f9a86128..f6d326425 100644
--- a/java/src/com/zerotier/sdk/PeerPhysicalPath.java
+++ b/java/src/com/zerotier/sdk/PeerPhysicalPath.java
@@ -31,48 +31,62 @@ import java.net.InetSocketAddress;
/**
* Physical network path to a peer
+ *
+ * Defined in ZeroTierOne.h as ZT_PeerPhysicalPath
*/
-public final class PeerPhysicalPath {
- private InetSocketAddress address;
- private long lastSend;
- private long lastReceive;
- private boolean fixed;
- private boolean preferred;
+public class PeerPhysicalPath {
- private PeerPhysicalPath() {}
+ private final InetSocketAddress address;
+
+ private final long lastSend;
+
+ private final long lastReceive;
+
+ private final boolean preferred;
+
+ public PeerPhysicalPath(InetSocketAddress address, long lastSend, long lastReceive, boolean preferred) {
+ this.address = address;
+ if (lastSend < 0) {
+ throw new RuntimeException("lastSend < 0: " + lastSend);
+ }
+ this.lastSend = lastSend;
+ if (lastReceive < 0) {
+ throw new RuntimeException("lastReceive < 0: " + lastReceive);
+ }
+ this.lastReceive = lastReceive;
+ this.preferred = preferred;
+ }
+
+ @Override
+ public String toString() {
+ return "PeerPhysicalPath(" + address + ", " + lastSend + ", " + lastReceive + ", " + preferred + ")";
+ }
/**
* Address of endpoint
*/
- public final InetSocketAddress address() {
+ public InetSocketAddress getAddress() {
return address;
}
/**
* Time of last send in milliseconds or 0 for never
*/
- public final long lastSend() {
+ public long getLastSend() {
return lastSend;
}
/**
* Time of last receive in milliseconds or 0 for never
*/
- public final long lastReceive() {
+ public long getLastReceive() {
return lastReceive;
}
- /**
- * Is path fixed? (i.e. not learned, static)
- */
- public final boolean isFixed() {
- return fixed;
- }
-
/**
* Is path preferred?
*/
- public final boolean isPreferred() {
+ public boolean isPreferred() {
return preferred;
}
-}
\ No newline at end of file
+}
diff --git a/java/src/com/zerotier/sdk/PeerRole.java b/java/src/com/zerotier/sdk/PeerRole.java
index fce183d9c..d69a1f1bb 100644
--- a/java/src/com/zerotier/sdk/PeerRole.java
+++ b/java/src/com/zerotier/sdk/PeerRole.java
@@ -27,19 +27,45 @@
package com.zerotier.sdk;
+/**
+ * What trust hierarchy role does this peer have?
+ *
+ * Defined in ZeroTierOne.h as ZT_PeerRole
+ */
public enum PeerRole {
+
/**
* An ordinary node
*/
- PEER_ROLE_LEAF,
+ PEER_ROLE_LEAF(0),
/**
* moon root
*/
- PEER_ROLE_MOON,
+ PEER_ROLE_MOON(1),
/**
* planetary root
*/
- PEER_ROLE_PLANET
-}
\ No newline at end of file
+ PEER_ROLE_PLANET(2);
+
+ @SuppressWarnings({"FieldCanBeLocal", "unused"})
+ private final int id;
+
+ PeerRole(int id) {
+ this.id = id;
+ }
+
+ public static PeerRole fromInt(int id) {
+ switch (id) {
+ case 0:
+ return PEER_ROLE_LEAF;
+ case 1:
+ return PEER_ROLE_MOON;
+ case 2:
+ return PEER_ROLE_PLANET;
+ default:
+ throw new RuntimeException("Unhandled value: " + id);
+ }
+ }
+}
diff --git a/java/src/com/zerotier/sdk/ResultCode.java b/java/src/com/zerotier/sdk/ResultCode.java
index 09e7d3b13..dc8a901b5 100644
--- a/java/src/com/zerotier/sdk/ResultCode.java
+++ b/java/src/com/zerotier/sdk/ResultCode.java
@@ -34,12 +34,20 @@ package com.zerotier.sdk;
* occurs, the node should be considered to not be working correctly. These
* indicate serious problems like an inaccessible data store or a compile
* problem.
+ *
+ * Defined in ZeroTierOne.h as ZT_ResultCode
*/
public enum ResultCode {
+
/**
* Operation completed normally
*/
- RESULT_OK(0),
+ RESULT_OK(0),
+
+ /**
+ * Call produced no error but no action was taken
+ */
+ RESULT_OK_IGNORED(1),
// Fatal errors (>=100, <1000)
/**
@@ -68,12 +76,36 @@ public enum ResultCode {
RESULT_ERROR_BAD_PARAMETER(1002);
-
- private final int id;
- ResultCode(int id) { this.id = id; }
- public int getValue() { return id; }
+ private final int id;
- public boolean isFatal(int id) {
- return (id > 100 && id < 1000);
+ ResultCode(int id) {
+ this.id = id;
}
-}
\ No newline at end of file
+
+ public static ResultCode fromInt(int id) {
+ switch (id) {
+ case 0:
+ return RESULT_OK;
+ case 1:
+ return RESULT_OK_IGNORED;
+ case 100:
+ return RESULT_FATAL_ERROR_OUT_OF_MEMORY;
+ case 101:
+ return RESULT_FATAL_ERROR_DATA_STORE_FAILED;
+ case 102:
+ return RESULT_FATAL_ERROR_INTERNAL;
+ case 1000:
+ return RESULT_ERROR_NETWORK_NOT_FOUND;
+ case 1001:
+ return RESULT_ERROR_UNSUPPORTED_OPERATION;
+ case 1002:
+ return RESULT_ERROR_BAD_PARAMETER;
+ default:
+ throw new RuntimeException("Unhandled value: " + id);
+ }
+ }
+
+ public boolean isFatal() {
+ return (id >= 100 && id < 1000);
+ }
+}
diff --git a/java/src/com/zerotier/sdk/Version.java b/java/src/com/zerotier/sdk/Version.java
index c93c25970..0dbe1d2a5 100644
--- a/java/src/com/zerotier/sdk/Version.java
+++ b/java/src/com/zerotier/sdk/Version.java
@@ -27,10 +27,27 @@
package com.zerotier.sdk;
-public final class Version {
- private Version() {}
-
- public int major = 0;
- public int minor = 0;
- public int revision = 0;
-}
\ No newline at end of file
+public class Version {
+
+ private final int major;
+ private final int minor;
+ private final int revision;
+
+ public Version(int major, int minor, int revision) {
+ this.major = major;
+ this.minor = minor;
+ this.revision = revision;
+ }
+
+ public int getMajor() {
+ return major;
+ }
+
+ public int getMinor() {
+ return minor;
+ }
+
+ public int getRevision() {
+ return revision;
+ }
+}
diff --git a/java/src/com/zerotier/sdk/VirtualNetworkConfig.java b/java/src/com/zerotier/sdk/VirtualNetworkConfig.java
index c7b48d5c5..bcf64854a 100644
--- a/java/src/com/zerotier/sdk/VirtualNetworkConfig.java
+++ b/java/src/com/zerotier/sdk/VirtualNetworkConfig.java
@@ -29,197 +29,302 @@ package com.zerotier.sdk;
import android.util.Log;
-import java.lang.Comparable;
-import java.lang.Override;
-import java.lang.String;
-import java.util.ArrayList;
+import com.zerotier.sdk.util.StringUtils;
+
import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
-public final class VirtualNetworkConfig implements Comparable {
+/**
+ * Virtual network configuration
+ *
+ * Defined in ZeroTierOne.h as ZT_VirtualNetworkConfig
+ */
+public class VirtualNetworkConfig implements Comparable {
+
private final static String TAG = "VirtualNetworkConfig";
public static final int MAX_MULTICAST_SUBSCRIPTIONS = 4096;
public static final int ZT_MAX_ZT_ASSIGNED_ADDRESSES = 16;
- private long nwid;
- private long mac;
- private String name;
- private VirtualNetworkStatus status;
- private VirtualNetworkType type;
- private int mtu;
- private boolean dhcp;
- private boolean bridge;
- private boolean broadcastEnabled;
- private int portError;
- private boolean enabled;
- private long netconfRevision;
- private InetSocketAddress[] assignedAddresses;
- private VirtualNetworkRoute[] routes;
- private VirtualNetworkDNS dns;
+ private final long nwid;
- private VirtualNetworkConfig() {
+ private final long mac;
+ private final String name;
+
+ private final VirtualNetworkStatus status;
+
+ private final VirtualNetworkType type;
+
+ private final int mtu;
+
+ private final boolean dhcp;
+
+ private final boolean bridge;
+
+ private final boolean broadcastEnabled;
+
+ private final int portError;
+
+ private final long netconfRevision;
+
+ private final InetSocketAddress[] assignedAddresses;
+
+ private final VirtualNetworkRoute[] routes;
+
+ private final VirtualNetworkDNS dns;
+
+ public VirtualNetworkConfig(long nwid, long mac, String name, VirtualNetworkStatus status, VirtualNetworkType type, int mtu, boolean dhcp, boolean bridge, boolean broadcastEnabled, int portError, long netconfRevision, InetSocketAddress[] assignedAddresses, VirtualNetworkRoute[] routes, VirtualNetworkDNS dns) {
+ this.nwid = nwid;
+ this.mac = mac;
+ this.name = name;
+ this.status = status;
+ this.type = type;
+ if (mtu < 0) {
+ throw new RuntimeException("mtu < 0: " + mtu);
+ }
+ this.mtu = mtu;
+ this.dhcp = dhcp;
+ this.bridge = bridge;
+ this.broadcastEnabled = broadcastEnabled;
+ this.portError = portError;
+ if (netconfRevision < 0) {
+ throw new RuntimeException("netconfRevision < 0: " + netconfRevision);
+ }
+ this.netconfRevision = netconfRevision;
+ this.assignedAddresses = assignedAddresses;
+ this.routes = routes;
+ this.dns = dns;
}
- public boolean equals(VirtualNetworkConfig cfg) {
- ArrayList aaCurrent = new ArrayList<>();
- ArrayList aaNew = new ArrayList<>();
- for (InetSocketAddress s : assignedAddresses) {
- aaCurrent.add(s.toString());
- }
- for (InetSocketAddress s : cfg.assignedAddresses) {
- aaNew.add(s.toString());
- }
- Collections.sort(aaCurrent);
- Collections.sort(aaNew);
- boolean aaEqual = aaCurrent.equals(aaNew);
+ @Override
+ public String toString() {
+ return "VirtualNetworkConfig(" + StringUtils.networkIdToString(nwid) + ", " + StringUtils.macAddressToString(mac) + ", " + name + ", " + status + ", " + type + ", " + mtu + ", " + dhcp + ", " + bridge + ", " + broadcastEnabled + ", " + portError + ", " + netconfRevision + ", " + Arrays.toString(assignedAddresses) + ", " + Arrays.toString(routes) + ", " + dns + ")";
+ }
- ArrayList rCurrent = new ArrayList<>();
- ArrayList rNew = new ArrayList<>();
- for (VirtualNetworkRoute r : routes) {
- rCurrent.add(r.toString());
+ @Override
+ public boolean equals(Object o) {
+
+ if (!(o instanceof VirtualNetworkConfig)) {
+ return false;
}
- for (VirtualNetworkRoute r : cfg.routes) {
- rNew.add(r.toString());
- }
- Collections.sort(rCurrent);
- Collections.sort(rNew);
- boolean routesEqual = rCurrent.equals(rNew);
+
+ VirtualNetworkConfig cfg = (VirtualNetworkConfig) o;
if (this.nwid != cfg.nwid) {
- Log.i(TAG, "nwid Changed. Old: " + Long.toHexString(this.nwid) + " (" + Long.toString(this.nwid) + "), " +
- "New: " + Long.toHexString(cfg.nwid) + " (" + Long.toString(cfg.nwid) + ")");
+ Log.i(TAG, "NetworkID Changed. Old: " + StringUtils.networkIdToString(this.nwid) + " (" + this.nwid + "), " +
+ "New: " + StringUtils.networkIdToString(cfg.nwid) + " (" + cfg.nwid + ")");
+
+ return false;
}
+
if (this.mac != cfg.mac) {
- Log.i(TAG, "MAC Changed. Old: " + Long.toHexString(this.mac) + ", New: " + Long.toHexString(cfg.mac));
+ Log.i(TAG, "MAC Changed. Old: " + StringUtils.macAddressToString(this.mac) + ", New: " + StringUtils.macAddressToString(cfg.mac));
+
+ return false;
}
if (!this.name.equals(cfg.name)) {
- Log.i(TAG, "Name Changed. Old: " + this.name + " New: "+ cfg.name);
+ Log.i(TAG, "Name Changed. Old: " + this.name + ", New: " + cfg.name);
+
+ return false;
}
- if (!this.type.equals(cfg.type)) {
- Log.i(TAG, "TYPE changed. Old " + this.type + ", New: " + cfg.type);
+ if (this.status != cfg.status) {
+ Log.i(TAG, "Status Changed. Old: " + this.status + ", New: " + cfg.status);
+
+ return false;
+ }
+
+ if (this.type != cfg.type) {
+ Log.i(TAG, "Type changed. Old " + this.type + ", New: " + cfg.type);
+
+ return false;
}
if (this.mtu != cfg.mtu) {
- Log.i(TAG, "MTU Changed. Old: " + this.mtu + ", New: " + cfg.mtu);
+ Log.i(TAG, "MTU Changed. Old: " + this.mtu + ", New: " + cfg.mtu);
+
+ return false;
}
if (this.dhcp != cfg.dhcp) {
Log.i(TAG, "DHCP Flag Changed. Old: " + this.dhcp + ", New: " + cfg.dhcp);
+
+ return false;
}
if (this.bridge != cfg.bridge) {
Log.i(TAG, "Bridge Flag Changed. Old: " + this.bridge + ", New: " + cfg.bridge);
+
+ return false;
}
if (this.broadcastEnabled != cfg.broadcastEnabled) {
- Log.i(TAG, "Broadcast Flag Changed. Old: "+ this.broadcastEnabled +", New: " + this.broadcastEnabled);
+ Log.i(TAG, "Broadcast Flag Changed. Old: "+ this.broadcastEnabled + ", New: " + cfg.broadcastEnabled);
+
+ return false;
}
if (this.portError != cfg.portError) {
- Log.i(TAG, "Port Error Changed. Old: " + this.portError + ", New: " + this.portError);
+ Log.i(TAG, "Port Error Changed. Old: " + this.portError + ", New: " + cfg.portError);
+
+ return false;
}
- if (this.enabled != cfg.enabled) {
- Log.i(TAG, "Enabled Changed. Old: " + this.enabled + ", New: " + this.enabled);
+ if (this.netconfRevision != cfg.netconfRevision) {
+ Log.i(TAG, "NetConfRevision Changed. Old: " + this.netconfRevision + ", New: " + cfg.netconfRevision);
+
+ return false;
}
- if (!aaEqual) {
+ if (!Arrays.equals(assignedAddresses, cfg.assignedAddresses)) {
+
+ ArrayList aaCurrent = new ArrayList<>();
+ ArrayList aaNew = new ArrayList<>();
+ for (InetSocketAddress s : assignedAddresses) {
+ aaCurrent.add(s.toString());
+ }
+ for (InetSocketAddress s : cfg.assignedAddresses) {
+ aaNew.add(s.toString());
+ }
+ Collections.sort(aaCurrent);
+ Collections.sort(aaNew);
+
Log.i(TAG, "Assigned Addresses Changed");
Log.i(TAG, "Old:");
for (String s : aaCurrent) {
Log.i(TAG, " " + s);
}
+ Log.i(TAG, "");
Log.i(TAG, "New:");
for (String s : aaNew) {
Log.i(TAG, " " +s);
}
+ Log.i(TAG, "");
+
+ return false;
}
- if (!routesEqual) {
+ if (!Arrays.equals(routes, cfg.routes)) {
+
+ ArrayList rCurrent = new ArrayList<>();
+ ArrayList rNew = new ArrayList<>();
+ for (VirtualNetworkRoute r : routes) {
+ rCurrent.add(r.toString());
+ }
+ for (VirtualNetworkRoute r : cfg.routes) {
+ rNew.add(r.toString());
+ }
+ Collections.sort(rCurrent);
+ Collections.sort(rNew);
+
Log.i(TAG, "Managed Routes Changed");
Log.i(TAG, "Old:");
for (String s : rCurrent) {
Log.i(TAG, " " + s);
}
+ Log.i(TAG, "");
Log.i(TAG, "New:");
for (String s : rNew) {
Log.i(TAG, " " + s);
}
+ Log.i(TAG, "");
+
+ return false;
}
- boolean dnsEquals = false;
- if (this.dns == null || cfg.dns == null) {
- dnsEquals = true;
- } else if (this.dns != null) {
- dnsEquals = this.dns.equals(cfg.dns);
+ boolean dnsEquals;
+ if (this.dns == null) {
+ //noinspection RedundantIfStatement
+ if (cfg.dns == null) {
+ dnsEquals = true;
+ } else {
+ dnsEquals = false;
+ }
+ } else {
+ if (cfg.dns == null) {
+ dnsEquals = false;
+ } else {
+ dnsEquals = this.dns.equals(cfg.dns);
+ }
}
- return this.nwid == cfg.nwid &&
- this.mac == cfg.mac &&
- this.name.equals(cfg.name) &&
- this.status.equals(cfg.status) &&
- this.type.equals(cfg.type) &&
- this.mtu == cfg.mtu &&
- this.dhcp == cfg.dhcp &&
- this.bridge == cfg.bridge &&
- this.broadcastEnabled == cfg.broadcastEnabled &&
- this.portError == cfg.portError &&
- this.enabled == cfg.enabled &&
- dnsEquals &&
- aaEqual && routesEqual;
+ if (!dnsEquals) {
+ return false;
+ }
+
+ return true;
}
+ @Override
public int compareTo(VirtualNetworkConfig cfg) {
- if(cfg.nwid == this.nwid) {
- return 0;
- } else {
- return this.nwid > cfg.nwid ? 1 : -1;
- }
+ return Long.compare(this.nwid, cfg.nwid);
+ }
+
+ @Override
+ public int hashCode() {
+
+ int result = 17;
+ result = 37 * result + (int) (nwid ^ (nwid >>> 32));
+ result = 37 * result + (int) (mac ^ (mac >>> 32));
+ result = 37 * result + name.hashCode();
+ result = 37 * result + status.hashCode();
+ result = 37 * result + type.hashCode();
+ result = 37 * result + mtu;
+ result = 37 * result + (dhcp ? 1 : 0);
+ result = 37 * result + (bridge ? 1 : 0);
+ result = 37 * result + (broadcastEnabled ? 1 : 0);
+ result = 37 * result + portError;
+ result = 37 * result + (int) (netconfRevision ^ (netconfRevision >>> 32));
+ result = 37 * result + Arrays.hashCode(assignedAddresses);
+ result = 37 * result + Arrays.hashCode(routes);
+ result = 37 * result + (dns == null ? 0 : dns.hashCode());
+
+ return result;
}
/**
* 64-bit ZeroTier network ID
*/
- public final long networkId() {
+ public long getNwid() {
return nwid;
}
/**
- * Ethernet MAC (40 bits) that should be assigned to port
+ * Ethernet MAC (48 bits) that should be assigned to port
*/
- public final long macAddress() {
+ public long getMac() {
return mac;
}
/**
* Network name (from network configuration master)
*/
- public final String name() {
+ public String getName() {
return name;
}
/**
* Network configuration request status
*/
- public final VirtualNetworkStatus networkStatus() {
+ public VirtualNetworkStatus getStatus() {
return status;
}
/**
* Network type
*/
- public final VirtualNetworkType networkType() {
+ public VirtualNetworkType getType() {
return type;
}
/**
* Maximum interface MTU
*/
- public final int mtu() {
+ public int getMtu() {
return mtu;
}
@@ -230,7 +335,7 @@ public final class VirtualNetworkConfig implements Comparable
*/
- public final boolean isDhcpAvailable() {
+ public boolean isDhcp() {
return dhcp;
}
@@ -240,21 +345,21 @@ public final class VirtualNetworkConfig implements ComparableThis is informational. If this is false, bridged packets will simply
* be dropped and bridging won't work.
*/
- public final boolean isBridgeEnabled() {
+ public boolean isBridge() {
return bridge;
}
/**
* If true, this network supports and allows broadcast (ff:ff:ff:ff:ff:ff) traffic
*/
- public final boolean broadcastEnabled() {
+ public boolean isBroadcastEnabled() {
return broadcastEnabled;
}
/**
* If the network is in PORT_ERROR state, this is the error most recently returned by the port config callback
*/
- public final int portError() {
+ public int getPortError() {
return portError;
}
@@ -263,12 +368,12 @@ public final class VirtualNetworkConfig implements ComparableIf this is zero, it means we're still waiting for our netconf.
*/
- public final long netconfRevision() {
+ public long getNetconfRevision() {
return netconfRevision;
}
/**
- * ZeroTier-assigned addresses (in {@link java.net.InetSocketAddress} objects)
+ * ZeroTier-assigned addresses (in {@link InetSocketAddress} objects)
*
* For IP, the port number of the sockaddr_XX structure contains the number
* of bits in the address netmask. Only the IP address and port are used.
@@ -277,16 +382,21 @@ public final class VirtualNetworkConfig implements Comparable
*
- * This should not call {@link Node#multicastSubscribe} or other network-modifying
+ * This should not call {@link Node#multicastSubscribe(long, long)} or other network-modifying
* methods, as this could cause a deadlock in multithreaded or interrupt
* driven environments.
*
@@ -53,8 +53,8 @@ public interface VirtualNetworkConfigListener {
* @param config {@link VirtualNetworkConfig} object with the new configuration
* @return 0 on success
*/
- public int onNetworkConfigurationUpdated(
+ int onNetworkConfigurationUpdated(
long nwid,
VirtualNetworkConfigOperation op,
VirtualNetworkConfig config);
-}
\ No newline at end of file
+}
diff --git a/java/src/com/zerotier/sdk/VirtualNetworkConfigOperation.java b/java/src/com/zerotier/sdk/VirtualNetworkConfigOperation.java
index b70eb4786..a1981bd15 100644
--- a/java/src/com/zerotier/sdk/VirtualNetworkConfigOperation.java
+++ b/java/src/com/zerotier/sdk/VirtualNetworkConfigOperation.java
@@ -24,26 +24,55 @@
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
+
package com.zerotier.sdk;
+/**
+ * Virtual network configuration update type
+ *
+ * Defined in ZeroTierOne.h as ZT_VirtualNetworkConfigOperation
+ */
public enum VirtualNetworkConfigOperation {
+
/**
* Network is coming up (either for the first time or after service restart)
*/
- VIRTUAL_NETWORK_CONFIG_OPERATION_UP,
+ VIRTUAL_NETWORK_CONFIG_OPERATION_UP(1),
/**
* Network configuration has been updated
*/
- VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE,
+ VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE(2),
/**
* Network is going down (not permanently)
*/
- VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,
+ VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN(3),
/**
* Network is going down permanently (leave/delete)
*/
- VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY
+ VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY(4);
+
+ @SuppressWarnings({"FieldCanBeLocal", "unused"})
+ private final int id;
+
+ VirtualNetworkConfigOperation(int id) {
+ this.id = id;
+ }
+
+ public static VirtualNetworkConfigOperation fromInt(int id) {
+ switch (id) {
+ case 1:
+ return VIRTUAL_NETWORK_CONFIG_OPERATION_UP;
+ case 2:
+ return VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE;
+ case 3:
+ return VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN;
+ case 4:
+ return VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY;
+ default:
+ throw new RuntimeException("Unhandled value: " + id);
+ }
+ }
}
diff --git a/java/src/com/zerotier/sdk/VirtualNetworkDNS.java b/java/src/com/zerotier/sdk/VirtualNetworkDNS.java
index 7046fd424..6e4bb3d22 100644
--- a/java/src/com/zerotier/sdk/VirtualNetworkDNS.java
+++ b/java/src/com/zerotier/sdk/VirtualNetworkDNS.java
@@ -8,15 +8,48 @@ package com.zerotier.sdk;
import java.net.InetSocketAddress;
import java.util.ArrayList;
+/**
+ * DNS configuration to be pushed on a virtual network
+ *
+ * Defined in ZeroTierOne.h as ZT_VirtualNetworkDNS
+ */
public class VirtualNetworkDNS implements Comparable {
- private String domain;
- private ArrayList servers;
- public VirtualNetworkDNS() {}
+ private final String domain;
+ private final ArrayList servers;
- public boolean equals(VirtualNetworkDNS o) {
- if (o == null) return false;
- return domain.equals(o.domain) && servers.equals(o.servers);
+ public VirtualNetworkDNS(String domain, ArrayList servers) {
+ this.domain = domain;
+ this.servers = servers;
+ }
+
+ @Override
+ public String toString() {
+ return "VirtualNetworkDNS(" + domain + ", " + servers + ")";
+ }
+
+ @Override
+ public boolean equals(Object o) {
+
+ if (o == null) {
+ return false;
+ }
+
+ if (!(o instanceof VirtualNetworkDNS)) {
+ return false;
+ }
+
+ VirtualNetworkDNS d = (VirtualNetworkDNS) o;
+
+ if (!domain.equals(d.domain)) {
+ return false;
+ }
+
+ if (!servers.equals(d.servers)) {
+ return false;
+ }
+
+ return true;
}
@Override
@@ -24,7 +57,21 @@ public class VirtualNetworkDNS implements Comparable {
return domain.compareTo(o.domain);
}
- public String getSearchDomain() { return domain; }
+ @Override
+ public int hashCode() {
- public ArrayList getServers() { return servers; }
+ int result = 17;
+ result = 37 * result + domain.hashCode();
+ result = 37 * result + servers.hashCode();
+
+ return result;
+ }
+
+ public String getDomain() {
+ return domain;
+ }
+
+ public ArrayList getServers() {
+ return servers;
+ }
}
diff --git a/java/src/com/zerotier/sdk/VirtualNetworkFrameListener.java b/java/src/com/zerotier/sdk/VirtualNetworkFrameListener.java
index 9ad322825..650c9cedc 100644
--- a/java/src/com/zerotier/sdk/VirtualNetworkFrameListener.java
+++ b/java/src/com/zerotier/sdk/VirtualNetworkFrameListener.java
@@ -28,17 +28,18 @@
package com.zerotier.sdk;
public interface VirtualNetworkFrameListener {
+
/**
* Function to send a frame out to a virtual network port
*
* @param nwid ZeroTier One network ID
* @param srcMac source MAC address
* @param destMac destination MAC address
- * @param ethertype
- * @param vlanId
+ * @param etherType EtherType
+ * @param vlanId VLAN ID
* @param frameData data to send
*/
- public void onVirtualNetworkFrame(
+ void onVirtualNetworkFrame(
long nwid,
long srcMac,
long destMac,
diff --git a/java/src/com/zerotier/sdk/VirtualNetworkRoute.java b/java/src/com/zerotier/sdk/VirtualNetworkRoute.java
index 8dd700c09..afd9ee45a 100644
--- a/java/src/com/zerotier/sdk/VirtualNetworkRoute.java
+++ b/java/src/com/zerotier/sdk/VirtualNetworkRoute.java
@@ -29,80 +29,135 @@ package com.zerotier.sdk;
import java.net.InetSocketAddress;
-public final class VirtualNetworkRoute implements Comparable
+/**
+ * A route to be pushed on a virtual network
+ *
+ * Defined in ZeroTierOne.h as ZT_VirtualNetworkRoute
+ */
+public class VirtualNetworkRoute implements Comparable
{
- private VirtualNetworkRoute() {
- target = null;
- via = null;
- flags = 0;
- metric = 0;
- }
-
/**
* Target network / netmask bits (in port field) or NULL or 0.0.0.0/0 for default
*/
- public InetSocketAddress target;
-
+ private final InetSocketAddress target;
+
/**
* Gateway IP address (port ignored) or NULL (family == 0) for LAN-local (no gateway)
*/
- public InetSocketAddress via;
+ private final InetSocketAddress via;
/**
* Route flags
*/
- public int flags;
+ private final int flags;
/**
* Route metric (not currently used)
*/
- public int metric;
+ private final int metric;
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(target.toString());
- if (via != null) {
- sb.append(via.toString());
- }
- return sb.toString();
+ public VirtualNetworkRoute(InetSocketAddress target, InetSocketAddress via, int flags, int metric) {
+ this.target = target;
+ this.via = via;
+ this.flags = flags;
+ this.metric = metric;
}
@Override
- public int compareTo(VirtualNetworkRoute other) {
- return this.toString().compareTo(other.toString());
- }
+ public String toString() {
+ return "VirtualNetworkRoute(" + target + ", " + via + ", " + flags + ", " + metric + ")";
+ }
- public boolean equals(VirtualNetworkRoute other) {
- boolean targetEquals = false;
- if (target == null && other.target == null) {
- targetEquals = true;
- }
- else if (target == null && other.target != null) {
- targetEquals = false;
- }
- else if (target != null && other.target == null) {
- targetEquals = false;
- }
- else {
- targetEquals = target.toString().equals(other.target.toString());
+ @Override
+ public int compareTo(VirtualNetworkRoute other) {
+ throw new RuntimeException("Unimplemented");
+ }
+
+ @Override
+ public boolean equals(Object o) {
+
+ if (!(o instanceof VirtualNetworkRoute)) {
+ return false;
}
+ VirtualNetworkRoute other = (VirtualNetworkRoute) o;
+
+ boolean targetEquals;
+ if (target == null) {
+ //noinspection RedundantIfStatement
+ if (other.target == null) {
+ targetEquals = true;
+ } else {
+ targetEquals = false;
+ }
+ } else {
+ if (other.target == null) {
+ targetEquals = false;
+ } else {
+ targetEquals = target.equals(other.target);
+ }
+ }
+
+ if (!targetEquals) {
+ return false;
+ }
boolean viaEquals;
- if (via == null && other.via == null) {
- viaEquals = true;
- }
- else if (via == null && other.via != null) {
- viaEquals = false;
- }
- else if (via != null && other.via == null) {
- viaEquals = false;
- }
- else {
- viaEquals = via.toString().equals(other.via.toString());
+ if (via == null) {
+ //noinspection RedundantIfStatement
+ if (other.via == null) {
+ viaEquals = true;
+ } else {
+ viaEquals = false;
+ }
+ } else {
+ if (other.via == null) {
+ viaEquals = false;
+ } else {
+ viaEquals = via.equals(other.via);
+ }
}
- return viaEquals && targetEquals;
+ if (!viaEquals) {
+ return false;
+ }
+
+ if (flags != other.flags) {
+ return false;
+ }
+
+ if (metric != other.metric) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+
+ int result = 17;
+ result = 37 * result + (target == null ? 0 : target.hashCode());
+ result = 37 * result + (via == null ? 0 : via.hashCode());
+ result = 37 * result + flags;
+ result = 37 * result + metric;
+
+ return result;
+ }
+
+ public InetSocketAddress getTarget() {
+ return target;
+ }
+
+ public InetSocketAddress getVia() {
+ return via;
+ }
+
+ public int getFlags() {
+ return flags;
+ }
+
+ public int getMetric() {
+ return metric;
}
}
diff --git a/java/src/com/zerotier/sdk/VirtualNetworkStatus.java b/java/src/com/zerotier/sdk/VirtualNetworkStatus.java
index 68e01bd61..8a32ba6ad 100644
--- a/java/src/com/zerotier/sdk/VirtualNetworkStatus.java
+++ b/java/src/com/zerotier/sdk/VirtualNetworkStatus.java
@@ -24,41 +24,76 @@
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
+
package com.zerotier.sdk;
+/**
+ * Virtual network status codes
+ *
+ * Defined in ZeroTierOne.h as ZT_VirtualNetworkStatus
+ */
public enum VirtualNetworkStatus {
+
/**
* Waiting for network configuration (also means revision == 0)
*/
- NETWORK_STATUS_REQUESTING_CONFIGURATION,
+ NETWORK_STATUS_REQUESTING_CONFIGURATION(0),
/**
* Configuration received and we are authorized
*/
- NETWORK_STATUS_OK,
-
- /**
- * Netconf master said SSO auth required.
- */
- NETWORK_STATUS_AUTHENTICATION_REQUIRED,
+ NETWORK_STATUS_OK(1),
/**
* Netconf master told us 'nope'
*/
- NETWORK_STATUS_ACCESS_DENIED,
+ NETWORK_STATUS_ACCESS_DENIED(2),
/**
* Netconf master exists, but this virtual network does not
*/
- NETWORK_STATUS_NOT_FOUND,
+ NETWORK_STATUS_NOT_FOUND(3),
/**
* Initialization of network failed or other internal error
*/
- NETWORK_STATUS_PORT_ERROR,
+ NETWORK_STATUS_PORT_ERROR(4),
/**
* ZeroTier One version too old
*/
- NETWORK_STATUS_CLIENT_TOO_OLD
+ NETWORK_STATUS_CLIENT_TOO_OLD(5),
+
+ /**
+ * External authentication is required (e.g. SSO)
+ */
+ NETWORK_STATUS_AUTHENTICATION_REQUIRED(6);
+
+ @SuppressWarnings({"FieldCanBeLocal", "unused"})
+ private final int id;
+
+ VirtualNetworkStatus(int id) {
+ this.id = id;
+ }
+
+ public static VirtualNetworkStatus fromInt(int id) {
+ switch (id) {
+ case 0:
+ return NETWORK_STATUS_REQUESTING_CONFIGURATION;
+ case 1:
+ return NETWORK_STATUS_OK;
+ case 2:
+ return NETWORK_STATUS_ACCESS_DENIED;
+ case 3:
+ return NETWORK_STATUS_NOT_FOUND;
+ case 4:
+ return NETWORK_STATUS_PORT_ERROR;
+ case 5:
+ return NETWORK_STATUS_CLIENT_TOO_OLD;
+ case 6:
+ return NETWORK_STATUS_AUTHENTICATION_REQUIRED;
+ default:
+ throw new RuntimeException("Unhandled value: " + id);
+ }
+ }
}
diff --git a/java/src/com/zerotier/sdk/VirtualNetworkType.java b/java/src/com/zerotier/sdk/VirtualNetworkType.java
index ab1f4e087..44be8864b 100644
--- a/java/src/com/zerotier/sdk/VirtualNetworkType.java
+++ b/java/src/com/zerotier/sdk/VirtualNetworkType.java
@@ -24,16 +24,41 @@
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
+
package com.zerotier.sdk;
+/**
+ * Virtual network type codes
+ *
+ * Defined in ZeroTierOne.h as ZT_VirtualNetworkType
+ */
public enum VirtualNetworkType {
+
/**
* Private networks are authorized via certificates of membership
*/
- NETWORK_TYPE_PRIVATE,
+ NETWORK_TYPE_PRIVATE(0),
/**
* Public networks have no access control -- they'll always be AUTHORIZED
*/
- NETWORK_TYPE_PUBLIC
+ NETWORK_TYPE_PUBLIC(1);
+
+ @SuppressWarnings({"FieldCanBeLocal", "unused"})
+ private final int id;
+
+ VirtualNetworkType(int id) {
+ this.id = id;
+ }
+
+ public static VirtualNetworkType fromInt(int id) {
+ switch (id) {
+ case 0:
+ return NETWORK_TYPE_PRIVATE;
+ case 1:
+ return NETWORK_TYPE_PUBLIC;
+ default:
+ throw new RuntimeException("Unhandled value: " + id);
+ }
+ }
}
diff --git a/java/src/com/zerotier/sdk/util/StringUtils.java b/java/src/com/zerotier/sdk/util/StringUtils.java
new file mode 100644
index 000000000..c7bcc5d9f
--- /dev/null
+++ b/java/src/com/zerotier/sdk/util/StringUtils.java
@@ -0,0 +1,52 @@
+/*
+ * ZeroTier One - Network Virtualization Everywhere
+ * Copyright (C) 2011-2023 ZeroTier, Inc. https://www.zerotier.com/
+ */
+
+package com.zerotier.sdk.util;
+
+public class StringUtils {
+
+ /**
+ * Convert mac address to string.
+ *
+ * @param mac MAC address
+ * @return string in XX:XX:XX:XX:XX:XX format
+ */
+ public static String macAddressToString(long mac) {
+
+ int[] macChars = new int[6];
+ for (int i = 0; i < 6; i++) {
+ macChars[i] = (int) (mac % 256);
+ mac >>= 8;
+ }
+
+ return String.format("%02x:%02x:%02x:%02x:%02x:%02x", macChars[5], macChars[4], macChars[3], macChars[2], macChars[1], macChars[0]);
+ }
+
+ /**
+ * Convert long to hex string.
+ *
+ * @param networkId long
+ * @return string with 0 padding
+ */
+ public static String networkIdToString(long networkId) {
+ return String.format("%016x", networkId);
+ }
+
+ /**
+ * Convert node address to string.
+ *
+ * Node addresses are 40 bits, so print 10 hex characters.
+ *
+ * @param address Node address
+ * @return formatted string
+ */
+ public static String addressToString(long address) {
+ return String.format("%010x", address);
+ }
+
+ public static String etherTypeToString(long etherType) {
+ return String.format("%04x", etherType);
+ }
+}
diff --git a/java/test/com/zerotier/sdk/util/StringUtilsTest.java b/java/test/com/zerotier/sdk/util/StringUtilsTest.java
new file mode 100644
index 000000000..257b14a99
--- /dev/null
+++ b/java/test/com/zerotier/sdk/util/StringUtilsTest.java
@@ -0,0 +1,73 @@
+/*
+ * ZeroTier One - Network Virtualization Everywhere
+ * Copyright (C) 2011-2023 ZeroTier, Inc. https://www.zerotier.com/
+ */
+
+package com.zerotier.sdk.util;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StringUtilsTest {
+
+ public StringUtilsTest() {
+ }
+
+ public String oldMacDisplay(long mac) {
+
+ String macStr = Long.toHexString(mac);
+
+ if (macStr.length() > 12) {
+ throw new RuntimeException();
+ }
+
+ while (macStr.length() < 12) {
+ //noinspection StringConcatenationInLoop
+ macStr = "0" + macStr;
+ }
+
+ //noinspection StringBufferReplaceableByString
+ StringBuilder displayMac = new StringBuilder();
+ displayMac.append(macStr.charAt(0));
+ displayMac.append(macStr.charAt(1));
+ displayMac.append(':');
+ displayMac.append(macStr.charAt(2));
+ displayMac.append(macStr.charAt(3));
+ displayMac.append(':');
+ displayMac.append(macStr.charAt(4));
+ displayMac.append(macStr.charAt(5));
+ displayMac.append(':');
+ displayMac.append(macStr.charAt(6));
+ displayMac.append(macStr.charAt(7));
+ displayMac.append(':');
+ displayMac.append(macStr.charAt(8));
+ displayMac.append(macStr.charAt(9));
+ displayMac.append(':');
+ displayMac.append(macStr.charAt(10));
+ displayMac.append(macStr.charAt(11));
+
+ return displayMac.toString();
+ }
+
+ @Test
+ public void testMacDisplay() {
+
+ long mac1 = 1234567891;
+ assertThat(StringUtils.macAddressToString(mac1)).isEqualTo(oldMacDisplay(mac1));
+
+ long mac2 = 999999999;
+ assertThat(StringUtils.macAddressToString(mac2)).isEqualTo(oldMacDisplay(mac2));
+
+ long mac3 = 0x7fffffffffffL;
+ assertThat(StringUtils.macAddressToString(mac3)).isEqualTo(oldMacDisplay(mac3));
+ assertThat(StringUtils.macAddressToString(mac3)).isEqualTo("7f:ff:ff:ff:ff:ff");
+
+ long mac4 = 0x7fafcf3f8fffL;
+ assertThat(StringUtils.macAddressToString(mac4)).isEqualTo(oldMacDisplay(mac4));
+ assertThat(StringUtils.macAddressToString(mac4)).isEqualTo("7f:af:cf:3f:8f:ff");
+ }
+}
diff --git a/one.cpp b/one.cpp
index 46a23b1ee..ba5be9b18 100644
--- a/one.cpp
+++ b/one.cpp
@@ -2235,6 +2235,27 @@ int main(int argc,char **argv)
}
}
+ // Check and fix permissions on critical files at startup
+ try {
+ char p[4096];
+ OSUtils::ztsnprintf(p, sizeof(p), "%s" ZT_PATH_SEPARATOR_S "identity.secret", homeDir.c_str());
+ if (OSUtils::fileExists(p)) {
+ OSUtils::lockDownFile(p, false);
+ }
+ }
+ catch (...) {
+ }
+
+ try {
+ char p[4096];
+ OSUtils::ztsnprintf(p, sizeof(p), "%s" ZT_PATH_SEPARATOR_S "authtoken.secret", homeDir.c_str());
+ if (OSUtils::fileExists(p)) {
+ OSUtils::lockDownFile(p, false);
+ }
+ }
+ catch (...) {
+ }
+
// This can be removed once the new controller code has been around for many versions
if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
fprintf(stderr,"%s: FATAL: an old controller.db exists in %s -- see instructions in controller/README.md for how to migrate!" ZT_EOL_S,argv[0],homeDir.c_str());
diff --git a/osdep/OSUtils.cpp b/osdep/OSUtils.cpp
index 36814523a..e237325c4 100644
--- a/osdep/OSUtils.cpp
+++ b/osdep/OSUtils.cpp
@@ -257,6 +257,16 @@ void OSUtils::lockDownFile(const char *path,bool isDir)
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
+
+ // Remove 'Everyone' group from R/RX access
+ startupInfo.cb = sizeof(startupInfo);
+ memset(&startupInfo, 0, sizeof(STARTUPINFOA));
+ memset(&processInfo, 0, sizeof(PROCESS_INFORMATION));
+ if (CreateProcessA(NULL, (LPSTR)(std::string("C:\\Windows\\System32\\icacls.exe \"") + path + "\" /remove:g Everyone /t /c /Q").c_str(), NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startupInfo, &processInfo)) {
+ WaitForSingleObject(processInfo.hProcess, INFINITE);
+ CloseHandle(processInfo.hProcess);
+ CloseHandle(processInfo.hThread);
+ }
}
#endif
#endif