Re-work of thread model

This commit is contained in:
Joseph Henry
2019-02-06 22:00:39 -08:00
parent 292fcdda2c
commit 2fdcf025e1
138 changed files with 7567 additions and 15053 deletions

View File

@@ -28,29 +28,63 @@ cmake_minimum_required (VERSION 3.0)
project (zt) project (zt)
set (CMAKE_VERBOSE_MAKEFILE ON) set (CMAKE_VERBOSE_MAKEFILE ON)
set (CMAKE_SUPPRESS_REGENERATION true)
set (PROJ_DIR ${PROJECT_SOURCE_DIR})
set (CMAKE_BINARY_DIR ${PROJECT_SOURCE_DIR}/bin)
set (EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set (LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib)
set (INCLUDE_PATH ${PROJ_DIR}/include)
# -----------------------------------------------------------------------------
# | BUILD CONFIG |
# -----------------------------------------------------------------------------
# Default build type: Release
# Release - Optimization and no debug info
# Debug - No optimization, debug info
# RelWithDebInfo - Release optimizations and debug info
# MinSizeRel - Similar to Release but with optimizations to minimize size
# Library and executable output paths
if (NOT CMAKE_BUILD_TYPE) if (NOT CMAKE_BUILD_TYPE)
set (CMAKE_BUILD_TYPE Release) message( FATAL_ERROR "Must specify CMAKE_BUILD_TYPE, CMake will exit." )
endif () endif ()
set (SILENCE "-Wno-unused-parameter -Wno-unused-variable -Wno-missing-field-initializers") if (CMAKE_BUILD_TYPE STREQUAL "Debug")
set (CMAKE_BINARY_DIR ${PROJECT_SOURCE_DIR}/bin/debug)
endif()
if (CMAKE_BUILD_TYPE STREQUAL "Release")
set (CMAKE_BINARY_DIR ${PROJECT_SOURCE_DIR}/bin/release)
endif()
set (EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set (LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib)
set (INTERMEDIATE_LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib/intermediate)
# -----------------------------------------------------------------------------
# | LIBRARY NAMES |
# -----------------------------------------------------------------------------
if (IN_XCODE)
set (XCODE_FRAMEWORK_NAME ${PROJECT_NAME})
endif ()
if (BUILDING_WIN)
# Possibly a CMake limitation? -- Can't share target output names
set (STATIC_LIB_NAME ${PROJECT_NAME}-static)
set (STATIC_LIB_OUTPUT_NAME ${PROJECT_NAME}-static)
set (DYNAMIC_LIB_NAME ${PROJECT_NAME}-shared)
set (DYNAMIC_LIB_OUTPUT_NAME ${PROJECT_NAME}-shared)
else ()
set (STATIC_LIB_NAME ${PROJECT_NAME}-static)
set (STATIC_LIB_OUTPUT_NAME ${PROJECT_NAME})
set (DYNAMIC_LIB_NAME ${PROJECT_NAME}-shared)
set (DYNAMIC_LIB_OUTPUT_NAME ${PROJECT_NAME})
endif ()
# -----------------------------------------------------------------------------
# | FLAGS |
# -----------------------------------------------------------------------------
set (SILENCE "-Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-missing-field-initializers")
set (LIBZT_FLAGS "-D_USING_LWIP_DEFINITIONS_=1 -DZT_SDK")
set (ZTCORE_FLAGS "-DZT_USE_MINIUPNPC=1 -DZT_SOFTWARE_UPDATE_DEFAULT=0")
if (BUILDING_WIN)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc -DNOMINMAX")
else ()
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${LIBZT_FLAGS} -fstack-protector")
set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${LIBZT_FLAGS} -DLWIP_DEBUG=1 -DLIBZT_DEBUG=1")
set (CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${LIBZT_FLAGS} -fstack-protector")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SILENCE} ${LIBZT_FLAGS} -O3 -Wall -Wextra -std=c++11")
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${SILENCE} ${LIBZT_FLAGS} -std=c++11 -DLWIP_DEBUG=1 -DLIBZT_DEBUG=1")
set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${SILENCE} ${LIBZT_FLAGS} -O3 -std=c++11")
endif ()
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# | PLATFORM/FEATURE AND IDE DETECTION | # | PLATFORM/FEATURE AND IDE DETECTION |
@@ -77,6 +111,9 @@ if (${CMAKE_GENERATOR} STREQUAL "Xcode")
#set_target_properties (${STATIC_LIB_NAME} PROPERTIES XCODE_ATTRIBUTE_MY_BUILD_ONLY_ACTIVE_ARCH YES) #set_target_properties (${STATIC_LIB_NAME} PROPERTIES XCODE_ATTRIBUTE_MY_BUILD_ONLY_ACTIVE_ARCH YES)
#set_target_properties (${STATIC_LIB_NAME} PROPERTIES XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "${MY_BUILD_ONLY_ACTIVE_ARCH}) #set_target_properties (${STATIC_LIB_NAME} PROPERTIES XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "${MY_BUILD_ONLY_ACTIVE_ARCH})
endif () endif ()
if (BUILDING_WIN32 OR BUILDING_WIN64 OR MSVC)
set (BUILDING_WIN TRUE)
endif ()
if (NOT BUILDING_ANDROID AND NOT IN_XCODE AND NOT BUILD_TESTS EQUAL 0) if (NOT BUILDING_ANDROID AND NOT IN_XCODE AND NOT BUILD_TESTS EQUAL 0)
set(SHOULD_BUILD_TESTS TRUE) set(SHOULD_BUILD_TESTS TRUE)
endif () endif ()
@@ -128,9 +165,41 @@ if ((BUILDING_ANDROID OR JNI) AND JNI_FOUND)
endif () endif ()
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# | LWIP PORT | # | SOURCE FILE GLOBS |
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
set (PROJ_DIR ${PROJECT_SOURCE_DIR})
set (LWIP_SRC_DIR "${PROJ_DIR}/ext/lwip/src")
set (ZTO_SRC_DIR "${PROJ_DIR}/ext/ZeroTierOne")
set (LIBZT_SRC_DIR "${PROJ_DIR}/src")
file (GLOB zerotiercoreSrcGlob
${ZTO_SRC_DIR}/node/*.cpp
${ZTO_SRC_DIR}/osdep/OSUtils.cpp
${ZTO_SRC_DIR}/osdep/PortMapper.cpp
${ZTO_SRC_DIR}/osdep/ManagedRoute.cpp)
file (GLOB libnatpmpSrcGlob
${ZTO_SRC_DIR}/ext/libnatpmp/natpmp.c
${ZTO_SRC_DIR}/ext/libnatpmp/getgateway.c)
file (GLOB libminiupnpcSrcGlob
${ZTO_SRC_DIR}/ext/miniupnpc/connecthostport.c
${ZTO_SRC_DIR}/ext/miniupnpc/igd_desc_parse.c
${ZTO_SRC_DIR}/ext/miniupnpc/minisoap.c
${ZTO_SRC_DIR}/ext/miniupnpc/minissdpc.c
${ZTO_SRC_DIR}/ext/miniupnpc/miniupnpc.c
${ZTO_SRC_DIR}/ext/miniupnpc/miniwget.c
${ZTO_SRC_DIR}/ext/miniupnpc/minixml.c
${ZTO_SRC_DIR}/ext/miniupnpc/portlistingparse.c
${ZTO_SRC_DIR}/ext/miniupnpc/receivedata.c
${ZTO_SRC_DIR}/ext/miniupnpc/upnpcommands.c
${ZTO_SRC_DIR}/ext/miniupnpc/upnpdev.c
${ZTO_SRC_DIR}/ext/miniupnpc/upnperrors.c
${ZTO_SRC_DIR}/ext/miniupnpc/upnpreplyparse.c)
file (GLOB libztSrcGlob ${LIBZT_SRC_DIR}/*.cpp)
if (UNIX) if (UNIX)
set (LWIP_PORT_DIR ${PROJ_DIR}/ext/lwip-contrib/ports/unix/port) set (LWIP_PORT_DIR ${PROJ_DIR}/ext/lwip-contrib/ports/unix/port)
endif () endif ()
@@ -139,69 +208,6 @@ if (BUILDING_WIN)
set (LWIP_PORT_DIR ${PROJ_DIR}/ext/lwip-contrib/ports/win32) set (LWIP_PORT_DIR ${PROJ_DIR}/ext/lwip-contrib/ports/win32)
endif () endif ()
# -----------------------------------------------------------------------------
# | LIBRARY NAMES |
# -----------------------------------------------------------------------------
if (IN_XCODE)
set (XCODE_FRAMEWORK_NAME ${PROJECT_NAME})
endif ()
if (BUILDING_WIN)
# Possibly a CMake limitation? -- Can't share target output names
set (STATIC_LIB_NAME ${PROJECT_NAME}-static)
set (STATIC_LIB_OUTPUT_NAME ${PROJECT_NAME}-static)
set (DYNAMIC_LIB_NAME ${PROJECT_NAME}-shared)
set (DYNAMIC_LIB_OUTPUT_NAME ${PROJECT_NAME}-shared)
else ()
set (STATIC_LIB_NAME ${PROJECT_NAME}-static)
set (STATIC_LIB_OUTPUT_NAME ${PROJECT_NAME})
set (DYNAMIC_LIB_NAME ${PROJECT_NAME}-shared)
set (DYNAMIC_LIB_OUTPUT_NAME ${PROJECT_NAME})
endif ()
# -----------------------------------------------------------------------------
# | FLAGS |
# -----------------------------------------------------------------------------
set (LIBZT_FLAGS "-DZT_SDK=1 -D_USING_LWIP_DEFINITIONS_=1")
set (LIBZT_FLAGS_DEBUG "-DZT_SDK=1 -DLIBZT_TRACE=1 -DLWIP_DEBUG=1 -DLIBZT_DEBUG=1 -DNS_TRACE=1 -DNS_DEBUG=1")
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${LIBZT_FLAGS_DEBUG}")
set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${LIBZT_FLAGS_DEBUG}")
if (BUILDING_WIN)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc -DNOMINMAX")
else ()
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector")
set (CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -fstack-protector")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${LIBZT_FLAGS} ${SILENCE} -O3 -Wall -Wextra -std=c++11")
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${SILENCE} -std=c++11")
set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${LIBZT_FLAGS} ${SILENCE} -O3 -std=c++11")
endif ()
#set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")
#set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fno-omit-frame-pointer -fsanitize=address")
# -----------------------------------------------------------------------------
# | SOURCE FILE GLOBS |
# -----------------------------------------------------------------------------
set (LWIP_SRC_DIR "${PROJ_DIR}/ext/lwip/src")
set (ZTO_SRC_DIR "${PROJ_DIR}/ext/ZeroTierOne")
set (LIBZT_SRC_DIR "${PROJ_DIR}/src")
include_directories ("${LIBZT_SRC_DIR}")
include_directories ("${ZTO_SRC_DIR}/include")
include_directories ("${PROJ_DIR}")
include_directories ("${ZTO_SRC_DIR}/osdep")
include_directories ("${ZTO_SRC_DIR}/node")
include_directories ("${ZTO_SRC_DIR}/service")
include_directories ("${PROJ_DIR}/include")
include_directories ("${LWIP_SRC_DIR}/include")
include_directories ("${LWIP_PORT_DIR}/include")
file (GLOB lwipSrcGlob file (GLOB lwipSrcGlob
${LWIP_SRC_DIR}/netif/*.c ${LWIP_SRC_DIR}/netif/*.c
${LWIP_SRC_DIR}/api/*.c ${LWIP_SRC_DIR}/api/*.c
@@ -211,176 +217,117 @@ file (GLOB lwipSrcGlob
${LWIP_SRC_DIR}/core/ipv6/*.c) ${LWIP_SRC_DIR}/core/ipv6/*.c)
list(REMOVE_ITEM lwipSrcGlob ${LWIP_SRC_DIR}/netif/slipif.c) list(REMOVE_ITEM lwipSrcGlob ${LWIP_SRC_DIR}/netif/slipif.c)
file (GLOB ztoSrcGlob
${ZTO_SRC_DIR}/node/*.cpp
${ZTO_SRC_DIR}/service/*.cpp
${ZTO_SRC_DIR}/osdep/OSUtils.cpp
${ZTO_SRC_DIR}/controller/*.cpp
${ZTO_SRC_DIR}/osdep/ManagedRoute.cpp)
file (GLOB libztSrcGlob ${LIBZT_SRC_DIR}/*.cpp)
file (GLOB ExampleAppSrcGlob
${PROJ_DIR}/examples/cpp/*.cpp
${PROJ_DIR}/examples/cpp/ipv4simple/*.cpp
${PROJ_DIR}/examples/cpp/ipv6simple/*.cpp
${PROJ_DIR}/examples/cpp/ipv6adhoc/*.cpp
${PROJ_DIR}/examples/cpp/sharedlib/*.cpp
${PROJ_DIR}/examples/ztproxy/*.cpp)
# header globs for xcode frameworks
file (GLOB frameworkPrivateHeaderGlob
${INCLUDE_PATH}/libzt.h
${INCLUDE_PATH}/libztDebug.h)
file (GLOB frameworkPublicHeaderGlob ${INCLUDE_PATH}/Xcode-Bridging-Header.h)
file (GLOB frameworkHeaderGlob ${frameworkPublicHeaderGlob} ${frameworkPrivateHeaderGlob})
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# | PLATFORM-SPECIFIC CONFIG | # | INCLUDES |
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# ANDROID-specific include_directories (${ZTO_SRC_DIR})
if (BUILDING_ANDROID) include_directories (${ZTO_SRC_DIR}/node)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -DSOCKLEN_T_DEFINED=1") include_directories (${ZTO_SRC_DIR}/osdep)
set (ANDROID_NDK /Users/$ENV{USER}/Library/Android/sdk/ndk-bundle/sysroot/usr/include/arm-linux-androideabi) include_directories (${ZTO_SRC_DIR}/include)
include_directories (${ANDROID_NDK}) include_directories (${ZTO_SRC_DIR}/ext/miniupnpc)
endif () include_directories (${ZTO_SRC_DIR}/ext/libnatpmp)
include_directories (${PROJ_DIR}/src)
# WINDOWS-specific MSVC flags and libraries include_directories (${PROJ_DIR}/include)
if (BUILDING_WIN) include_directories (${LWIP_SRC_DIR}/include)
# 32-bit include_directories (${LWIP_PORT_DIR}/include)
if(NOT BUILDING_WIN64) include_directories (${PROJ_DIR}/ext/concurrentqueue)
set (WINLIBDIR, "C:/Program Files (x86)/Windows Kits/10/Lib/10.0.16299.0/um/x86")
endif ()
# 64-bit
if(BUILDING_WIN64)
set (WINLIBDIR, "C:/Program Files (x86)/Windows Kits/10/Lib/10.0.16299.0/um/x64")
endif ()
#find_library (ws2_32_LIBRARY_PATH NAMES WS2_32 HINTS ${WINLIBDIR})
#find_library (shlwapi_LIBRARY_PATH NAMES ShLwApi HINTS ${WINLIBDIR})
set (ws2_32_LIBRARY_PATH "${WINLIBDIR}/WS2_32.Lib")
set (shlwapi_LIBRARY_PATH "${WINLIBDIR}/ShLwApi.Lib")
set (iphlpapi_LIBRARY_PATH "${WINLIBDIR}/iphlpapi.Lib")
message (STATUS ${WINLIBDIR})
message (STATUS "WS2_32=${ws2_32_LIBRARY_PATH}")
message (STATUS "ShLwApi=${shlwapi_LIBRARY_PATH}")
message (STATUS "liphlpapi=${iphlpapi_LIBRARY_PATH}")
add_definitions (-DZT_SDK=1)
add_definitions (-DADD_EXPORTS=1)
endif ()
# -----------------------------------------------------------------------------
# | OBJECTS-PIC (INTERMEDIATE) |
# -----------------------------------------------------------------------------
add_library (lwip_pic ${lwipSrcGlob})
set_target_properties (lwip_pic PROPERTIES POSITION_INDEPENDENT_CODE ON)
add_library (zto_pic ${ztoSrcGlob})
set_target_properties (zto_pic PROPERTIES POSITION_INDEPENDENT_CODE ON)
add_library (http_pic "${ZTO_SRC_DIR}/ext/http-parser/http_parser.c")
set_target_properties (http_pic PROPERTIES POSITION_INDEPENDENT_CODE ON)
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# | OBJECT LIBRARIES (INTERMEDIATE) | # | OBJECT LIBRARIES (INTERMEDIATE) |
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# lwip_obj
add_library (lwip_obj OBJECT ${lwipSrcGlob})
# zto_obj # zto_obj
add_library (zto_obj OBJECT ${ztoSrcGlob}) add_library (zto_obj OBJECT ${zerotiercoreSrcGlob})
set_target_properties (zto_obj PROPERTIES COMPILE_FLAGS "${SILENCE} -std=c++11 -DZT_USE_MINIUPNPC=1 -DZT_SOFTWARE_UPDATE_DEFAULT=0")
if (BUILDING_WIN) if (BUILDING_WIN)
target_link_libraries (zto_obj ws2_32) target_link_libraries (zto_obj ws2_32)
target_link_libraries (zto_obj ${shlwapi_LIBRARY_PATH}) target_link_libraries (zto_obj ${shlwapi_LIBRARY_PATH})
target_link_libraries (zto_obj ${iphlpapi_LIBRARY_PATH}) target_link_libraries (zto_obj ${iphlpapi_LIBRARY_PATH})
endif () endif ()
# http_obj
add_library (http_obj OBJECT "${ZTO_SRC_DIR}/ext/http-parser/http_parser.c") # libnatpmp_obj
add_library (libnatpmp_obj OBJECT ${libnatpmpSrcGlob})
set_target_properties (libnatpmp_obj PROPERTIES COMPILE_FLAGS "")
# miniupnpc_obj
add_library (miniupnpc_obj OBJECT ${libminiupnpcSrcGlob})
target_compile_definitions(miniupnpc_obj PRIVATE MACOSX ZT_USE_MINIUPNPC MINIUPNP_STATICLIB _DARWIN_C_SOURCE MINIUPNPC_SET_SOCKET_TIMEOUT MINIUPNPC_GET_SRC_ADDR _BSD_SOURCE _DEFAULT_SOURCE MINIUPNPC_VERSION_STRING=\"2.0\" UPNP_VERSION_STRING=\"UPnP/1.1\" ENABLE_STRNATPMPERR OS_STRING=\"Darwin/15.0.0\")
# lwip_obj
add_library (lwip_obj OBJECT ${lwipSrcGlob})
set_target_properties (lwip_obj PROPERTIES COMPILE_FLAGS "")
# libzt_obj
add_library (libzt_obj OBJECT ${libztSrcGlob})
set_target_properties (libzt_obj PROPERTIES COMPILE_FLAGS "-std=c++11")
add_library (lwip_pic ${lwipSrcGlob})
set_target_properties (lwip_pic PROPERTIES POSITION_INDEPENDENT_CODE ON)
add_library (zto_pic ${zerotiercoreSrcGlob})
set_target_properties (zto_pic PROPERTIES COMPILE_FLAGS "${SILENCE} -std=c++11")
set_target_properties (zto_pic PROPERTIES POSITION_INDEPENDENT_CODE ON)
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# | LIBZT BUILD TARGETS (FINAL PRODUCT) | # | BUILD TARGETS (FINAL PRODUCT) |
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# static # libzerotiercore.a
add_library (${STATIC_LIB_NAME} STATIC add_library (zerotiercore STATIC $<TARGET_OBJECTS:zto_obj>)
$<TARGET_OBJECTS:lwip_obj> set_target_properties (zerotiercore PROPERTIES
$<TARGET_OBJECTS:zto_obj> OUTPUT_NAME zerotiercore
$<TARGET_OBJECTS:http_obj> ${libztSrcGlob}) LIBRARY_OUTPUT_DIRECTORY ${INTERMEDIATE_LIBRARY_OUTPUT_PATH})
set_target_properties (${STATIC_LIB_NAME} PROPERTIES OUTPUT_NAME ${STATIC_LIB_OUTPUT_NAME})
# dynamic # libnatpmp.a
add_library (${DYNAMIC_LIB_NAME} SHARED ${libztSrcGlob}) add_library (natpmp STATIC $<TARGET_OBJECTS:libnatpmp_obj>)
set_target_properties (natpmp PROPERTIES
OUTPUT_NAME natpmp
LIBRARY_OUTPUT_DIRECTORY ${INTERMEDIATE_LIBRARY_OUTPUT_PATH})
# libminiupnpc.a
add_library (miniupnpc STATIC $<TARGET_OBJECTS:miniupnpc_obj>)
set_target_properties (miniupnpc PROPERTIES
OUTPUT_NAME miniupnpc
LIBRARY_OUTPUT_DIRECTORY ${INTERMEDIATE_LIBRARY_OUTPUT_PATH})
# liblwip.a
add_library (lwip STATIC $<TARGET_OBJECTS:lwip_obj>)
set_target_properties (lwip PROPERTIES
OUTPUT_NAME lwip
LIBRARY_OUTPUT_DIRECTORY ${INTERMEDIATE_LIBRARY_OUTPUT_PATH})
# libzt.a
add_library (zt STATIC $<TARGET_OBJECTS:libzt_obj>
$<TARGET_OBJECTS:zto_obj>
$<TARGET_OBJECTS:libnatpmp_obj>
$<TARGET_OBJECTS:miniupnpc_obj>
$<TARGET_OBJECTS:lwip_obj>)
set_target_properties (zt PROPERTIES
OUTPUT_NAME zt
LIBRARY_OUTPUT_DIRECTORY ${INTERMEDIATE_LIBRARY_OUTPUT_PATH})
# libzt.so/dylib/dll
add_library (zt-shared SHARED ${libztSrcGlob})
message (STATUS ${libztSrcGlob}) message (STATUS ${libztSrcGlob})
target_link_libraries (${DYNAMIC_LIB_NAME} lwip_pic zto_pic http_pic) target_link_libraries (zt-shared lwip_pic zto_pic)
set_target_properties (${DYNAMIC_LIB_NAME} PROPERTIES OUTPUT_NAME ${DYNAMIC_LIB_OUTPUT_NAME}) set_target_properties (zt-shared PROPERTIES COMPILE_FLAGS "${SILENCE} -std=c++11 -DZT_SDK")
set_target_properties (${DYNAMIC_LIB_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS true) set_target_properties (zt-shared PROPERTIES OUTPUT_NAME ${DYNAMIC_LIB_OUTPUT_NAME}
WINDOWS_EXPORT_ALL_SYMBOLS true)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
if (BUILDING_ANDROID) if (BUILDING_ANDROID)
target_link_libraries (${DYNAMIC_LIB_NAME} android log) target_link_libraries (zt-shared android log)
endif ()
if (BUILDING_WIN)
target_link_libraries (${STATIC_LIB_NAME} ws2_32)
target_link_libraries (${STATIC_LIB_NAME} ${shlwapi_LIBRARY_PATH})
target_link_libraries (${STATIC_LIB_NAME} ${iphlpapi_LIBRARY_PATH})
target_link_libraries (${DYNAMIC_LIB_NAME} ws2_32)
target_link_libraries (${DYNAMIC_LIB_NAME} ${shlwapi_LIBRARY_PATH})
target_link_libraries (${DYNAMIC_LIB_NAME} ${iphlpapi_LIBRARY_PATH})
endif ()
if (BUILDING_LINUX OR BUILDING_DARWIN)
target_link_libraries (${STATIC_LIB_NAME} pthread)
target_link_libraries (${DYNAMIC_LIB_NAME} pthread)
endif ()
# xcode framework
if (IN_XCODE)
add_library(${XCODE_FRAMEWORK_NAME} STATIC
$<TARGET_OBJECTS:lwip_obj>
$<TARGET_OBJECTS:zto_obj>
$<TARGET_OBJECTS:http_obj>
${libztSrcGlob}
${frameworkHeaderGlob})
set_target_properties(${XCODE_FRAMEWORK_NAME} PROPERTIES
FRAMEWORK TRUE
FRAMEWORK_VERSION A
DEFINES_MODULE TRUE
MACOSX_FRAMEWORK_IDENTIFIER com.cmake.${XCODE_FRAMEWORK_NAME}
MODULE_MAP "~/op/zt/libzt/packages/module.modulemap"
PUBLIC_HEADER "${frameworkHeaderGlob}"
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer"
)
endif () endif ()
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# | TEST APPLICATIONS AND EXAMPLES | # | EXECUTABLES |
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
if (SHOULD_BUILD_TESTS) if (SHOULD_BUILD_TESTS)
# foreach (testsourcefile ${ExampleAppSrcGlob}) add_executable (example ${PROJ_DIR}/test/example.cpp)
# string (REPLACE ".cpp" "" testname ${testsourcefile}) target_link_libraries(example zt)
# get_filename_component (testname ${testname} NAME)
# add_executable (${testname} ${testsourcefile})
# if (BUILDING_WIN)
# target_link_libraries (${testname} ${STATIC_LIB_NAME})
# else ()
# target_link_libraries (${testname} ${STATIC_LIB_NAME} pthread dl)
# endif ()
# endforeach (testsourcefile ${ExampleAppSrcGlob})
if (NOT BUILDING_WIN) # only necessary for raw driver development add_executable (selftest ${PROJ_DIR}/test/selftest.cpp)
# selftest target_link_libraries(selftest zt)
#add_executable (selftest ${PROJ_DIR}/test/selftest.cpp) set_target_properties (selftest PROPERTIES COMPILE_FLAGS "${SILENCE} -D__SELFTEST__")
#target_compile_options (selftest PRIVATE -D__SELFTEST__) endif ()
#if (BUILDING_WIN)
# target_link_libraries (selftest ${STATIC_LIB_NAME} ${ws2_32_LIBRARY_PATH} ${shlwapi_LIBRARY_PATH} ${iphlpapi_LIBRARY_PATH})
#else ()
# target_link_libraries (selftest ${STATIC_LIB_NAME} pthread)
#endif ()
# nativetest
#add_executable (nativetest ${PROJ_DIR}/test/selftest.cpp)
#target_compile_options (nativetest PRIVATE -D__NATIVETEST__)
endif ()
endif ()

44
Jenkinsfile vendored
View File

@@ -1,44 +0,0 @@
#!/usr/bin/env groovy
node('master') {
checkout scm
def changelog = getChangeLog currentBuild
mattermostSend "Building ${env.JOB_NAME} #${env.BUILD_NUMBER} \n Change Log: \n ${changelog}"
}
parallel 'centos7': {
node('centos7') {
try {
checkout scm
sh 'git submodule update --init'
stage('linux') {
sh 'cmake -H. -Bbuild; cmake --build build'
}
}
catch (err) {
currentBuild.result = "FAILURE"
slackSend color: '#ff0000', message: "${env.JOB_NAME} broken on linux (<${env.BUILD_URL}|Open>)"
throw err
}
}
},
'macOS': {
node('macOS') {
unlockKeychainMac "~/Library/Keychains/login.keychain-db"
try {
checkout scm
sh 'git submodule update --init'
stage('macOS') {
sh 'cmake -H. -Bbuild; cmake --build build'
}
}
catch (err) {
currentBuild.result = "FAILURE"
slackSend color: '#ff0000', message: "${env.JOB_NAME} broken on macOS (<${env.BUILD_URL}|Open>)"
throw err
}
}
}
mattermostSend color: "#00ff00", message: "${env.JOB_NAME} #${env.BUILD_NUMBER} Complete (<${env.BUILD_URL}|Show More...>)"

View File

@@ -1,50 +1,68 @@
# NOTE: This file only exists as a convenience for cleaning and building #
# products for release. To build, use CMake. Instructions in README.md # ZeroTier SDK - Network Virtualization Everywhere
# Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
#
# 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 <http://www.gnu.org/licenses/>.
#
# --
#
# You can be released from the requirements of the license by purchasing
# a commercial license. Buying such a license is mandatory as soon as you
# develop commercial closed-source software that incorporates or links
# directly against ZeroTier software without disclosing the source code
# of your own application.
#
ifeq ($(OS),Windows_NT) ifeq ($(OS),Windows_NT)
DIST_BUILD_SCRIPT := packages\dist.bat DIST_BUILD_SCRIPT := ports\dist.bat
CLEAN_SCRIPT := packages\clean.bat CLEAN_SCRIPT := ports\clean.bat
else else
DIST_BUILD_SCRIPT := ./packages/dist.sh DIST_BUILD_SCRIPT := ./ports/dist.sh
CLEAN_SCRIPT := ./packages/clean.sh CLEAN_SCRIPT := ./ports/clean.sh
PACKAGE_SCRIPT := ./packages/package.sh PACKAGE_SCRIPT := ./ports/package.sh
endif endif
.PHONY: clean CONCURRENT_BUILD_JOBS=2
clean:
$(CLEAN_SCRIPT)
# Build and package everything
# This command shall be run twice:
# (1) Generates projects
# <perform any required modifications>
# (2) Build products and package everything
.PHONY: dist
dist: patch
$(DIST_BUILD_SCRIPT)
.PHONY: package
package:
$(PACKAGE_SCRIPT)
# Initialize submodules and apply patches
.PHONY: all
all: update patch
cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Release
cmake --build build
# Remove any CMake-generated library-building projects
clean_packages:
rm -rf packages/xcode_ios
rm -rf packages/xcode_macos
.PHONY: update
update:
git submodule update --init --recursive
# Patch submodules # Patch submodules
patch: patch:
-git -C ext/lwip apply ../lwip.patch -git -C ext/lwip apply ../lwip.patch
-git -C ext/lwip-contrib apply ../lwip-contrib.patch -git -C ext/lwip-contrib apply ../lwip-contrib.patch
-git -C ext/ZeroTierOne apply ../ZeroTierOne.patch #-git -C ext/ZeroTierOne apply ../ZeroTierOne.patch
.PHONY: clean
clean:
rm -rf bin staging generated
all: debug release
release:
-mkdir generated
cmake -H. -Bgenerated/release -DCMAKE_BUILD_TYPE=Release
cmake --build generated/release -j $(CONCURRENT_BUILD_JOBS)
debug:
-mkdir generated
cmake -H. -Bgenerated/debug -DCMAKE_BUILD_TYPE=Debug
cmake --build generated/debug -j $(CONCURRENT_BUILD_JOBS)
# dist:
# Build and package everything
# This command shall be run twice:
# (1) Generates projects
# <perform any required modifications>
# (2) Build products and package everything
.PHONY: dist
dist: patch
$(DIST_BUILD_SCRIPT)

View File

@@ -26,7 +26,9 @@ Java JNI API: [ZeroTier.java](packages/android/app/src/main/java/ZeroTier.java)
### C++ Example ### C++ Example
``` ```
#include <sys/socket.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <netinet/in.h>
#include "libzt.h" #include "libzt.h"
@@ -36,15 +38,14 @@ int main()
char *remoteIp = "10.8.8.42"; char *remoteIp = "10.8.8.42";
int remotePort = 8080; int remotePort = 8080;
int fd, err = 0; int fd, err = 0;
struct zts_sockaddr_in addr; struct sockaddr_in addr;
addr.sin_family = ZTS_AF_INET; addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(remoteIp); addr.sin_addr.s_addr = inet_addr(remoteIp);
addr.sin_port = htons(remotePort); addr.sin_port = htons(remotePort);
zts_startjoin("path", 0xc7cd7c981b0f52a2); // config path, network ID zts_startjoin("path", 0xc7cd7c981b0f52a2); // config path, network ID
printf("nodeId=%llx\n", zts_get_node_id());
if ((fd = zts_socket(ZTS_AF_INET, ZTS_SOCK_STREAM, 0)) < 0) { if ((fd = zts_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("error creating socket\n"); printf("error creating socket\n");
} }
if ((err = zts_connect(fd, (const struct sockaddr *)&addr, sizeof(addr))) < 0) { if ((err = zts_connect(fd, (const struct sockaddr *)&addr, sizeof(addr))) < 0) {

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ExampleAndroidApp</name>
<comment>Project ExampleAndroidApp created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,2 @@
connection.project.dir=
eclipse.preferences.version=1

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-9/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>app</name>
<comment>Project app created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,2 @@
connection.project.dir=..
eclipse.preferences.version=1

View File

@@ -20,15 +20,25 @@ android {
minifyEnabled false minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
} }
release {
debuggable true
jniDebuggable true
minifyEnabled false
}
} }
} }
dependencies { dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
implementation files('libs/libzt-android-debug.aar') implementation files('libs/libzt-android-debug.aar')
implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3' implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation("com.squareup.okhttp3:okhttp:3.12.0")
implementation 'com.android.support.constraint:constraint-layout:1.1.2' implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.bumptech.glide:glide:4.6.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
} }

View File

@@ -0,0 +1,79 @@
package com.example.exampleandroidapp;
import com.zerotier.libzt.ZeroTierSocketFactory;
import com.zerotier.libzt.ZeroTier;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.concurrent.ThreadLocalRandom;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HTTPWorker extends Thread {
@Override
public void run() {
long tid = Thread.currentThread().getId();
// Test: Perform randomly-delayed HTTP GET requests
if (true) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.socketFactory(new ZeroTierSocketFactory());
OkHttpClient client = builder.build();
Request request1 = new Request.Builder()
.url("http://11.7.7.223:80/warandpeace.txt")
.build();
Request request2 = new Request.Builder()
.url("http://11.7.7.223:8082/pumpkin.jpg")
.build();
RequestBody formBody = new FormBody.Builder()
.add("message", "Your message")
.build();
Request request3 = new Request.Builder()
.url("http://11.7.7.223:8082/")
.post(formBody)
.build();
long i = 0;
for (;;) {
try {
System.out.println("PEER STATUS IS = " + ZeroTier.get_peer_status(0x7caea82fc4L));
int randomNum = ThreadLocalRandom.current().nextInt(0, 2 + 1);
i++;
Response response = null;
if (randomNum == 0) {
response = client.newCall(request1).execute();
}
if (randomNum == 1) {
//response = client.newCall(request2).execute();
response = client.newCall(request1).execute();
}
if (randomNum == 2) {
//response = client.newCall(request3).execute();
response = client.newCall(request1).execute();
//System.out.println(tid+"::POST");
//continue;
}
InputStream in = response.body().byteStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = in.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
System.out.println(tid+"::GET: i="+i+", len="+buffer.toByteArray().length);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
//System.exit(0);
}
}
}
}
}

View File

@@ -1,103 +1,442 @@
package com.example.exampleandroidapp; package com.example.exampleandroidapp;
import java.util.concurrent.ThreadLocalRandom;
import java.io.ByteArrayOutputStream;
import java.net.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.os.Bundle;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.FormBody;
import com.zerotier.libzt.ZeroTier; import com.zerotier.libzt.ZeroTier;
import com.zerotier.libzt.ZTSocketAddress; import com.zerotier.libzt.ZeroTierSocket;
import com.zerotier.libzt.ZTFDSet; import com.zerotier.libzt.ZeroTierSocketFactory;
import com.zerotier.libzt.ZeroTierSSLSocketFactory;
//import com.zerotier.libzt.ZeroTierEventListener;
import com.zerotier.libzt.ZeroTierSocketImplFactory;
import com.example.exampleandroidapp.MyZeroTierEventListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
//import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import javax.net.ssl.SSLContext;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Callback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
String requestURL = "http://11.7.7.223:80/";
// Used to load the 'native-lib' library on application startup. private static String createDataSize(int msgSize) {
static { StringBuilder sb = new StringBuilder(msgSize);
System.loadLibrary("zt-shared"); for (int i=0; i<msgSize; i++) {
sb.append('a');
}
return sb.toString();
} }
/*
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
String HTTP_POST(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.socketFactory(new ZeroTierSocketFactory());
OkHttpClient client = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
void HTTP_GET() throws IOException {
}
String sampleJson(String player1, String player2) {
return "{'winCondition':'HIGH_SCORE',"
+ "'name':'Bowling',"
+ "'round':4,"
+ "'lastSaved':1367702411696,"
+ "'dateStarted':1367702378785,"
+ "'players':["
+ "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
+ "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
+ "]}";
}
*/
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
final ZeroTier zt = new ZeroTier();
new Thread(new Runnable() { // WD TEST
public void run() { if (true) {
final String path = getApplicationContext().getFilesDir() + "/zerotier"; System.out.println("Starting ZeroTier...");
long nwid = 0xe42a7f55c2b9be61L; MyZeroTierEventListener listener = new MyZeroTierEventListener();
ZeroTier.start(getApplicationContext().getFilesDir() + "/zerotier3", listener, 9994);
// Test modes while (listener.isOnline == false) {
boolean blocking_start_call = true; try {
boolean client_mode = true; Thread.sleep(100);
boolean tcp = false; } catch (Exception e) {
boolean loop = true;
int fd = -1, client_fd = -1, err, r, w, length = 0, flags = 0;
byte[] rxBuffer;
byte[] txBuffer = "welcome to the machine".getBytes();
String remoteAddrStr = "172.28.221.116";
String localAddrStr = "1.2.3.4";
int portNo = 4040;
ZTSocketAddress remoteAddr, localAddr;
ZTSocketAddress sockname = new ZTSocketAddress();
ZTSocketAddress addr = new ZTSocketAddress();
// METHOD 1 (easy)
// Blocking call that waits for all components of the service to start
System.out.println("Starting ZT service...");
if (blocking_start_call) {
zt.startjoin(path, nwid);
}
System.out.println("ZT service ready.");
// Device/Node address info
System.out.println("path=" + zt.get_path());
long nodeId = zt.get_node_id();
System.out.println("nodeId=" + Long.toHexString(nodeId));
int numAddresses = zt.get_num_assigned_addresses(nwid);
System.out.println("this node has (" + numAddresses + ") assigned addresses on network " + Long.toHexString(nwid));
for (int i=0; i<numAddresses; i++) {
zt.get_address_at_index(nwid, i, sockname);
//System.out.println("address[" + i + "] = " + sockname.toString()); // ip:port
System.out.println("address[" + i + "] = " + sockname.toCIDR());
}
zt.get_6plane_addr(nwid, nodeId, sockname);
System.out.println("6PLANE address = " + sockname.toCIDR());
System.out.println("mode:tcp");
if ((fd = zt.socket(zt.AF_INET, zt.SOCK_STREAM, 0)) < 0) {
System.out.println("error creating socket");
return;
}
// CLIENT
int lengthToRead;
if (client_mode) {
remoteAddr = new ZTSocketAddress(remoteAddrStr, portNo);
if ((err = zt.connect(fd, remoteAddr)) < 0) {
System.out.println("error connecting (err=" + err + ")");
return;
}
int n = 20000;
String in = "echo!";
String echo_msg = "";
for (int i = 0; i < n; i += 1) {
echo_msg += in;
}
w = zt.write(fd, echo_msg.getBytes());
//rxBuffer = new byte[100];
//lengthToRead = 100;
System.out.println("w="+w);
//System.out.println("reading bytes...");
//r = zt.read(fd, rxBuffer, lengthToRead);
//System.out.println("r="+r);
//System.out.println("string="+new String(rxBuffer));
} }
} }
System.out.println("joining network...");
ZeroTier.join(0x0);
System.out.println("waiting for callback");
while (listener.isNetworkReady == false) {
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
//
System.exit(0);
}
System.out.println("Starting ZeroTier...");
MyZeroTierEventListener listener = new MyZeroTierEventListener();
ZeroTier.start(getApplicationContext().getFilesDir() + "/zerotier3", listener, 9994);
//System.out.println("ZTSDK nodeId=" + Long.toHexString(ZeroTier.get_node_id()));
while (listener.isOnline == false) {
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
System.out.println("joining network...");
ZeroTier.join(0x0);
System.out.println("waiting for callback");
while (listener.isNetworkReady == false) {
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
// Start threads
List<Thread> threads = new ArrayList<>();
for(int i = 0;i < 5;i++){
try {
Thread.sleep(500);
} catch (Exception e) {}
HTTPWorker thread = new HTTPWorker();
thread.start();
threads.add(thread);
}
System.out.println("sleeping...");
try {
Thread.sleep(60000000);
} catch (Exception e) {}
System.exit(0);
// Test: setsockopt() and getsockopt() [non-exhaustive]
/*
if (true) {
try {
ZeroTierSocket zts = new ZeroTierSocket();
zts.connect(new InetSocketAddress("11.7.7.223", 8082));
zts.setSoTimeout(1337);
int to = zts.getSoTimeout();
assert to == 1337;
} catch (Exception e) {
}
}
*/
// Test: Perform randomly-delayed HTTP GET requests
if (false) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.socketFactory(new ZeroTierSocketFactory());
OkHttpClient client = builder.build();
Request request1 = new Request.Builder()
.url("http://11.7.7.223:8082/")
.build();
long i = 0;
for (;;) {
try {
Thread.sleep((long)(Math.random() * 250));
Response response = client.newCall(request1).execute();
i++;
System.out.println("GET: i="+i+", len="+response.toString().length());
//response.close();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
e.printStackTrace();
}
}
}
// Test: Perform randomly-delayed HTTP GET requests
if (true) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.socketFactory(new ZeroTierSocketFactory());
OkHttpClient client = builder.build();
Request request1 = new Request.Builder()
.url("http://11.7.7.223:80/warandpeace.txt")
.header("Transfer-Encoding", "chunked")
//.header("Connection","close")
.build();
Request request2 = new Request.Builder()
.url("http://11.7.7.223:8082/pumpkin.jpg")
.header("Transfer-Encoding", "chunked")
.header("Connection","close")
.build();
String postMessage = "what?";
try {
postMessage = new String(createDataSize(1024).getBytes(), "UTF8");
}
catch (Exception e)
{
System.out.println(e);
}
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
okhttp3.RequestBody body = RequestBody.create(JSON, postMessage);
//RequestBody formBody = new FormBody.Builder()
// .add("message", postMessage)
// .build();
Request request3 = new Request.Builder()
.url("http://11.7.7.223:8082/")
//.retryOnConnectionFailure(true)
.header("Transfer-Encoding", "chunked")
.header("Connection","close")
//.header("Connection","keep-alive")
.post(body)
.build();
long i = 0;
for (;;) {
try {
System.out.println("iteration="+i);
int randomNum = ThreadLocalRandom.current().nextInt(0, 2 + 1);
Thread.sleep(10);
i++;
Response response = null;
if (randomNum == 0) {
System.out.println("(0) GET: war");
response = client.newCall(request1).execute();
}
if (randomNum == 1) {
System.out.println("(1) GET: pumpkin");
response = client.newCall(request2).execute();
}
if (randomNum == 2) {
System.out.println("(2) POST: data");
response = client.newCall(request3).execute();
response.close();
continue;
}
InputStream in = response.body().byteStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = in.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
System.out.println("GET: i="+i+", len="+buffer.toByteArray().length);
response.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
}
// Test: Perform randomly-delayed HTTP GET requests
if (true) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.socketFactory(new ZeroTierSocketFactory());
OkHttpClient client = builder.build();
Request request = new Request.Builder()
.url(requestURL+"warandpeace.txt")
.build();
long i = 0;
for (;;) {
try {
//Thread.sleep((long)(Math.random()) );
//System.out.println("iteration="+i);
i++;
Response response = client.newCall(request).execute();
//System.out.println(response.body().string());
InputStream in = response.body().byteStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = in.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
System.out.println("\tCOMPLETE, i="+i+", len="+buffer.toByteArray().length);
/*
//Bitmap bitmap = BitmapFactory.decodeByteArray(buffer.toByteArray(), 0, buffer.toByteArray().length);
//ImageView imageView = (ImageView) findViewById(R.id.imageView);
//imageView.setImageBitmap(bitmap);
*/
/*
BufferedInputStream bufferedInputStream = new BufferedInputStream(in);
Bitmap bitmap=BitmapFactory.decodeStream(bufferedInputStream);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
*/
//
// Thread.sleep(5000);
//response.close();
} catch (Exception e) {
System.out.println("EXCEPTION:"+e);
//System.exit(0);
e.printStackTrace();
}
}
}
// ...
// Test #2: HttpURLConnection
if (false)
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext context = null;
// Set runtime default socket implementation factory
try {
//Socket.setSocketImplFactory(new ZeroTierSocketImplFactory());
//SSLSocket.setSocketImplFactory(new ZeroTierSocketImplFactory());
context = SSLContext.getInstance("SSL");
//context.init(null, null, null);
context.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
ZeroTierSSLSocketFactory customSocketFactory = new ZeroTierSSLSocketFactory(context.getSocketFactory());
HttpsURLConnection.setDefaultSSLSocketFactory(customSocketFactory);
// Test HTTP client
String GET_URL = "https://10.6.6.152";
String USER_AGENT = "Mozilla/5.0";
try {
URL obj = new URL(GET_URL);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setSSLSocketFactory(customSocketFactory);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
System.out.println("neat?");
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK)
{
// success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.out.println("GET request failed");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
} }
).start();
} }
} }

View File

@@ -0,0 +1,82 @@
package com.example.exampleandroidapp;
import com.zerotier.libzt.ZeroTier;
import com.zerotier.libzt.ZeroTierEventListener;
public class MyZeroTierEventListener implements ZeroTierEventListener {
public boolean isNetworkReady = false;
public boolean isOnline = false;
public void onZeroTierEvent(long id, int eventCode)
{
if (eventCode == ZeroTier.EVENT_NODE_UP) {
System.out.println("EVENT_NODE_UP: nodeId=" + Long.toHexString(id));
}
if (eventCode == ZeroTier.EVENT_NODE_ONLINE) {
// The core service is running properly and can join networks now
System.out.println("EVENT_NODE_ONLINE: nodeId=" + Long.toHexString(ZeroTier.get_node_id()));
isOnline = true;
}
if (eventCode == ZeroTier.EVENT_NODE_OFFLINE) {
// Network does not seem to be reachable by any available strategy
System.out.println("EVENT_NODE_OFFLINE");
}
if (eventCode == ZeroTier.EVENT_NODE_DOWN) {
// Called when the node is shutting down
System.out.println("EVENT_NODE_DOWN");
}
if (eventCode == ZeroTier.EVENT_NODE_IDENTITY_COLLISION) {
// Another node with this identity already exists
System.out.println("EVENT_NODE_IDENTITY_COLLISION");
}
if (eventCode == ZeroTier.EVENT_NODE_UNRECOVERABLE_ERROR) {
// Try again
System.out.println("EVENT_NODE_UNRECOVERABLE_ERROR");
}
if (eventCode == ZeroTier.EVENT_NODE_NORMAL_TERMINATION) {
// Normal closure
System.out.println("EVENT_NODE_NORMAL_TERMINATION");
}
if (eventCode == ZeroTier.EVENT_NETWORK_READY_IP4) {
// We have at least one assigned address and we've received a network configuration
System.out.println("ZTS_EVENT_NETWORK_READY_IP4: nwid=" + Long.toHexString(id));
isNetworkReady = true;
}
if (eventCode == ZeroTier.EVENT_NETWORK_READY_IP6) {
// We have at least one assigned address and we've received a network configuration
System.out.println("ZTS_EVENT_NETWORK_READY_IP6: nwid=" + Long.toHexString(id));
isNetworkReady = true;
}
if (eventCode == ZeroTier.EVENT_NETWORK_DOWN) {
// Someone called leave(), we have no assigned addresses, or otherwise cannot use this interface
System.out.println("EVENT_NETWORK_DOWN: nwid=" + Long.toHexString(id));
}
if (eventCode == ZeroTier.EVENT_NETWORK_REQUESTING_CONFIG) {
// Waiting for network configuration
System.out.println("EVENT_NETWORK_REQUESTING_CONFIG: nwid=" + Long.toHexString(id));
}
if (eventCode == ZeroTier.EVENT_NETWORK_OK) {
// Config received and this node is authorized for this network
System.out.println("EVENT_NETWORK_OK: nwid=" + Long.toHexString(id));
}
if (eventCode == ZeroTier.EVENT_NETWORK_ACCESS_DENIED) {
// You are not authorized to join this network
System.out.println("EVENT_NETWORK_ACCESS_DENIED: nwid=" + Long.toHexString(id));
}
if (eventCode == ZeroTier.EVENT_NETWORK_NOT_FOUND) {
// The virtual network does not exist
System.out.println("EVENT_NETWORK_NOT_FOUND: nwid=" + Long.toHexString(id));
}
if (eventCode == ZeroTier.EVENT_NETWORK_CLIENT_TOO_OLD) {
// The core version is too old
System.out.println("EVENT_NETWORK_CLIENT_TOO_OLD: nwid=" + Long.toHexString(id));
}
if (eventCode == ZeroTier.EVENT_PEER_P2P) {
System.out.println("EVENT_PEER_P2P: id=" + Long.toHexString(id));
}
if (eventCode == ZeroTier.EVENT_PEER_RELAY) {
System.out.println("EVENT_PEER_RELAY: id=" + Long.toHexString(id));
}
}
}

View File

@@ -15,4 +15,12 @@
app:layout_constraintRight_toRightOf="parent" app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" /> app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/imageView"
android:layout_width="136dp"
android:layout_height="213dp"
app:srcCompat="@android:color/transparent"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="16dp" />
</android.support.constraint.ConstraintLayout> </android.support.constraint.ConstraintLayout>

View File

@@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2027
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExampleWindowsCSharpApp", "ExampleWindowsCSharpApp\ExampleWindowsCSharpApp.csproj", "{74F548E3-64FD-41FF-9416-0AE1FC24E8BE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{74F548E3-64FD-41FF-9416-0AE1FC24E8BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{74F548E3-64FD-41FF-9416-0AE1FC24E8BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{74F548E3-64FD-41FF-9416-0AE1FC24E8BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{74F548E3-64FD-41FF-9416-0AE1FC24E8BE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BC236939-C661-4FEB-8935-4A61C2ECEC19}
EndGlobalSection
EndGlobal

View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>

View File

@@ -1,54 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{74F548E3-64FD-41FF-9416-0AE1FC24E8BE}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ExampleWindowsCSharpApp</RootNamespace>
<AssemblyName>ExampleWindowsCSharpApp</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="libzt.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -1,118 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using ZeroTier;
namespace ExampleWindowsCSharpApp
{
class Program
{
static void Main(string[] args)
{
ulong nwid = 0xe4da7455b2b9ee6a;
Console.Write("waiting for libzt to come online...\n");
libzt.zts_startjoin("config_path", nwid);
Console.Write("I am " + libzt.zts_get_node_id().ToString("X") +"\n");
Console.Write("ZT ready\n");
int fd;
int err = 0;
bool clientMode = false;
if ((fd = libzt.zts_socket(2, 1, 0)) < 0)
{
Console.Write("error creating socket\n");
}
// CLIENT
if (clientMode == true)
{
string remoteAddrStr = "172.28.221.116";
Int16 remotePort = 2323;
// Convert managed address object to pointer for unmanaged code
libzt.SockAddrIn addr = new libzt.SockAddrIn();
addr.Family = (byte)libzt.SockAddrFamily.Inet;
addr.Port = IPAddress.HostToNetworkOrder((Int16)remotePort);
addr.Addr = (uint)IPAddress.Parse(remoteAddrStr).Address;
IntPtr addrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(libzt.SockAddrIn)));
Marshal.StructureToPtr(addr, addrPtr, false);
int addrlen = Marshal.SizeOf(addr);
if ((err = libzt.zts_connect(fd, addrPtr, addrlen)) < 0)
{
Console.Write("error connecting to remote server\n");
}
// Send message
string msgStr = "Hello from C#!";
byte[] msgBuf = Encoding.ASCII.GetBytes(msgStr);
int buflen = System.Text.ASCIIEncoding.ASCII.GetByteCount(msgStr);
if ((err = libzt.zts_write(fd, msgBuf, buflen)) < 0)
{
Console.Write("error writing to remote server\n");
}
libzt.zts_close(fd);
Marshal.FreeHGlobal(addrPtr);
}
else // SERVER
{
string localAddrStr = "0.0.0.0";
Int16 bindPort = 5050;
libzt.SockAddrIn addr = new libzt.SockAddrIn();
addr.Family = (byte)libzt.SockAddrFamily.Inet;
addr.Port = IPAddress.HostToNetworkOrder((Int16)bindPort);
addr.Addr = (uint)IPAddress.Parse(localAddrStr).Address;
IntPtr addrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(libzt.SockAddrIn)));
Marshal.StructureToPtr(addr, addrPtr, false);
int addrlen = Marshal.SizeOf(addr);
if ((err = libzt.zts_bind(fd, addrPtr, addrlen)) < 0)
{
Console.Write("error binding to local port\n");
}
if ((err = libzt.zts_listen(fd, 1)) < 0)
{
Console.Write("error putting socket in listening state\n");
}
int accfd;
Console.Write("waiting to accept connection...\n");
if ((accfd = libzt.zts_accept(fd, IntPtr.Zero, IntPtr.Zero)) < 0)
{
Console.Write("error accepting incoming connection\n");
}
Console.Write("accepted connection!\n");
// Read message
byte[] msgBuf = new byte[32];
int buflen = 32;
Console.Write("reading from client...\n");
if ((err = libzt.zts_read(accfd, msgBuf, buflen)) < 0)
{
Console.Write("error reading from remote client\n");
}
Console.Write("read " + err + " bytes from client\n");
string msgStr = System.Text.Encoding.UTF8.GetString(msgBuf, 0, msgBuf.Length);
Console.Write("msg from client = " + msgStr + "\n");
libzt.zts_close(fd);
libzt.zts_close(accfd);
Marshal.FreeHGlobal(addrPtr);
}
Console.Write("fd=" + fd);
Console.Write("wrote=" + err);
libzt.zts_stop();
}
}
}

View File

@@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ExampleWindowsCSharpApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExampleWindowsCSharpApp")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("74f548e3-64fd-41ff-9416-0ae1fc24e8be")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -1,184 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace ZeroTier
{
static class libzt
{
public enum SockAddrFamily
{
Inet = 2,
Inet6 = 10
}
[StructLayout(LayoutKind.Sequential)]
public struct SockAddr
{
public ushort Family;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)]
public byte[] Data;
};
[StructLayout(LayoutKind.Sequential)]
public struct SockAddrIn
{
byte len; // unique to lwIP
public byte Family;
public Int16 Port;
public uint Addr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] Zero;
}
[StructLayout(LayoutKind.Sequential)]
public struct SockAddrIn6
{
public ushort Family;
public ushort Port;
public uint FlowInfo;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] Addr;
public uint ScopeId;
};
/****************************************************************************/
/* ZeroTier Service Controls */
/****************************************************************************/
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_start(string path);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_startjoin(string path, ulong nwid);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void zts_stop();
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void zts_join(ulong nwid);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void zts_leave(ulong nwid);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void zts_get_homepath(string homePath, int len);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern Int64 zts_get_node_id();
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_running();
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_has_address(ulong nwid);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_get_address(ulong nwid, IntPtr addr, int address_family);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void zts_get_6plane_addr(IntPtr addr, string nwid, string nodeId);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void zts_get_rfc4193_addr(IntPtr addr, string nwid, string nodeId);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern long zts_get_peer_count();
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_get_peer_address(string peer, ulong nodeId);
/****************************************************************************/
/* Socket-like API */
/****************************************************************************/
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_socket(int socket_family, int socket_type, int protocol);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_connect(int fd, IntPtr addr, int addrlen);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_bind(int fd, IntPtr addr, int addrlen);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_listen(int fd, int backlog);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_accept(int fd, IntPtr addr, IntPtr addrlen);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_setsockopt(int fd, int level, int optname, IntPtr optval, int optlen);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_getsockopt(int fd, int level, int optname, IntPtr optval, IntPtr optlen);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_getsockname(int fd, IntPtr addr, IntPtr addrlen);
/*
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_getpeername(int fd, System.IntPtr addr, IntPtr addrlen);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_gethostname(string name, int len);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_sethostname(string name, int len);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern IntPtr *zts_gethostbyname(string name);
*/
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_close(int fd);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_select(int nfds, IntPtr readfds, IntPtr writefds, IntPtr exceptfds, IntPtr timeout);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_fcntl(int fd, int cmd, int flags);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_ioctl(int fd, ulong request, IntPtr argp);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_send(int fd, byte[] buf, int len, int flags);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_sendto(int fd, byte[] buf, int len, int flags, IntPtr addr, int addrlen);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_sendmsg(int fd, byte[] msg, int flags);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_recv(int fd, byte[] buf, int len, int flags);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_recvfrom(int fd, byte[] buf, int len, int flags, IntPtr addr, IntPtr addrlen);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_recvmsg(int fd, byte[] msg, int flags);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_read(int fd, byte[] buf, int len);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_write(int fd, byte[] buf, int len);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_shutdown(int fd, int how);
/*
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_add_dns_nameserver(System.IntPtr addr);
[DllImport("libzt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int zts_del_dns_nameserver(System.IntPtr addr);
*/
}
}

View File

@@ -1,280 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
// Simple Java example for libzt using JNI
import com.zerotier.libzt.ZeroTier;
import com.zerotier.libzt.ZTSocketAddress;
import com.zerotier.libzt.ZTFDSet;
import java.lang.Thread;
public class ExampleApp {
static { System.loadLibrary("zt"); } // load libzt.dylib or libzt.so
static void sleep(int ms)
{
try { Thread.sleep(ms); }
catch (InterruptedException e) { e.printStackTrace(); }
}
public static void main(String[] args)
{
final ZeroTier zt = new ZeroTier();
new Thread(new Runnable()
{
public void run()
{
String path = "/Users/joseph/op/zt/libzt/ztjni"; // Where node's config files are stored
long nwid = 0xa09acf7233e4b071L;
// Test modes
boolean blocking_start_call = true;
boolean client_mode = false;
boolean tcp = false;
boolean loop = true; // RX/TX multiple times
boolean idle = false; // Idle loop after node comes online. For testing reachability
boolean use_select = true;
int fd = -1, client_fd = -1, err, r, w, lengthToRead = 0, flags = 0;
byte[] rxBuffer;
byte[] txBuffer = "welcome to the machine".getBytes();
String remoteAddrStr = "11.7.7.107";
String localAddrStr = "0.0.0.0";
int portNo = 4040;
ZTSocketAddress remoteAddr, localAddr;
ZTSocketAddress sockname = new ZTSocketAddress();
ZTSocketAddress addr = new ZTSocketAddress();
// METHOD 1 (easy)
// Blocking call that waits for all components of the service to start
System.out.println("Starting ZT service...");
if (blocking_start_call) {
zt.startjoin(path, nwid);
}
// METHOD 2
// Optional. Non-blocking call to start service. You'll have to use the below process to determine
// when you are allowed to start making socket calls.
if (!blocking_start_call) {
zt.start(path, true);
while(!zt.ready()) {
try { // Wait for core service to start
Thread.sleep(250);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
System.out.println("Core started. Networks can be joined after this point");
zt.join(nwid);
// Wait for userspace stack to start, we trigger this by joining a network
while(!zt.stack_running()) {
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
System.out.println("ZT service ready.");
// Device/Node address info
System.out.println("path=" + zt.get_path());
long nodeId = zt.get_node_id();
System.out.println("nodeId=" + Long.toHexString(nodeId));
int numAddresses = zt.get_num_assigned_addresses(nwid);
System.out.println("this node has (" + numAddresses + ") assigned addresses on network " + Long.toHexString(nwid));
for (int i=0; i<numAddresses; i++) {
zt.get_address_at_index(nwid, i, sockname);
//System.out.println("address[" + i + "] = " + sockname.toString()); // ip:port
System.out.println("address[" + i + "] = " + sockname.toCIDR());
}
zt.get_6plane_addr(nwid, nodeId, sockname);
System.out.println("6PLANE address = " + sockname.toCIDR());
// Idle loop test
while(idle) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } }
// TCP
if (tcp) {
System.out.println("mode:tcp");
if ((fd = zt.socket(zt.AF_INET, zt.SOCK_STREAM, 0)) < 0) {
System.out.println("error creating socket");
return;
}
// CLIENT
if (client_mode) {
System.out.println("mode:client");
remoteAddr = new ZTSocketAddress(remoteAddrStr, portNo);
if ((err = zt.connect(fd, remoteAddr)) < 0) {
System.out.println("error connecting (err=" + err + ")");
return;
}
String echo_msg = "echo!";
w = zt.write(fd, echo_msg.getBytes());
rxBuffer = new byte[100];
lengthToRead = 100;
System.out.println("reading bytes...");
r = zt.read(fd, rxBuffer);
System.out.println("r="+r);
System.out.println("string="+new String(rxBuffer));
}
// SERVER
if (!client_mode) {
System.out.println("mode:server");
localAddr = new ZTSocketAddress(localAddrStr, portNo);
if ((err = zt.bind(fd, localAddr)) < 0) {
System.out.println("error binding socket to virtual interface");
return;
} if ((err = zt.listen(fd, 1)) < 0) {
System.out.println("error putting socket into listening state");
return;
}
remoteAddr = new ZTSocketAddress(localAddrStr, 0);
client_fd = -1;
if ((client_fd = zt.accept(fd, remoteAddr)) < 0) {
System.out.println("error accepting incoming connection (err=" + client_fd + ")");
return;
}
System.out.println("accepted connection (client_fd=" + client_fd + ")");
rxBuffer = new byte[100];
lengthToRead = 100;
System.out.println("reading bytes...");
r = zt.read(client_fd, rxBuffer);
System.out.println("r="+r);
System.out.println("string="+new String(rxBuffer));
System.out.println("writing bytes...");
String echo_msg = "echo!";
w = zt.write(client_fd, echo_msg.getBytes());
System.out.println("wrote (" + w + ") bytes");
}
}
// UDP
if (!tcp) {
System.out.println("mode:udp");
if ((fd = zt.socket(zt.AF_INET, zt.SOCK_DGRAM, 0)) < 0) {
System.out.println("error creating socket");
return;
}
// CLIENT
if (client_mode) {
System.out.println("mode:client");
localAddr = new ZTSocketAddress(localAddrStr, portNo);
if ((err = zt.bind(fd, localAddr)) < 0) {
System.out.println("error binding socket to virtual interface");
return;
}
remoteAddr = new ZTSocketAddress(remoteAddrStr, portNo);
System.out.println("sending message to: " + remoteAddr.toString());
if (loop) {
while (true) {
sleep(500);
if ((w = zt.sendto(fd, txBuffer, flags, remoteAddr)) < 0) {
System.out.println("error sending bytes");
} else {
System.out.println("sendto()=" + w);
}
}
} else {
if ((w = zt.sendto(fd, txBuffer, flags, remoteAddr)) < 0) {
System.out.println("error sending bytes");
} else {
System.out.println("sendto()=" + w);
}
}
}
// SERVER
if (!client_mode) {
System.out.println("mode:server");
localAddr = new ZTSocketAddress(localAddrStr, portNo);
System.out.println("binding to " + localAddr.toString());
if ((err = zt.bind(fd, localAddr)) < 0) {
System.out.println("error binding socket to virtual interface");
return;
}
rxBuffer = new byte[100];
remoteAddr = new ZTSocketAddress("-1.-1.-1.-1", 0);
// select() loop
ZTFDSet master_set = new ZTFDSet();
master_set.ZERO();
master_set.SET(fd);
int nfds = fd + 1;
if (use_select)
{
while(true)
{
err = zt.select(nfds, master_set, null, null, 0, 100000);
if (err < 0) {
System.out.println("select failed");
} if (err == 0) {
System.out.println("select timed out");
} if (err > 0) {
System.out.println("select detected something to read on");
for (int i = 0; i < nfds; i++)
{
if (master_set.ISSET(i))
{
System.out.println("attempting to read from: " + i);
r = zt.recvfrom(fd, rxBuffer, flags, remoteAddr);
System.out.println("read (" + r + ") bytes from " + remoteAddr.toString() + ", buffer = " + new String(rxBuffer));
}
}
}
}
}
if (!use_select)
{
while(true) {
addr = new ZTSocketAddress();
r = zt.recvfrom(fd, rxBuffer, flags, remoteAddr);
System.out.println("read (" + r + ") bytes from " + remoteAddr.toString() + ", buffer = " + new String(rxBuffer));
}
}
}
}
zt.close(client_fd);
zt.close(fd);
}
}).start();
while(true)
{
try { Thread.sleep(3000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
}

View File

@@ -1,8 +0,0 @@
## ZeroTier with Java via JNI
***
### ExampleApp
Copy `zt.jar` file into this directory
Extract shared library from JAR file: `jar xf zt.jar libzt.dylib`
Build ExampleApp: `javac -cp ".:zt.jar" ExampleApp.java`

View File

@@ -1,54 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
package com.zerotier.libzt;
public class ZTFDSet
{
byte[] fds_bits = new byte[1024];
public void CLR(int fd)
{
fds_bits[fd] = 0x00;
}
public boolean ISSET(int fd)
{
return fds_bits[fd] == 0x01;
}
public void SET(int fd)
{
fds_bits[fd] = 0x01;
}
public void ZERO()
{
for (int i=0; i<1024; i++) {
fds_bits[i] = 0x00;
}
}
}

View File

@@ -1,92 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
package com.zerotier.libzt;
import com.zerotier.libzt.ZeroTier;
import java.net.InetAddress;
// Designed to transport address information across the JNI boundary
public class ZTSocketAddress
{
public byte[] _ip6 = new byte[16];
public byte[] _ip4 = new byte[4];
public int _family;
public int _port; // Also reused for netmask or prefix
public ZTSocketAddress() {}
public ZTSocketAddress(String ipStr, int port)
{
if(ipStr.contains(":")) {
_family = ZeroTier.AF_INET6;
try {
InetAddress ip = InetAddress.getByName(ipStr);
_ip6 = ip.getAddress();
}
catch (Exception e) { }
}
else if(ipStr.contains(".")) {
_family = ZeroTier.AF_INET;
try {
InetAddress ip = InetAddress.getByName(ipStr);
_ip4 = ip.getAddress();
}
catch (Exception e) { }
}
_port = port;
}
public int getPort() { return _port; }
public int getNetmask() { return _port; }
public int getPrefix() { return _port; }
private String ipString()
{
if (_family == ZeroTier.AF_INET) {
try {
InetAddress inet = InetAddress.getByAddress(_ip4);
return "" + inet.getHostAddress();
} catch (Exception e) {
System.out.println(e);
}
}
if (_family == ZeroTier.AF_INET6) {
try {
InetAddress inet = InetAddress.getByAddress(_ip6);
return "" + inet.getHostAddress();
} catch (Exception e) {
System.out.println(e);
}
}
return "";
}
public String toString() { return ipString() + ":" + _port; }
public String toCIDR() { return ipString() + "/" + _port; }
}

View File

@@ -1,82 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
package com.zerotier.libzt;
import java.net.*;
public class ZeroTier {
public static int AF_INET = 2;
public static int AF_INET6 = 30;
public static int SOCK_STREAM = 1;
public static int SOCK_DGRAM = 2;
public static int O_APPEND = 1024;
public static int O_NONBLOCK = 2048;
public static int O_ASYNC = 8192;
public static int O_DIRECT = 65536;
public static int O_NOATIME = 262144;
public static int F_GETFL = 3;
public static int F_SETFL = 4;
public native void start(String homePath, boolean blocking);
public native void startjoin(String homePath, long nwid);
public native void stop();
public native boolean core_running();
public native boolean stack_running();
public native boolean ready();
public native int join(long nwid);
public native int leave(long nwid);
public native String get_path();
public native long get_node_id();
public native int get_num_assigned_addresses(long nwid);
public native boolean get_address_at_index(long nwid, int index, ZTSocketAddress addr);
public native boolean has_address(long nwid);
public native boolean get_address(long nwid, int address_family, ZTSocketAddress addr);
public native void get_6plane_addr(long nwid, long nodeId, ZTSocketAddress addr);
public native void get_rfc4193_addr(long nwid, long nodeId, ZTSocketAddress addr);
public native int socket(int family, int type, int protocol);
public native int connect(int fd, ZTSocketAddress addr);
public native int bind(int fd, ZTSocketAddress addr);
public native int listen(int fd, int backlog);
public native int accept(int fd, ZTSocketAddress addr);
public native int accept4(int fd, String addr, int port);
public native int close(int fd);
public native int setsockopt(int fd, int level, int optname, int optval, int optlen);
public native int getsockopt(int fd, int level, int optname, int optval, int optlen);
public native int sendto(int fd, byte[] buf, int flags, ZTSocketAddress addr);
public native int send(int fd, byte[] buf, int flags);
public native int recv(int fd, byte[] buf, int flags);
public native int recvfrom(int fd, byte[] buf, int flags, ZTSocketAddress addr);
public native int read(int fd, byte[] buf);
public native int write(int fd, byte[] buf);
public native int shutdown(int fd, int how);
public native boolean getsockname(int fd, ZTSocketAddress addr);
public native int getpeername(int fd, ZTSocketAddress addr);
public native int fcntl(int sock, int cmd, int flag);
public native int select(int nfds, ZTFDSet readfds, ZTFDSet writefds, ZTFDSet exceptfds, int timeout_sec, int timeout_usec);
}

View File

@@ -1,194 +0,0 @@
// This file is built with libzt.a via `make tests`
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#if defined(__APPLE__)
#include <net/ethernet.h>
#endif
#if defined(__linux__)
#include <netinet/ether.h>
#include <sys/socket.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>
#endif
#include "libzt.h"
unsigned short csum(unsigned short *buf, int nwords)
{
unsigned long sum;
for(sum=0; nwords>0; nwords--)
sum += *buf++;
sum = (sum >> 16) + (sum &0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
int main(int argc , char *argv[])
{
if (argc < 3) {
fprintf(stderr, "usage: layer2 <zt_home_dir> <nwid>\n");
return 1;
}
// initialize library
printf("Starting libzt...\n");
zts_startjoin(argv[1], strtoull(argv[2], NULL, 16));
uint64_t device_id = zts_get_node_id();
fprintf(stderr, "Complete. I am %llx\n", device_id);
// create socket
int fd;
if ((fd = zts_socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) < 0) {
printf("There was a problem creating the raw socket\n");
exit(-1);
}
fprintf(stderr, "Created raw socket (%d)\n", fd);
#if defined(__APPLE__)
fprintf(stderr, "SOCK_RAW not supported on mac builds yet. exiting");
exit(0);
#endif
#if defined(__linux__) // The rest of this file isn't yet supported on non-linux platforms
// get interface index to bind on
struct ifreq if_idx;
memset(&if_idx, 0, sizeof(struct ifreq));
strncpy(if_idx.ifr_name, "libzt0", IFNAMSIZ-1);
if (zts_ioctl(fd, SIOCGIFINDEX, &if_idx) < 0) {
perror("SIOCGIFINDEX");
exit(-1);
}
fprintf(stderr, "if_idx.ifr_ifindex=%d\n", if_idx.ifr_ifindex);
// get MAC address of interface to send on
struct ifreq if_mac;
memset(&if_mac, 0, sizeof(struct ifreq));
strncpy(if_mac.ifr_name, "libzt0", IFNAMSIZ-1);
if (zts_ioctl(fd, SIOCGIFHWADDR, &if_mac) < 0) {
perror("SIOCGIFHWADDR");
exit(-1);
}
const unsigned char* mac=(unsigned char*)if_mac.ifr_hwaddr.sa_data;
fprintf(stderr, "hwaddr=%02X:%02X:%02X:%02X:%02X:%02X\n", mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
// get IP address of interface to send on
struct ifreq if_ip;
memset(&if_ip, 0, sizeof(struct ifreq));
strncpy(if_ip.ifr_name, "libzt0", IFNAMSIZ-1);
if (zts_ioctl(fd, SIOCGIFADDR, &if_ip) < 0) {
perror("SIOCGIFADDR");
exit(-1);
}
char ipv4_str[INET_ADDRSTRLEN];
struct sockaddr_in *in4 = (struct sockaddr_in *)&if_ip.ifr_addr;
inet_ntop(AF_INET, (const void *)&in4->sin_addr.s_addr, ipv4_str, INET_ADDRSTRLEN);
fprintf(stderr, "addr=%s", ipv4_str);
// construct ethernet header
int tx_len = 0;
char sendbuf[1024];
struct ether_header *eh = (struct ether_header *) sendbuf;
memset(sendbuf, 0, 1024);
// Ethernet header
eh->ether_shost[0] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[0];
eh->ether_shost[1] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[1];
eh->ether_shost[2] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[2];
eh->ether_shost[3] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[3];
eh->ether_shost[4] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[4];
eh->ether_shost[5] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[5];
// set destination MAC
int MY_DEST_MAC0 = 0x72;
int MY_DEST_MAC1 = 0x92;
int MY_DEST_MAC2 = 0xd4;
int MY_DEST_MAC3 = 0xfd;
int MY_DEST_MAC4 = 0x43;
int MY_DEST_MAC5 = 0x45;
eh->ether_dhost[0] = MY_DEST_MAC0;
eh->ether_dhost[1] = MY_DEST_MAC1;
eh->ether_dhost[2] = MY_DEST_MAC2;
eh->ether_dhost[3] = MY_DEST_MAC3;
eh->ether_dhost[4] = MY_DEST_MAC4;
eh->ether_dhost[5] = MY_DEST_MAC5;
eh->ether_type = htons(ETH_P_IP);
tx_len += sizeof(struct ether_header);
// Construct the IP header
int ttl = 64;
struct iphdr *iph = (struct iphdr *) (sendbuf + sizeof(struct ether_header));
iph->ihl = 5;
iph->version = 4;
iph->tos = 16; // Low delay
iph->id = htons(54321);
iph->ttl = ttl; // hops
iph->protocol = 17; // UDP
// Source IP address, can be spoofed
iph->saddr = inet_addr(inet_ntoa(((struct sockaddr_in *)&if_ip.ifr_addr)->sin_addr));
// iph->saddr = inet_addr("192.168.0.112");
// Destination IP address
iph->daddr = inet_addr("10.7.7.1");
tx_len += sizeof(struct iphdr);
// Construct UDP header
struct udphdr *udph = (struct udphdr *) (sendbuf + sizeof(struct iphdr) + sizeof(struct ether_header));
udph->source = htons(3423);
udph->dest = htons(5342);
udph->check = 0; // skip
tx_len += sizeof(struct udphdr);
// Fill in UDP payload
sendbuf[tx_len++] = 0xde;
sendbuf[tx_len++] = 0xad;
sendbuf[tx_len++] = 0xbe;
sendbuf[tx_len++] = 0xef;
// Fill in remaining header info
// Length of UDP payload and header
udph->len = htons(tx_len - sizeof(struct ether_header) - sizeof(struct iphdr));
// Length of IP payload and header
iph->tot_len = htons(tx_len - sizeof(struct ether_header));
// Calculate IP checksum on completed header
iph->check = csum((unsigned short *)(sendbuf+sizeof(struct ether_header)), sizeof(struct iphdr)/2);
// Send packet
// Destination address
struct sockaddr_ll socket_address;
// Index of the network device
socket_address.sll_ifindex = if_idx.ifr_ifindex;
// Address length
socket_address.sll_halen = ETH_ALEN;
// Destination MAC
socket_address.sll_addr[0] = MY_DEST_MAC0;
socket_address.sll_addr[1] = MY_DEST_MAC1;
socket_address.sll_addr[2] = MY_DEST_MAC2;
socket_address.sll_addr[3] = MY_DEST_MAC3;
socket_address.sll_addr[4] = MY_DEST_MAC4;
socket_address.sll_addr[5] = MY_DEST_MAC5;
while(1)
{
usleep(10000);
// Send packet
if (zts_sendto(fd, sendbuf, tx_len, 0, (struct sockaddr*)&socket_address, sizeof(struct sockaddr_ll)) < 0)
fprintf(stderr, "Send failed\n");
}
// dismantle all zt virtual taps
zts_stop();
#endif
return 0;
}

View File

@@ -1,36 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
import zerotier.ZeroTier
object ExampleApp extends App {
// load libzt.dylib or libzt.so
System.loadLibrary("zt")
val libzt = new ZeroTier
libzt.startjoin("/Users/joseph/op/zt/libzt/ztjni", 0xa09acf0232a930f7L)
val fd = libzt.socket(2, 1, 0)
println(s"libzt.socket(): $fd")
}

View File

@@ -1,18 +0,0 @@
OSTYPE=$(shell uname -s | tr '[A-Z]' '[a-z]')
BUILD=build/$(OSTYPE)
ifeq ($(OSTYPE),darwin)
SHARED_LIB=libzt.dylib
endif
ifeq ($(OSTYPE),linux)
SHARED_LIB=libzt.so
endif
example_scala_app:
scalac *.scala
copy_dynamic_lib:
cp ../../../$(BUILD)/$(SHARED_LIB) .
clean:
-find . -type f \( -name '*.class' \) -delete

View File

@@ -1,14 +0,0 @@
## ZeroTier with Scala via JNI
***
To get this example project to work, do the following:
- From libzt main directory, build shared library: `make shared_jni_lib`
- Copy the resultant dynamic library (`*.so` or `*.dylib`) from `build/` to this current directory
- Change to this directory and `make example_scala_app`
- Run: `scala -Djava.library.path=$(pwd) -cp "." ExampleApp`
Notes:
Upon execution, it will load the libzt dynamic library via the `loadLibrary` method and begin generating an identity.

View File

@@ -1,76 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
package zerotier;
class ZeroTier {
// socket families
// socket types
// basic service controls
@native def start(path: String, blocking: Boolean): Int
@native def startjoin(path: String, nwid: Long): Int
@native def stop(): Unit
@native def running(): Int
@native def join(nwid: Long): Unit
@native def leave(nwid: Long): Unit
// advanced service controls
//@native def get_path(): Unit
@native def get_node_id(): Long
//@native def get_6plane_addr(): Unit
//@native def get_rfc4193_addr(): Unit
// socket API
@native def socket(socket_family: Int, socket_type: Int, protocol: Int): Int
@native def connect(fd: Int, addr: String, port: Int): Int
@native def bind(fd: Int, addr: String, port: Int): Int
@native def listen(fd: Int, backlog: Int): Int
@native def accept(fd: Int, addr: Object, addrlen: Int): Int
@native def accept4(fd: Int, addr: Object, addrlen: Int, flags: Int): Int
@native def close(fd: Int): Int
@native def setsockopt(fd: Int, level: Int, optname: Int, optval: Object, optlen: Int): Int
@native def getsockopt(fd: Int, level: Int, optname: Int, optval: Object, optlen: Int): Int
@native def read(fd: Int, buf: Object, len: Int): Int
@native def write(fd: Int, buf: Object, len: Int): Int
@native def send(fd: Int, buf: Object, len: Int, flags: Int): Int
@native def sendto(fd: Int, buf: Object, len: Int, addr: Object, addrlen: Int): Int
@native def sendmsg(fd: Int, msg: Object, flags: Int): Int
@native def recv(fd: Int, buf: Object, len: Int, flags: Int): Int
@native def recvfrom(fd: Int, buf: Object, len: Int, addr: Object, addrlen: Int): Int
@native def recvmsg(fd: Int, msg: Object, flags: Int): Int
@native def shutdown(fd: Int, how: Int): Int
//@native def getsockname(): Int
//@native def getpeername(): Int
//@native def gethostname(): Int
//@native def sethostname(): Int
//@native def gethostbyname(): Object
//@native def poll(): Int
//@native def select(): Int
@native def fcntl(fd: Int, cmd: Int, flags: Int): Int
@native def ioctl(fd: Int, request: Long, argp: Object): Int
// stack controls
//@native def add_dns(): Int
//@native def del_dns(): Int
}

View File

@@ -1,374 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objects = {
/* Begin PBXBuildFile section */
7C6D474121126417004C82ED /* libzt-static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7CC090842112516900AB1506 /* libzt-static.a */; };
7CC0908021124A1200AB1506 /* wrapper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7CC0907E21124A1200AB1506 /* wrapper.cpp */; };
7CC0908221124F8900AB1506 /* Example.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CC0908121124F8900AB1506 /* Example.swift */; };
7CFEEDAA21123E550071915A /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CFEEDA921123E550071915A /* AppDelegate.swift */; };
7CFEEDAC21123E550071915A /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CFEEDAB21123E550071915A /* ViewController.swift */; };
7CFEEDAF21123E550071915A /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 7CFEEDAD21123E550071915A /* Main.storyboard */; };
7CFEEDB121123E560071915A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 7CFEEDB021123E560071915A /* Assets.xcassets */; };
7CFEEDB421123E560071915A /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 7CFEEDB221123E560071915A /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
7CC0907D21124A1100AB1506 /* ExampleSwiftApp-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "ExampleSwiftApp-Bridging-Header.h"; sourceTree = "<group>"; };
7CC0907E21124A1200AB1506 /* wrapper.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = wrapper.cpp; sourceTree = "<group>"; };
7CC0907F21124A1200AB1506 /* wrapper.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = wrapper.hpp; sourceTree = "<group>"; };
7CC0908121124F8900AB1506 /* Example.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Example.swift; sourceTree = "<group>"; };
7CC090842112516900AB1506 /* libzt-static.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libzt-static.a"; path = "../../../bin/lib/Debug/libzt-static.a"; sourceTree = "<group>"; };
7CFEEDA621123E550071915A /* ExampleSwiftApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ExampleSwiftApp.app; sourceTree = BUILT_PRODUCTS_DIR; };
7CFEEDA921123E550071915A /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7CFEEDAB21123E550071915A /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; };
7CFEEDAE21123E550071915A /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
7CFEEDB021123E560071915A /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
7CFEEDB321123E560071915A /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
7CFEEDB521123E560071915A /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
7CFEEDA321123E550071915A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
7C6D474121126417004C82ED /* libzt-static.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
7CC090832112516800AB1506 /* Frameworks */ = {
isa = PBXGroup;
children = (
7CC090842112516900AB1506 /* libzt-static.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
7CFEED9D21123E550071915A = {
isa = PBXGroup;
children = (
7CFEEDA821123E550071915A /* ExampleSwiftApp */,
7CFEEDA721123E550071915A /* Products */,
7CC090832112516800AB1506 /* Frameworks */,
);
sourceTree = "<group>";
};
7CFEEDA721123E550071915A /* Products */ = {
isa = PBXGroup;
children = (
7CFEEDA621123E550071915A /* ExampleSwiftApp.app */,
);
name = Products;
sourceTree = "<group>";
};
7CFEEDA821123E550071915A /* ExampleSwiftApp */ = {
isa = PBXGroup;
children = (
7CFEEDA921123E550071915A /* AppDelegate.swift */,
7CFEEDAB21123E550071915A /* ViewController.swift */,
7CFEEDAD21123E550071915A /* Main.storyboard */,
7CFEEDB021123E560071915A /* Assets.xcassets */,
7CFEEDB221123E560071915A /* LaunchScreen.storyboard */,
7CFEEDB521123E560071915A /* Info.plist */,
7CC0907E21124A1200AB1506 /* wrapper.cpp */,
7CC0907F21124A1200AB1506 /* wrapper.hpp */,
7CC0907D21124A1100AB1506 /* ExampleSwiftApp-Bridging-Header.h */,
7CC0908121124F8900AB1506 /* Example.swift */,
);
path = ExampleSwiftApp;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
7CFEEDA521123E550071915A /* ExampleSwiftApp */ = {
isa = PBXNativeTarget;
buildConfigurationList = 7CFEEDB821123E560071915A /* Build configuration list for PBXNativeTarget "ExampleSwiftApp" */;
buildPhases = (
7CFEEDA221123E550071915A /* Sources */,
7CFEEDA321123E550071915A /* Frameworks */,
7CFEEDA421123E550071915A /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = ExampleSwiftApp;
productName = ExampleSwiftApp;
productReference = 7CFEEDA621123E550071915A /* ExampleSwiftApp.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
7CFEED9E21123E550071915A /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0940;
LastUpgradeCheck = 0940;
ORGANIZATIONNAME = ZeroTier;
TargetAttributes = {
7CFEEDA521123E550071915A = {
CreatedOnToolsVersion = 9.4.1;
LastSwiftMigration = 0940;
};
};
};
buildConfigurationList = 7CFEEDA121123E550071915A /* Build configuration list for PBXProject "ExampleSwiftApp" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 7CFEED9D21123E550071915A;
productRefGroup = 7CFEEDA721123E550071915A /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
7CFEEDA521123E550071915A /* ExampleSwiftApp */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
7CFEEDA421123E550071915A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
7CFEEDB421123E560071915A /* LaunchScreen.storyboard in Resources */,
7CFEEDB121123E560071915A /* Assets.xcassets in Resources */,
7CFEEDAF21123E550071915A /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
7CFEEDA221123E550071915A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
7CC0908221124F8900AB1506 /* Example.swift in Sources */,
7CFEEDAC21123E550071915A /* ViewController.swift in Sources */,
7CFEEDAA21123E550071915A /* AppDelegate.swift in Sources */,
7CC0908021124A1200AB1506 /* wrapper.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
7CFEEDAD21123E550071915A /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
7CFEEDAE21123E550071915A /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
7CFEEDB221123E560071915A /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
7CFEEDB321123E560071915A /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
7CFEEDB621123E560071915A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 11.4;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
7CFEEDB721123E560071915A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 11.4;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
7CFEEDB921123E560071915A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = 57AG88JR8A;
INFOPLIST_FILE = ExampleSwiftApp/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
"LIBRARY_SEARCH_PATHS[arch=*]" = /Users/joseph/op/zt/libzt_new/bin/lib/Debug;
PRODUCT_BUNDLE_IDENTIFIER = zerotier.ExampleSwiftApp;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "ExampleSwiftApp/ExampleSwiftApp-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 4.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
7CFEEDBA21123E560071915A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = 57AG88JR8A;
INFOPLIST_FILE = ExampleSwiftApp/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = zerotier.ExampleSwiftApp;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "ExampleSwiftApp/ExampleSwiftApp-Bridging-Header.h";
SWIFT_VERSION = 4.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
7CFEEDA121123E550071915A /* Build configuration list for PBXProject "ExampleSwiftApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7CFEEDB621123E560071915A /* Debug */,
7CFEEDB721123E560071915A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
7CFEEDB821123E560071915A /* Build configuration list for PBXNativeTarget "ExampleSwiftApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7CFEEDB921123E560071915A /* Debug */,
7CFEEDBA21123E560071915A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 7CFEED9E21123E550071915A /* Project object */;
}

View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:ExampleSwiftApp.xcodeproj">
</FileRef>
</Workspace>

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>

View File

@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>ExampleSwiftApp.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
</dict>
</plist>

View File

@@ -1,46 +0,0 @@
//
// AppDelegate.swift
// ExampleSwiftApp
//
// Created by Joseph Henry on 8/1/18.
// Copyright © 2018 ZeroTier. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}

View File

@@ -1,98 +0,0 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@@ -1,6 +0,0 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" systemVersion="17A277" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>

View File

@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" systemVersion="17A277" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>

View File

@@ -1,73 +0,0 @@
//
// Example.swift
// ExampleSwiftApp
//
// Created by Joseph Henry on 8/1/18.
// Copyright © 2018 ZeroTier. All rights reserved.
//
import Foundation
import UIKit
class MyApplication: UIResponder, UIApplicationDelegate {
static func libzt_example_function()
{
var fd: Int32 = -1;
var err: Int32 = -1;
let clientMode = true;
let remotePort = 4545;
let remoteAddress = "192.168.195.1";
let appDir = String(NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0])
// Start up and create socket
print("starting...");
zts_startjoin(appDir, 0x1c33c1ceb0aa9251);
print("I am ", NSString(format:"%llx", zts_get_node_id()));
fd = zts_socket(2, 1, 0);
if(fd < 0) {
print("error creating socket");
}
print("fd = ", fd);
// Remote address
var in4 = sockaddr_in(sin_len: UInt8(MemoryLayout<sockaddr_in>.size),
sin_family: UInt8(AF_INET),
sin_port: UInt16(remotePort).bigEndian,
sin_addr: in_addr(s_addr: 0),
sin_zero: (0,0,0,0,0,0,0,0))
inet_pton(AF_INET, remoteAddress, &(in4.sin_addr));
// CLIENT
if (clientMode)
{
print("connecting...");
let addrlen = socklen_t(MemoryLayout.size(ofValue: in4))
let a = withUnsafeMutablePointer(to: &in4) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
err = zts_connect(fd, $0, addrlen)
}
}
if(err < 0) {
print("error connecting to remote server");
}
print("connected");
print("sending message to server");
var msg: String = "Hello from Swift!";
err = zts_write(fd, msg, msg.count)
if(err < 0) {
print("error creating socket");
}
print("wrote ", err, " bytes");
zts_close(fd);
}
else // SERVER
{
}
zts_stop();
}
}

View File

@@ -1,71 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#ifndef LIBZT_BRIDGING_HEADER_H
#define LIBZT_BRIDGING_HEADER_H
#include <sys/socket.h>
#include "/Users/joseph/op/zt/libzt_new/include/libzt.h"
// ZT SERVICE CONTROLS
int zts_start(const char *path, int blocking);
int zts_startjoin(const char *path, const uint64_t nwid);
void zts_stop();
int zts_core_running();
int zts_stack_running();
int zts_ready();
int zts_join(uint64_t nwid);
int zts_leave(uint64_t nwid);
uint64_t zts_get_node_id();
// SOCKET API
int zts_connect(int fd, const struct sockaddr *addr, socklen_t addrlen);
int zts_bind(int fd, const struct sockaddr *addr, socklen_t addrlen);
int zts_accept(int fd, struct sockaddr *addr, socklen_t *addrlen);
int zts_listen(int fd, int backlog);
int zts_socket(int socket_family, int socket_type, int protocol);
int zts_setsockopt(int fd, int level, int optname, const void *optval, socklen_t optlen);
int zts_getsockopt(int fd, int level, int optname, void *optval, socklen_t *optlen);
int zts_close(int fd);
int zts_getsockname(int fd, struct sockaddr *addr, socklen_t *addrlen);
int zts_getpeername(int fd, struct sockaddr *addr, socklen_t *addrlen);
ssize_t zts_send(int fd, const void *buf, size_t len, int flags);
ssize_t zts_sendto(int fd, const void *buf, size_t len, int flags, const struct sockaddr *addr, socklen_t addrlen);
ssize_t zts_sendmsg(int fd, const struct msghdr *msg, int flags);
ssize_t zts_recv(int fd, void *buf, size_t len, int flags);
ssize_t zts_recvfrom(int fd, void *buf, size_t len, int flags, struct sockaddr *addr, socklen_t *addrlen);
ssize_t zts_recvmsg(int fd, struct msghdr *msg,int flags);
int zts_read(int fd, void *buf, size_t len);
int zts_write(int fd, const void *buf, size_t len);
int zts_shutdown(int fd, int how);
int zts_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
int zts_fcntl(int fd, int cmd, int flags);
int zts_ioctl(int fd, unsigned long request, void *argp);
#endif /* LIBZT_BRIDGING_HEADER_H */

View File

@@ -1,45 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>

View File

@@ -1,28 +0,0 @@
//
// ViewController.swift
// ExampleSwiftApp
//
// Created by Joseph Henry on 8/1/18.
// Copyright © 2018 ZeroTier. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
MyApplication.libzt_example_function();
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

View File

@@ -1,20 +0,0 @@
//
// wrapper.cpp
// ExampleSwiftApp
//
// Created by Joseph Henry on 8/1/18.
// Copyright © 2018 ZeroTier. All rights reserved.
//
#include "wrapper.hpp"
#include "/Users/joseph/op/zt/libzt_new/include/libzt.h"
#ifdef __cplusplus
extern "C" {
#endif
// Nothing, implementation is in src/libzt.cpp
#ifdef __cplusplus
}
#endif

View File

@@ -1,14 +0,0 @@
//
// wrapper.hpp
// ExampleSwiftApp
//
// Created by Joseph Henry on 8/1/18.
// Copyright © 2018 ZeroTier. All rights reserved.
//
#ifndef wrapper_hpp
#define wrapper_hpp
#include <stdio.h>
#endif /* wrapper_hpp */

View File

@@ -1,406 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#if defined(__linux__) || defined(__APPLE__)
#include <netdb.h>
#include <unistd.h>
#endif
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <fcntl.h>
#include <vector>
#include <algorithm>
#include <map>
#include "libzt.h"
#include "RingBuffer.h"
#include "ztproxy.hpp"
#if defined(_WIN32)
#include <time.h>
void sleep(unsigned long ms)
{
Sleep(ms);
}
#endif
namespace ZeroTier {
typedef void PhySocket;
ZTProxy::ZTProxy(int proxy_listen_port, std::string nwid, std::string path, std::string internal_addr,
int internal_port, std::string dns_nameserver)
:
_enabled(true),
_run(true),
_proxy_listen_port(proxy_listen_port),
_internal_port(internal_port),
_nwid(nwid),
_internal_addr(internal_addr),
_dns_nameserver(dns_nameserver),
_phy(this,false,true)
{
// Set up TCP listen sockets
// IPv4
struct sockaddr_in in4;
memset(&in4,0,sizeof(in4));
in4.sin_family = AF_INET;
in4.sin_addr.s_addr = Utils::hton((uint32_t)(0x7f000001)); // listen for TCP @127.0.0.1
in4.sin_port = Utils::hton((uint16_t)proxy_listen_port);
_tcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
if (!_tcpListenSocket) {
DEBUG_ERROR("Error binding on port %d for IPv4 HTTP listen socket", proxy_listen_port);
}
// IPv6
/*
struct sockaddr_in6 in6;
memset((void *)&in6,0,sizeof(in6));
in6.sin6_family = AF_INET6;
in6.sin6_port = in4.sin_port;
in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
in6.sin6_port = Utils::hton((uint16_t)proxy_listen_port);
_tcpListenSocket6 = _phy.tcpListen((const struct sockaddr *)&in6,this);
*/
/*
if (!_tcpListenSocket6) {
DEBUG_ERROR("Error binding on port %d for IPv6 HTTP listen socket", proxy_listen_port);
}
*/
_thread = Thread::start(this);
}
ZTProxy::~ZTProxy()
{
_run = false;
_phy.whack();
Thread::join(_thread);
_phy.close(_tcpListenSocket,false);
_phy.close(_tcpListenSocket6,false);
}
void ZTProxy::threadMain()
throw()
{
// Add DNS nameserver
if (_dns_nameserver.length() > 0) {
DEBUG_INFO("setting DNS nameserver (%s)", _dns_nameserver.c_str());
struct sockaddr_in dns_address;
dns_address.sin_addr.s_addr = inet_addr(_dns_nameserver.c_str());
zts_add_dns_nameserver((struct sockaddr*)&dns_address);
}
TcpConnection *conn = NULL;
uint32_t msecs = 1;
struct timeval tv;
tv.tv_sec = msecs / 1000;
tv.tv_usec = (msecs % 1000) * 1000;
int ret = 0;
// Main I/O loop
// Moves data between client application socket and libzt VirtualSocket
while(_run) {
_phy.poll(1);
conn_m.lock();
// build fd_sets to select upon
FD_ZERO(&read_set);
FD_ZERO(&write_set);
nfds = 0;
for (size_t i=0; i<clist.size(); i++) {
FD_SET(clist[i]->zfd, &read_set);
FD_SET(clist[i]->zfd, &write_set);
nfds = clist[i]->zfd > nfds ? clist[i]->zfd : nfds;
}
ret = zts_select(nfds + 1, &read_set, &write_set, NULL, &tv);
if (ret > 0) {
for (int fd_i=0; fd_i<nfds+1; fd_i++) { // I/O needs to be handled on at least one fd
// RX, Handle data incoming from libzt
if (FD_ISSET(fd_i, &read_set)) {
int wr = 0, rd = 0;
conn = zmap[fd_i];
if (conn == NULL) {
DEBUG_ERROR("invalid conn");
exit(0);
}
// read data from libzt and place it on ring buffer
conn->rx_m.lock();
if (conn->RXbuf->count() > 0) {
//DEBUG_INFO("libzt has incoming data on fd=%d, RXing via conn=%p, sock=%p",
// conn->zfd, conn, conn->client_sock);
}
if ((rd = zts_read(conn->zfd, conn->RXbuf->get_buf(),ZT_MAX_MTU)) < 0) {
DEBUG_ERROR("error while reading data from libzt, err=%d", rd);
}
else {
//DEBUG_INFO("LIBZT -> RXBUFFER = %d bytes", rd);
conn->RXbuf->produce(rd);
}
// attempt to write data to client from buffer
if ((wr = _phy.streamSend(conn->client_sock, conn->RXbuf->get_buf(), conn->RXbuf->count())) < 0) {
DEBUG_ERROR("error while writing the data from the RXbuf to the client PhySocket, err=%d", wr);
}
else {
//DEBUG_INFO("RXBUFFER -> CLIENT = %d bytes", wr);
conn->RXbuf->consume(wr);
}
conn->rx_m.unlock();
}
// TX, Handle data outgoing from client to libzt
if (FD_ISSET(fd_i, &write_set)) {
int wr = 0;
conn = zmap[fd_i];
if (conn == NULL) {
DEBUG_ERROR("invalid conn, possibly closed before transmit was possible");
}
// read data from client and place it on ring buffer
conn->tx_m.lock();
if (conn->TXbuf->count() > 0) {
// DEBUG_INFO("client has outgoing data of len=%d on fd=%d, TXing via conn=%p, sock=%p",
// conn->TXbuf->count(), conn->zfd, conn, conn->client_sock);
if ((wr = zts_write(conn->zfd, conn->TXbuf->get_buf(), conn->TXbuf->count())) < 0) {
DEBUG_ERROR("error while sending the data over libzt, err=%d", wr);
}
else {
//DEBUG_INFO("TXBUFFER -> LIBZT = %d bytes", wr);
conn->TXbuf->consume(wr); // data is presumed sent, mark it as such in the ringbuffer
}
}
conn->tx_m.unlock();
}
}
}
conn_m.unlock();
}
}
bool isValidIPAddress(const char *ip)
{
struct sockaddr_in sa;
return inet_pton(AF_INET, ip, &(sa.sin_addr)) == 1;
}
void ZTProxy::phyOnTcpData(PhySocket *sock, void **uptr, void *data, unsigned long len)
{
int wr = 0, zfd = -1, err = 0;
DEBUG_EXTRA("sock=%p, len=%lu", sock, len);
std::string host = _internal_addr;
TcpConnection *conn = cmap[sock];
if (conn == NULL) {
DEBUG_ERROR("invalid conn");
exit(0);
}
if (conn->zfd < 0) { // no connection yet
if (host == "") {
DEBUG_ERROR("invalid hostname or address (empty)");
return;
}
DEBUG_INFO("establishing proxy connection...");
uint16_t dest_port, ipv;
dest_port = _internal_port;
host = _internal_addr;
if (isValidIPAddress(host.c_str()) == false) {
// try to resolve this if it isn't an IP address
struct hostent *h = zts_gethostbyname(host.c_str());
if (h == NULL) {
DEBUG_ERROR("unable to resolve hostname (%s) (errno=%d)", host.c_str(), errno);
return;
}
// TODO
// host = h->h_addr_list[0];
}
// determine address type
ipv = host.find(":") != std::string::npos ? 6 : 4;
// connect to remote host
if (ipv == 4) {
DEBUG_INFO("attempting to proxy [0.0.0.0:%d -> %s:%d]", _proxy_listen_port, host.c_str(), dest_port);
struct sockaddr_in in4;
memset(&in4,0,sizeof(in4));
in4.sin_family = AF_INET;
in4.sin_addr.s_addr = inet_addr(host.c_str());
in4.sin_port = Utils::hton(dest_port);
if ((zfd = zts_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
DEBUG_ERROR("unable to create socket (errno=%d)", errno);
return;
}
if ((err = zts_connect(zfd, (const struct sockaddr *)&in4, sizeof(in4))) < 0) {
DEBUG_ERROR("unable to connect to remote host (errno=%d)", errno);
return;
}
}
if (ipv == 6) {
//DEBUG_INFO("attempting to proxy [0.0.0.0:%d -> %s:%d]", _proxy_listen_port, host.c_str(), dest_port);
/*
struct sockaddr_in6 in6;
memset(&in6,0,sizeof(in6));
in6.sin6_family = AF_INET;
struct hostent *server;
server = gethostbyname2((char*)host.c_str(),AF_INET6);
memmove((char *) &in6.sin6_addr.s6_addr, (char *) server->h_addr, server->h_length);
in6.sin6_port = Utils::hton(dest_port);
zfd = zts_socket(AF_INET, SOCK_STREAM, 0);
err = zts_connect(zfd, (const struct sockaddr *)&in6, sizeof(in6));
*/
}
if (zfd < 0 || err < 0) {
// now release TX buffer contents we previously saved, since we can't connect
DEBUG_ERROR("error while connecting to remote host (zfd=%d, err=%d)", zfd, err);
conn->tx_m.lock();
conn->TXbuf->reset();
conn->tx_m.unlock();
return;
}
else {
DEBUG_INFO("successfully connected to remote host");
}
conn_m.lock();
// on success, add connection entry to map, set physock for later
clist.push_back(conn);
conn->zfd = zfd;
conn->client_sock = sock;
cmap[conn->client_sock] = conn;
zmap[zfd] = conn;
conn_m.unlock();
}
// Write data coming from client TCP connection to its TX buffer, later emptied into libzt by threadMain I/O loop
conn->tx_m.lock();
if ((wr = conn->TXbuf->write((const char *)data, len)) < 0) {
DEBUG_ERROR("there was an error while writing data from client to tx buffer, err=%d", wr);
}
else {
// DEBUG_INFO("CLIENT -> TXBUFFER = %d bytes", wr);
}
conn->tx_m.unlock();
}
void ZTProxy::phyOnTcpAccept(PhySocket *sockL, PhySocket *sockN, void **uptrL, void **uptrN,
const struct sockaddr *from)
{
DEBUG_INFO("sockL=%p, sockN=%p", sockL, sockN);
TcpConnection *conn = new TcpConnection();
conn->client_sock = sockN;
cmap[sockN]=conn;
}
void ZTProxy::phyOnTcpClose(PhySocket *sock, void **uptr)
{
DEBUG_INFO("sock=%p", sock);
conn_m.lock();
TcpConnection *conn = cmap[sock];
if (conn) {
conn->client_sock=NULL;
if (conn->zfd >= 0) {
zts_close(conn->zfd);
}
cmap.erase(sock);
for (size_t i=0; i<clist.size(); i++) {
if (conn == clist[i]) {
clist.erase(clist.begin()+i);
break;
}
}
zmap[conn->zfd] = NULL;
delete conn;
conn = NULL;
}
#if defined(_WIN32)
closesocket(_phy.getDescriptor(sock));
#else
close(_phy.getDescriptor(sock));
#endif
conn_m.unlock();
}
void ZTProxy::phyOnDatagram(PhySocket *sock, void **uptr, const struct sockaddr *localAddr,
const struct sockaddr *from, void *data, unsigned long len) {
DEBUG_INFO();
}
void ZTProxy::phyOnTcpWritable(PhySocket *sock, void **uptr) {
DEBUG_INFO();
}
void ZTProxy::phyOnFileDescriptorActivity(PhySocket *sock, void **uptr, bool readable, bool writable) {
DEBUG_INFO("sock=%p", sock);
}
void ZTProxy::phyOnTcpConnect(PhySocket *sock, void **uptr, bool success) {
DEBUG_INFO("sock=%p", sock);
}
void ZTProxy::phyOnUnixClose(PhySocket *sock, void **uptr) {
DEBUG_INFO("sock=%p", sock);
}
void ZTProxy::phyOnUnixData(PhySocket *sock,void **uptr,void *data,ssize_t len) {
DEBUG_INFO("sock=%p, len=%lu", sock, len);
}
void ZTProxy::phyOnUnixWritable(PhySocket *sock, void **uptr, bool lwip_invoked) {
DEBUG_INFO("sock=%p", sock);
}
}
int main(int argc, char **argv)
{
if (argc < 6 || argc > 7) {
printf("\nZeroTier TCP Proxy Service\n");
printf("ztproxy [config_file_path] [local_listen_port] [nwid] [zt_host_addr] [zt_resource_port] [optional_dns_nameserver]\n");
exit(0);
}
std::string path = argv[1];
int proxy_listen_port = atoi(argv[2]);
std::string nwidstr = argv[3];
std::string internal_addr = argv[4];
int internal_port = atoi(argv[5]);
std::string dns_nameserver= "";//argv[6];
// Start ZeroTier Node
// Join Network which contains resources we need to proxy
DEBUG_INFO("waiting for libzt to come online");
uint64_t nwid = strtoull(nwidstr.c_str(),NULL,16);
zts_startjoin(path.c_str(), nwid);
ZeroTier::ZTProxy *proxy = new ZeroTier::ZTProxy(proxy_listen_port, nwidstr, path, internal_addr, internal_port, dns_nameserver);
if (proxy) {
printf("\nZTProxy started. Listening on %d\n", proxy_listen_port);
printf("Traffic will be proxied to and from %s:%d on network %s\n", internal_addr.c_str(), internal_port, nwidstr.c_str());
printf("Proxy Node config files and key stored in: %s/\n\n", path.c_str());
while(1) {
sleep(1);
}
}
else {
printf("unable to create proxy\n");
}
return 0;
}

View File

@@ -1,132 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#ifndef ZT_ZTPROXY_HPP
#define ZT_ZTPROXY_HPP
#include "Constants.hpp"
#include "Thread.hpp"
#include "InetAddress.hpp"
#include "Mutex.hpp"
#include "Phy.hpp"
#include "OSUtils.hpp"
#if defined(__linux__) || defined(__APPLE__)
#include <sys/select.h>
#endif
#include <queue>
#include <vector>
#include <stdio.h>
#define BUF_SZ 1024*1024
namespace ZeroTier {
typedef void PhySocket;
class ZTProxy;
class TcpConnection
{
public:
int zfd;
PhySocket *client_sock;
RingBuffer *TXbuf, *RXbuf;
Mutex tx_m, rx_m;
TcpConnection() {
zfd = -1;
TXbuf = new RingBuffer(BUF_SZ);
RXbuf = new RingBuffer(BUF_SZ);
}
~TcpConnection() {
delete TXbuf;
delete RXbuf;
client_sock = NULL;
TXbuf = NULL;
RXbuf = NULL;
}
};
class ZTProxy
{
friend class Phy<ZTProxy *>;
public:
ZTProxy(int proxy_listen_port, std::string nwid, std::string path, std::string internal_addr, int internal_port, std::string _dns_nameserver);
~ZTProxy();
// Send incoming data to intended host
void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len);
void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len);
void phyOnTcpWritable(PhySocket *sock,void **uptr);
void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable);
// Establish outgoing connection to intended host
void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success);
// Accept connection
void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from);
// Handle the closure of a Unix Domain socket
void phyOnUnixClose(PhySocket *sock,void **uptr);
void phyOnUnixData(PhySocket *sock,void **uptr,void *data,ssize_t len);
void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked);
// Handle the closure of a TCP connection
void phyOnTcpClose(PhySocket *sock,void **uptr);
void threadMain()
throw();
TcpConnection *getConnection(PhySocket *sock);
private:
volatile bool _enabled;
volatile bool _run;
Mutex conn_m;
fd_set read_set, write_set;
int nfds;
int _proxy_listen_port;
int _internal_port;
std::string _nwid;
std::string _internal_addr;
std::string _dns_nameserver;
Thread _thread;
Phy<ZTProxy*> _phy;
PhySocket *_tcpListenSocket;
PhySocket *_tcpListenSocket6;
// mapping from ZeroTier VirtualSocket fd to TcpConnection pointer
std::map<int, TcpConnection*> zmap;
// mapping from ZeroTier PhySocket to TcpConnection pointer
std::map<PhySocket*, TcpConnection*> cmap;
std::vector<TcpConnection*> clist;
};
}
#endif

View File

@@ -36,29 +36,3 @@ index 74c22d33..58979e26 100644
if (i < nqcb->oldQueues.size()) { if (i < nqcb->oldQueues.size()) {
if (nqcb->oldQueues[i]->byteLength > maxQueueLength) { if (nqcb->oldQueues[i]->byteLength > maxQueueLength) {
maxQueueLength = nqcb->oldQueues[i]->byteLength; maxQueueLength = nqcb->oldQueues[i]->byteLength;
diff --git a/service/OneService.cpp b/service/OneService.cpp
index a1c53764..e3034059 100644
--- a/service/OneService.cpp
+++ b/service/OneService.cpp
@@ -625,6 +625,8 @@ public:
break;
if (!pkt)
break;
+ if (!_run)
+ break;
const ZT_ResultCode rc = _node->processWirePacket(nullptr,pkt->now,pkt->sock,&(pkt->from),pkt->data,pkt->size,&_nextBackgroundTaskDeadline);
{
@@ -2244,6 +2246,12 @@ public:
#endif
syncManagedStuff(n,true,true);
n.tap->setMtu(nwc->mtu);
+#if defined(ZT_SDK)
+ // Inform the virtual tap of the update
+ if (op == ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE) {
+ n.tap->lastConfigUpdate(OSUtils::now());
+ }
+#endif
} else {
_nets.erase(nwid);
return -999; // tap init failed

View File

@@ -0,0 +1,61 @@
This license file applies to everything in this repository except that which
is explicitly annotated as being written by other authors, i.e. the Boost
queue (included in the benchmarks for comparison), Intel's TBB library (ditto),
the CDSChecker tool (used for verification), the Relacy model checker (ditto),
and Jeff Preshing's semaphore implementation (used in the blocking queue) which
has a zlib license (embedded in blockingconcurrentqueue.h).
---
Simplified BSD License:
Copyright (c) 2013-2016, Cameron Desrochers.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---
I have also chosen to dual-license under the Boost Software License as an alternative to
the Simplified BSD license above:
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@@ -1,32 +0,0 @@
diff --git a/ports/unix/port/include/arch/cc.h b/ports/unix/port/include/arch/cc.h
index 80b37d8..ae46d76 100644
--- a/ports/unix/port/include/arch/cc.h
+++ b/ports/unix/port/include/arch/cc.h
@@ -32,6 +32,8 @@
#ifndef LWIP_ARCH_CC_H
#define LWIP_ARCH_CC_H
+#include "include/Debug.hpp" // libzt
+
/* see https://sourceforge.net/p/predef/wiki/OperatingSystems/ */
#if defined __ANDROID__
#define LWIP_UNIX_ANDROID
@@ -65,7 +67,7 @@
#endif
#if defined(LWIP_UNIX_ANDROID) && defined(FD_SET)
-typedef __kernel_fd_set fd_set;
+//typedef __kernel_fd_set fd_set;
#endif
#if defined(LWIP_UNIX_MACH)
@@ -81,6 +83,9 @@ typedef struct sio_status_s sio_status_t;
#define sio_fd_t sio_status_t*
#define __sio_fd_t_defined
+// Comment out the following line to use lwIP's default diagnostic printing routine
+#define LWIP_PLATFORM_DIAG(x) do {DEBUG_INFO x;} while(0)
+
typedef unsigned int sys_prot_t;
#endif /* LWIP_ARCH_CC_H */

View File

@@ -1,2 +0,0 @@
// Refers to the actual lwIP stack driver location
#include "../include/lwipopts.h"

View File

@@ -1,346 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
/**
* @file
*
* Useful constants
*/
#ifndef LIBZT_CONSTANTS_HPP
#define LIBZT_CONSTANTS_HPP
//////////////////////////////////////////////////////////////////////////////
// Callbacks //
//////////////////////////////////////////////////////////////////////////////
#define ZTS_NODE_CALLBACKS 1
#define ZTS_NETWORK_CALLBACKS 1
#define ZTS_NETIF_CALLBACKS 1
#define ZTS_PEER_CALLBACKS 1
#define ZTS_CALLBACK_PROCESSING_INTERVAL ZTS_WRAPPER_CHECK_INTERVAL // 100 // ms
#define ZTS_CALLBACK_MSG_QUEUE_LEN 256
//////////////////////////////////////////////////////////////////////////////
// Error codes returned by ZeroTier and the libzt API //
// See ext/ZeroTierOne/include/ZeroTierOne.h //
//////////////////////////////////////////////////////////////////////////////
typedef int zts_err_t;
#define ZTS_ERR_OK 0 // Everything is ok
#define ZTS_ERR_INVALID_ARG -1 // A parameter provided by the user application is invalid (e.g. our of range, NULL, etc)
#define ZTS_ERR_SERVICE -2 // The service isn't initialized or is for some other reason currently unavailable
#define ZTS_ERR_INVALID_OP -3 // For some reason this API operation is not permitted (perhaps the service is still starting?)
#define ZTS_EVENT_NONE 0x00000000
// Node-specific events
#define ZTS_EVENT_NODE_ONLINE 0x00000001 // Node is online
#define ZTS_EVENT_NODE_OFFLINE 0x00000002 // Node is offline
#define ZTS_EVENT_NODE_DOWN 0x00000004 // Node is shutting down
#define ZTS_EVENT_NODE_IDENTITY_COLLISION 0x00000008 // Identity collision - check for duplicate instances
#define ZTS_EVENT_NODE_UNRECOVERABLE_ERROR 0x00000010 // Something is seriously wrong
#define ZTS_EVENT_NODE_NORMAL_TERMINATION 0x00000020 // Service thread has stopped
// Network-specific events
#define ZTS_EVENT_NETWORK_NOT_FOUND 0x00000080
#define ZTS_EVENT_NETWORK_CLIENT_TOO_OLD 0x00000100
#define ZTS_EVENT_NETWORK_REQUESTING_CONFIG 0x00000200
#define ZTS_EVENT_NETWORK_OK 0x00000400
#define ZTS_EVENT_NETWORK_ACCESS_DENIED 0x00000800
#define ZTS_EVENT_NETWORK_READY_IP4 0x00001000
#define ZTS_EVENT_NETWORK_READY_IP6 0x00002000
#define ZTS_EVENT_NETWORK_DOWN 0x00004000
#define ZTS_EVENT_NETWORK_STATUS_CHANGE ZTS_EVENT_NETWORK_NOT_FOUND | ZTS_EVENT_NETWORK_CLIENT_TOO_OLD | ZTS_EVENT_NETWORK_REQUESTING_CONFIG | ZTS_EVENT_NETWORK_OK | ZTS_EVENT_NETWORK_ACCESS_DENIED
// lwIP netif events
#define ZTS_EVENT_NETIF_UP_IP4 0x00100000
#define ZTS_EVENT_NETIF_UP_IP6 0x00200000
#define ZTS_EVENT_NETIF_DOWN_IP4 0x00400000
#define ZTS_EVENT_NETIF_DOWN_IP6 0x00800000
#define ZTS_EVENT_NETIF_REMOVED 0x01000000
#define ZTS_EVENT_NETIF_LINK_UP 0x02000000
#define ZTS_EVENT_NETIF_LINK_DOWN 0x04000000
#define ZTS_EVENT_NETIF_NEW_ADDRESS 0x08000000
#define ZTS_EVENT_NETIF_STATUS_CHANGE ZTS_EVENT_NETIF_UP_IP4 | ZTS_EVENT_NETIF_UP_IP6 | ZTS_EVENT_NETIF_DOWN_IP4 | ZTS_EVENT_NETIF_DOWN_IP6 | ZTS_EVENT_NETIF_LINK_UP | ZTS_EVENT_NETIF_LINK_DOWN
//
#define ZTS_EVENT_GENERIC_DOWN ZTS_EVENT_NETWORK_DOWN | ZTS_EVENT_NETIF_DOWN_IP4 | ZTS_EVENT_NETIF_DOWN_IP6 | ZTS_EVENT_NETIF_LINK_DOWN
// Peer events
#define ZTS_EVENT_PEER_P2P 0x20000000
#define ZTS_EVENT_PEER_RELAY 0x40000000
#define ZTS_EVENT_PEER_UNREACHABLE 0x80000000 // Not yet supported
//////////////////////////////////////////////////////////////////////////////
// libzt config //
//////////////////////////////////////////////////////////////////////////////
/**
* Default port that libzt will use to support all virtual communication
*/
#define ZTS_DEFAULT_PORT 9994
/**
* Maximum port number allowed
*/
#define ZTS_MAX_PORT 65535
/**
* For layer-2 only (this will omit all user-space network stack code)
*/
#define ZTS_NO_STACK 0
/**
* How fast service states are re-checked (in milliseconds)
*/
#define ZTS_WRAPPER_CHECK_INTERVAL 50
/**
* By how much thread I/O and callback loop delays are multiplied (unitless)
*/
#define ZTS_HIBERNATION_MULTIPLIER 50
/**
* Maximum allowed number of networks joined to concurrently
*/
#define ZTS_MAX_JOINED_NETWORKS 64
/**
* Maximum address assignments per network
*/
#define ZTS_MAX_ASSIGNED_ADDRESSES 16
/**
* Maximum routes per network
*/
#define ZTS_MAX_NETWORK_ROUTES 32
/**
* Length of buffer required to hold a ztAddress/nodeID
*/
#define ZTS_ID_LEN 16
/**
* Polling interval (in ms) for file descriptors wrapped in the Phy I/O loop (for raw drivers only)
*/
#define ZTS_PHY_POLL_INTERVAL 1
/**
* Maximum length of libzt/ZeroTier home path (where keys, and config files are stored)
*/
#define ZTS_HOME_PATH_MAX_LEN 256
/**
* Length of human-readable MAC address string
*/
#define ZTS_MAC_ADDRSTRLEN 18
/**
* Interval (in ms) for performing background tasks
*/
#define ZTS_HOUSEKEEPING_INTERVAL 1000
/**
* Name of the service thread (for debug purposes only)
*/
#define ZTS_SERVICE_THREAD_NAME "ZeroTierServiceThread"
/**
* Name of the callback monitor thread (for debug purposes only)
*/
#define ZTS_EVENT_CALLBACK_THREAD_NAME "ZeroTierEventCallbackThread"
//////////////////////////////////////////////////////////////////////////////
// lwIP driver config //
// For more LWIP configuration options see: include/lwipopts.h //
//////////////////////////////////////////////////////////////////////////////
/*
* The following three quantities are related and govern how incoming frames are fed into the
* network stack's core:
* Every LWIP_GUARDED_BUF_CHECK_INTERVAL milliseconds, a callback will be called from the core and
* will input a maximum of LWIP_FRAMES_HANDLED_PER_CORE_CALL frames before returning control back
* to the core. Meanwhile, incoming frames from the ZeroTier wire will be allocated and their
* pointers will be cached in the receive frame buffer of the size LWIP_MAX_GUARDED_RX_BUF_SZ to
* await the next callback from the core
*/
#define LWIP_GUARDED_BUF_CHECK_INTERVAL 5 // in ms
#define LWIP_MAX_GUARDED_RX_BUF_SZ 1024 // number of frame pointers that can be cached waiting for receipt into core
#define LWIP_FRAMES_HANDLED_PER_CORE_CALL 16 // How many frames are handled per call from core
typedef signed char err_t;
#define ND6_DISCOVERY_INTERVAL 1000
#define ARP_DISCOVERY_INTERVAL ARP_TMR_INTERVAL
//////////////////////////////////////////////////////////////////////////////
// Subset of: ZeroTierOne.h and Constants.hpp //
// We redefine a few ZT structures here so that we don't need to drag the //
// entire ZeroTierOne.h file into the user application //
//////////////////////////////////////////////////////////////////////////////
/**
* Maximum MTU size for ZeroTier
*/
#define ZT_MAX_MTU 10000
/**
* Maximum number of direct network paths to a given peer
*/
#define ZT_MAX_PEER_NETWORK_PATHS 16
//
// This include file also auto-detects and canonicalizes some environment
// information defines:
//
// __LINUX__
// __APPLE__
// __BSD__ (OSX also defines this)
// __UNIX_LIKE__ (Linux, BSD, etc.)
// __WINDOWS__
//
// Also makes sure __BYTE_ORDER is defined reasonably.
//
// Hack: make sure __GCC__ is defined on old GCC compilers
#ifndef __GCC__
#if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1) || defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2) || defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
#define __GCC__
#endif
#endif
#if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
#ifndef __LINUX__
#define __LINUX__
#endif
#ifndef __UNIX_LIKE__
#define __UNIX_LIKE__
#endif
#include <endian.h>
#endif
#ifdef __APPLE__
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
#include <TargetConditionals.h>
#ifndef __UNIX_LIKE__
#define __UNIX_LIKE__
#endif
#ifndef __BSD__
#define __BSD__
#endif
#include <machine/endian.h>
#endif
// Defined this macro to disable "type punning" on a number of targets that
// have issues with unaligned memory access.
#if defined(__arm__) || defined(__ARMEL__) || (defined(__APPLE__) && ( (defined(TARGET_OS_IPHONE) && (TARGET_OS_IPHONE != 0)) || (defined(TARGET_OS_WATCH) && (TARGET_OS_WATCH != 0)) || (defined(TARGET_IPHONE_SIMULATOR) && (TARGET_IPHONE_SIMULATOR != 0)) ) )
#ifndef ZT_NO_TYPE_PUNNING
#define ZT_NO_TYPE_PUNNING
#endif
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#ifndef __UNIX_LIKE__
#define __UNIX_LIKE__
#endif
#ifndef __BSD__
#define __BSD__
#endif
#include <machine/endian.h>
#ifndef __BYTE_ORDER
#define __BYTE_ORDER _BYTE_ORDER
#define __LITTLE_ENDIAN _LITTLE_ENDIAN
#define __BIG_ENDIAN _BIG_ENDIAN
#endif
#endif
#if defined(_WIN32) || defined(_WIN64)
#ifndef __WINDOWS__
#define __WINDOWS__
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#pragma warning(disable : 4290)
#pragma warning(disable : 4996)
#pragma warning(disable : 4101)
#undef __UNIX_LIKE__
#undef __BSD__
#define ZT_PATH_SEPARATOR '\\'
#define ZT_PATH_SEPARATOR_S "\\"
#define ZT_EOL_S "\r\n"
#include <WinSock2.h>
#include <Windows.h>
#endif
// Assume little endian if not defined
#if (defined(__APPLE__) || defined(__WINDOWS__)) && (!defined(__BYTE_ORDER))
#undef __BYTE_ORDER
#undef __LITTLE_ENDIAN
#undef __BIG_ENDIAN
#define __BIG_ENDIAN 4321
#define __LITTLE_ENDIAN 1234
#define __BYTE_ORDER 1234
#endif
#ifdef __UNIX_LIKE__
#define ZT_PATH_SEPARATOR '/'
#define ZT_PATH_SEPARATOR_S "/"
#define ZT_EOL_S "\n"
#endif
#ifndef __BYTE_ORDER
#include <endian.h>
#endif
#ifdef __NetBSD__
#define RTF_MULTICAST 0x20000000
#endif
#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
#ifndef likely
#define likely(x) __builtin_expect((x),1)
#endif
#ifndef unlikely
#define unlikely(x) __builtin_expect((x),0)
#endif
#else
#ifndef likely
#define likely(x) (x)
#endif
#ifndef unlikely
#define unlikely(x) (x)
#endif
#endif
#ifdef __WINDOWS__
#define ZT_PACKED_STRUCT(D) __pragma(pack(push,1)) D __pragma(pack(pop))
#else
#define ZT_PACKED_STRUCT(D) D __attribute__((packed))
#endif
#endif // _H

View File

@@ -1,215 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
/**
* @file
*
* Management of virtual tap interfaces
*/
#ifndef LIBZT_DEFS_HPP
#define LIBZT_DEFS_HPP
#include "Constants.hpp"
#ifndef _USING_LWIP_DEFINITIONS_
#include <sys/socket.h>
#endif
namespace ZeroTier {
//////////////////////////////////////////////////////////////////////////////
// Subset of: ZeroTierOne.h //
// We redefine a few ZT structures here so that we don't need to drag the //
// entire ZeroTierOne.h file into the user application //
//////////////////////////////////////////////////////////////////////////////
/**
* What trust hierarchy role does this peer have?
*/
enum zts_peer_role
{
ZTS_PEER_ROLE_LEAF = 0, // ordinary node
ZTS_PEER_ROLE_MOON = 1, // moon root
ZTS_PEER_ROLE_PLANET = 2 // planetary root
};
/**
* A structure used to represent a virtual network route
*/
struct zts_virtual_network_route
{
/**
* Target network / netmask bits (in port field) or NULL or 0.0.0.0/0 for default
*/
struct sockaddr_storage target;
/**
* Gateway IP address (port ignored) or NULL (family == 0) for LAN-local (no gateway)
*/
struct sockaddr_storage via;
/**
* Route flags
*/
uint16_t flags;
/**
* Route metric (not currently used)
*/
uint16_t metric;
};
/**
* A structure used to convey network-specific details to the user application
*/
struct zts_network_details
{
/**
* Network ID
*/
uint64_t nwid;
/**
* Maximum Transmission Unit size for this network
*/
int mtu;
/**
* Number of addresses (actually) assigned to the node on this network
*/
short num_addresses;
/**
* Array of IPv4 and IPv6 addresses assigned to the node on this network
*/
struct sockaddr_storage addr[ZTS_MAX_ASSIGNED_ADDRESSES];
/**
* Number of routes
*/
unsigned int num_routes;
/**
* Array of IPv4 and IPv6 addresses assigned to the node on this network
*/
struct zts_virtual_network_route routes[ZTS_MAX_NETWORK_ROUTES];
};
/**
* Physical network path to a peer
*/
struct zts_physical_path
{
/**
* Address of endpoint
*/
struct sockaddr_storage address;
/**
* Time of last send in milliseconds or 0 for never
*/
uint64_t lastSend;
/**
* Time of last receive in milliseconds or 0 for never
*/
uint64_t lastReceive;
/**
* Is this a trusted path? If so this will be its nonzero ID.
*/
uint64_t trustedPathId;
/**
* Is path expired?
*/
int expired;
/**
* Is path preferred?
*/
int preferred;
};
/**
* Peer status result buffer
*/
struct zts_peer_details
{
/**
* ZeroTier address (40 bits)
*/
uint64_t address;
/**
* Remote major version or -1 if not known
*/
int versionMajor;
/**
* Remote minor version or -1 if not known
*/
int versionMinor;
/**
* Remote revision or -1 if not known
*/
int versionRev;
/**
* Last measured latency in milliseconds or -1 if unknown
*/
int latency;
/**
* What trust hierarchy role does this device have?
*/
enum zts_peer_role role;
/**
* Number of paths (size of paths[])
*/
unsigned int pathCount;
/**
* Known network paths to peer
*/
zts_physical_path paths[ZT_MAX_PEER_NETWORK_PATHS];
};
/**
* List of peers
*/
struct zts_peer_list
{
zts_peer_details *peers;
unsigned long peerCount;
};
} // namespace ZeroTier
#endif // _H

View File

@@ -1,97 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
/**
* @file
*
* Ring buffer implementation for network stack drivers
*/
#ifndef ZT_RINGBUFFER_H
#define ZT_RINGBUFFER_H
#include <cstdint>
#include <stdlib.h>
typedef char bufElementType;
class RingBuffer
{
private:
bufElementType * buf;
size_t size;
size_t begin;
size_t end;
bool wrap;
public:
/**
* create a RingBuffer with space for up to size elements.
*/
explicit RingBuffer(size_t size)
: size(size),
begin(0),
end(0),
wrap(false)
{
buf = new bufElementType[size];
}
/*
RingBuffer(const RingBuffer<T> & ring)
{
this(ring.size);
begin = ring.begin;
end = ring.end;
memcpy(buf, ring.buf, sizeof(T) * size);
}
*/
~RingBuffer()
{
delete[] buf;
}
// get a reference to the underlying buffer
bufElementType* get_buf();
// adjust buffer index pointer as if we copied data in
size_t produce(size_t n);
// merely reset the buffer pointer, doesn't erase contents
void reset();
// adjust buffer index pointer as if we copied data out
size_t consume(size_t n);
size_t write(const bufElementType * data, size_t n);
size_t read(bufElementType * dest, size_t n);
size_t count();
size_t getFree();
};
#endif // _H

View File

@@ -1,393 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
/**
* @file
*
* Header for ZeroTier service controls
*/
#ifndef LIBZT_SERVICE_CONTROLS_HPP
#define LIBZT_SERVICE_CONTROLS_HPP
#include "Constants.hpp"
namespace ZeroTier {
#ifdef _WIN32
#ifdef ADD_EXPORTS
#define ZT_SOCKET_API __declspec(dllexport)
#else
#define ZT_SOCKET_API __declspec(dllimport)
#endif
#define ZTCALL __cdecl
#else
#define ZT_SOCKET_API
#define ZTCALL
#endif
//////////////////////////////////////////////////////////////////////////////
// ZeroTier Service Controls //
//////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief (optional) Sets the port for the background libzt service. If this function is called
* with a port number between 1-65535 it will attempt to bind to that port. If it is called with
* a port number of 0 it will attempt to randomly search for an available port. If this function
* is never called, the service will try to bind on LIBZT_DEFAULT_PORT which is 9994.
*
* @usage Should be called at the beginning of your application before `zts_startjoin()`
* @param portno Port number
* @return 0 if successful; or -1 if failed
*/
ZT_SOCKET_API int ZTCALL zts_set_service_port(int portno);
/**
* @brief (optional) Returns the port number used by the ZeroTier service
* @usage Can be called if a port number was previously assigned
* @return the port number used by the ZeroTier service
*/
ZT_SOCKET_API int ZTCALL zts_get_service_port();
/**
* @brief Starts the ZeroTier service
*
* @usage Should be called at the beginning of your application. Will blocks until all of the following conditions are met:
* - ZeroTier core service has been initialized
* - Cryptographic identity has been generated or loaded from directory specified by `path`
* - Virtual network is successfully joined
* - IP address is assigned by network controller service
* @param path path directory where cryptographic identities and network configuration files are stored and retrieved
* (`identity.public`, `identity.secret`)
* @param blocking whether or not this call will block until the entire service is up and running
* @return 0 if successful; or 1 if failed
*/
ZT_SOCKET_API int ZTCALL zts_start(const char *path, int blocking);
/**
* @brief Starts the ZeroTier service and notifies user application of events via callback
*
* @usage Should be called at the beginning of your application. Will blocks until all of the following conditions are met:
* - ZeroTier core service has been initialized
* - Cryptographic identity has been generated or loaded from directory specified by `path`
* - Virtual network is successfully joined
* - IP address is assigned by network controller service
* @param path path directory where cryptographic identities and network configuration files are stored and retrieved
* (`identity.public`, `identity.secret`)
* @param userCallbackFunc User-specified callback for ZeroTier events
* @param blocking whether or not this call will block until the entire service is up and running
* @return 0 if successful; or 1 if failed
*/
ZT_SOCKET_API int ZTCALL zts_start_with_callback(const char *path, void (*userCallbackFunc)(uint64_t, int), int blocking);
/**
* @brief Starts the ZeroTier service
*
* @usage Should be called at the beginning of your application. Will blocks until all of the following conditions are met:
* - ZeroTier core service has been initialized
* - Cryptographic identity has been generated or loaded from directory specified by `path`
* - Virtual network is successfully joined
* - IP address is assigned by network controller service
* @param path path directory where cryptographic identities and network configuration files are stored and retrieved
* (`identity.public`, `identity.secret`)
* @param nwid A 16-digit hexidecimal network identifier (e.g. Earth: `8056c2e21c000001`)
* @return 0 if successful; or 1 if failed
*/
ZT_SOCKET_API int ZTCALL zts_startjoin(const char *path, const uint64_t nwid);
/**
* @brief Stops the ZeroTier service, brings down all virtual interfaces in order to stop all traffic processing.
*
* @usage This should be called when the application anticipates not needing any sort of traffic processing for a
* prolonged period of time. The stack driver (with associated timers) will remain active in case future traffic
* processing is required. Note that the application must tolerate a multi-second startup time if zts_start()
* zts_startjoin() is called again. To stop this background thread and free all resources use zts_free() instead.
* @param blocking whether or not this call will block until the entire service is torn down
* @return Returns 0 on success, -1 on failure
*/
ZT_SOCKET_API int ZTCALL zts_stop(int blocking = 1);
/**
* @brief Stops all background services, brings down all interfaces, frees all resources. After calling this function
* an application restart will be required before the library can be used again. This is a blocking call.
*
* @usage This should be called at the end of your program or when you do not anticipate communicating over ZeroTier
* @return Returns 0 on success, -1 on failure
*/
ZT_SOCKET_API int ZTCALL zts_free();
/**
* @brief Return whether the ZeroTier service is currently running
*
* @usage Call this after zts_start()
* @return 1 if running, 0 if not running
*/
ZT_SOCKET_API int ZTCALL zts_core_running();
/**
* @brief Return whether libzt is ready to handle socket API calls. Alternatively you could
* have just called zts_startjoin(path, nwid)
*
* @usage Call this after zts_start()
* @return 1 if running, 0 if not running
*/
ZT_SOCKET_API int ZTCALL zts_ready();
/**
* @brief Return the number of networks currently joined by this node
*
* @usage Call this after zts_start(), zts_startjoin() and/or zts_join()
* @return Number of networks joined by this node
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_get_num_joined_networks();
/**
* @brief Populates a structure with details for a given network
*
* @usage Call this from the application thread any time after the node has joined a network
* @param nwid A 16-digit hexidecimal virtual network ID
* @param nd Pointer to a zts_network_details structure to populate
* @return ZTS_ERR_SERVICE if failed, 0 if otherwise
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_get_network_details(uint64_t nwid, struct zts_network_details *nd);
/**
* @brief Populates an array of structures with details for any given number of networks
*
* @usage Call this from the application thread any time after the node has joined a network
* @param nds Pointer to an array of zts_network_details structures to populate
* @param num Number of zts_network_details structures available to copy data into, will be updated
* to reflect number of structures that were actually populated
* @return ZTS_ERR_SERVICE if failed, 0 if otherwise
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_get_all_network_details(struct zts_network_details *nds, int *num);
/**
* @brief Join a network
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param nwid A 16-digit hexidecimal virtual network ID
* @return 0 if successful, -1 for any failure
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_join(const uint64_t nwid, int blocking = 1);
/**
* @brief Leave a network
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param nwid A 16-digit hexidecimal virtual network ID
* @return 0 if successful, -1 for any failure
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_leave(const uint64_t nwid, int blocking = 1);
/**
* @brief Leaves all networks
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param nwid A 16-digit hexidecimal virtual network ID
* @return 0 if successful, -1 for any failure
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_leave_all(int blocking = 1);
/**
* @brief Orbits a given moon (user-defined root server)
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param moonWorldId A 16-digit hexidecimal world ID
* @param moonSeed A 16-digit hexidecimal seed ID
* @return ZTS_ERR_OK if successful, ZTS_ERR_SERVICE, ZTS_ERR_INVALID_ARG, ZTS_ERR_INVALID_OP if otherwise
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_orbit(uint64_t moonWorldId, uint64_t moonSeed);
/**
* @brief De-orbits a given moon (user-defined root server)
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param moonWorldId A 16-digit hexidecimal world ID
* @return ZTS_ERR_OK if successful, ZTS_ERR_SERVICE, ZTS_ERR_INVALID_ARG, ZTS_ERR_INVALID_OP if otherwise
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_deorbit(uint64_t moonWorldId);
/**
* @brief Copies the configuration path used by ZeroTier into the provided buffer
*
* @usage Use this to determine where ZeroTier is storing identity files
* @param homePath Path to ZeroTier configuration files
* @param len Length of destination buffer
* @return 0 if no error, -1 if invalid argument was supplied
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_get_path(char *homePath, size_t *len);
/**
* @brief Returns the node ID of this instance
*
* @usage Call this after zts_start() and/or when zts_running() returns true
* @return
*/
ZT_SOCKET_API uint64_t ZTCALL zts_get_node_id();
/**
* @brief Returns whether any address has been assigned to the SockTap for this network
*
* @usage This is used as an indicator of readiness for service for the ZeroTier core and stack
* @param nwid Network ID
* @return
*/
ZT_SOCKET_API int ZTCALL zts_has_address(const uint64_t nwid);
/**
* @brief Returns the number of addresses assigned to this node for the given nwid
*
* @param nwid Network ID
* @return The number of addresses assigned
*/
ZT_SOCKET_API int ZTCALL zts_get_num_assigned_addresses(const uint64_t nwid);
/**
* @brief Returns the assigned address located at the given index
*
* @usage The indices of each assigned address are not guaranteed and should only
* be used for iterative purposes.
* @param nwid Network ID
* @param index location of assigned address
* @return The number of addresses assigned
*/
ZT_SOCKET_API int ZTCALL zts_get_address_at_index(
const uint64_t nwid, const int index, struct sockaddr *addr, socklen_t *addrlen);
/**
* @brief Get IP address for this device on a given network
*
* @usage FIXME: Only returns first address found, good enough for most cases
* @param nwid Network ID
* @param addr Destination structure for address
* @param addrlen size of destination address buffer, will be changed to size of returned address
* @return 0 if an address was successfully found, -1 if failure
*/
ZT_SOCKET_API int ZTCALL zts_get_address(
const uint64_t nwid, struct sockaddr_storage *addr, const int address_family);
/**
* @brief Computes a 6PLANE IPv6 address for the given Network ID and Node ID
*
* @usage Can call any time
* @param addr Destination structure for address
* @param nwid Network ID
* @param nodeId Node ID
* @return
*/
ZT_SOCKET_API void ZTCALL zts_get_6plane_addr(
struct sockaddr_storage *addr, const uint64_t nwid, const uint64_t nodeId);
/**
* @brief Computes a RFC4193 IPv6 address for the given Network ID and Node ID
*
* @usage Can call any time
* @param addr Destination structure for address
* @param nwid Network ID
* @param nodeId Node ID
* @return
*/
ZT_SOCKET_API void ZTCALL zts_get_rfc4193_addr(
struct sockaddr_storage *addr, const uint64_t nwid, const uint64_t nodeId);
/**
* @brief Return the number of peers
*
* @usage Call this after zts_start() has succeeded
* @return
*/
ZT_SOCKET_API zts_err_t zts_get_peer_count();
ZT_SOCKET_API zts_err_t zts_get_peers(struct zts_peer_details *pds, int *num);
/**
* @brief Enables the HTTP backplane management system
*
* @usage Call this after zts_start() has succeeded
* @return ZTS_ERR_OK if successful, ZTS_ERR_SERVICE if otherwise
*/
ZT_SOCKET_API zts_err_t zts_enable_http_backplane_mgmt();
/**
* @brief Disables the HTTP backplane management system
*
* @usage Call this after zts_start() has succeeded
* @return ZTS_ERR_OK if successful, ZTS_ERR_SERVICE, ZTS_ERR_INVALID_OP if otherwise
*/
ZT_SOCKET_API zts_err_t zts_disable_http_backplane_mgmt();
/**
* @brief Starts a ZeroTier service in the background
*
* @usage For internal use only.
* @param
* @return
*/
#if defined(_WIN32)
DWORD WINAPI _zts_start_service(LPVOID thread_id);
#else
void *_zts_start_service(void *thread_id);
#endif
/**
* @brief [Should not be called from user application] This function must be surrounded by
* ZT service locks. It will determine if it is currently safe and allowed to operate on
* the service.
* @usage Can be called at any time
* @return 1 or 0
*/
int _zts_can_perform_service_operation();
/**
* @brief [Should not be called from user application] Returns whether or not the node is
* online.
* @usage Can be called at any time
* @return 1 or 0
*/
int _zts_node_online();
/**
* @brief [Should not be called from user application] Adjusts the delay multiplier for the
* network stack driver thread.
* @usage Can be called at any time
*/
void _hibernate_if_needed();
#ifdef __cplusplus
}
#endif
} // namespace ZeroTier
#endif // _H

View File

@@ -63,22 +63,86 @@ typedef int socklen_t;
#include <Windows.h> #include <Windows.h>
#endif #endif
/*
#ifdef _USING_LWIP_DEFINITIONS_ #ifdef _USING_LWIP_DEFINITIONS_
#include "lwip/sockets.h" #include "lwip/sockets.h"
#endif #endif
*/
#include "Constants.hpp"
#include "Defs.hpp"
#include "ServiceControls.hpp"
class InetAddress;
class VirtualTap;
#if defined(_MSC_VER) #if defined(_MSC_VER)
#include <BaseTsd.h> #include <BaseTsd.h>
typedef SSIZE_T ssize_t; typedef SSIZE_T ssize_t;
#endif #endif
namespace ZeroTier {
#ifdef __cplusplus
extern "C" {
#endif
// Custom errno to prevent conflicts with platform's own errno
extern int zts_errno;
typedef int zts_err_t;
#ifdef __cplusplus
}
#endif
/**
* The system port upon which ZT traffic is sent and received
*/
#define ZTS_DEFAULT_PORT 9994
//////////////////////////////////////////////////////////////////////////////
// Control API error codes //
//////////////////////////////////////////////////////////////////////////////
#define ZTS_ERR_OK 0 // Everything is ok
#define ZTS_ERR_INVALID_ARG -1 // A parameter provided by the user application is invalid (e.g. our of range, NULL, etc)
#define ZTS_ERR_SERVICE -2 // The service isn't initialized or is for some other reason currently unavailable
#define ZTS_ERR_INVALID_OP -3 // For some reason this API operation is not permitted (perhaps the service is still starting?)
//////////////////////////////////////////////////////////////////////////////
// Control API event codes //
//////////////////////////////////////////////////////////////////////////////
#define ZTS_EVENT_NONE -1
#define ZTS_EVENT_NODE_UP 0
// Standard node events
#define ZTS_EVENT_NODE_OFFLINE 1
#define ZTS_EVENT_NODE_ONLINE 2
#define ZTS_EVENT_NODE_DOWN 3
#define ZTS_EVENT_NODE_IDENTITY_COLLISION 4
// libzt node events
#define ZTS_EVENT_NODE_UNRECOVERABLE_ERROR 16
#define ZTS_EVENT_NODE_NORMAL_TERMINATION 17
// Network-specific events
#define ZTS_EVENT_NETWORK_NOT_FOUND 32
#define ZTS_EVENT_NETWORK_CLIENT_TOO_OLD 33
#define ZTS_EVENT_NETWORK_REQUESTING_CONFIG 34
#define ZTS_EVENT_NETWORK_OK 35
#define ZTS_EVENT_NETWORK_ACCESS_DENIED 36
#define ZTS_EVENT_NETWORK_READY_IP4 37
#define ZTS_EVENT_NETWORK_READY_IP6 38
#define ZTS_EVENT_NETWORK_DOWN 39
//
#define ZTS_EVENT_NETWORK_STACK_UP 48
#define ZTS_EVENT_NETWORK_STACK_DOWN 49
// lwIP netif events
#define ZTS_EVENT_NETIF_UP_IP4 64
#define ZTS_EVENT_NETIF_UP_IP6 65
#define ZTS_EVENT_NETIF_DOWN_IP4 66
#define ZTS_EVENT_NETIF_DOWN_IP6 67
#define ZTS_EVENT_NETIF_REMOVED 68
#define ZTS_EVENT_NETIF_LINK_UP 69
#define ZTS_EVENT_NETIF_LINK_DOWN 70
#define ZTS_EVENT_NETIF_NEW_ADDRESS 71
// Peer events
#define ZTS_EVENT_PEER_P2P 96
#define ZTS_EVENT_PEER_RELAY 97
#define ZTS_EVENT_PEER_UNREACHABLE 98
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// Common definitions and structures for interacting with the ZT socket API // // Common definitions and structures for interacting with the ZT socket API //
// This is a subset of lwip/sockets.h, lwip/arch.h, and lwip/inet.h // // This is a subset of lwip/sockets.h, lwip/arch.h, and lwip/inet.h //
@@ -196,7 +260,7 @@ typedef SSIZE_T ssize_t;
#error "external ZTS_FD_SETSIZE too small for number of sockets" #error "external ZTS_FD_SETSIZE too small for number of sockets"
#endif // FD_SET #endif // FD_SET
#if !defined(_USING_LWIP_DEFINITIONS_) #if defined(_USING_LWIP_DEFINITIONS_)
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
@@ -322,15 +386,454 @@ struct sockaddr_ll {
#endif #endif
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// Socket API // // Subset of: ZeroTierOne.h //
// We redefine a few ZT structures here so that we don't need to drag the //
// entire ZeroTierOne.h file into the user application //
//////////////////////////////////////////////////////////////////////////////
/**
* Maximum address assignments per network
*/
#define ZTS_MAX_ASSIGNED_ADDRESSES 16
/**
* Maximum routes per network
*/
#define ZTS_MAX_NETWORK_ROUTES 32
/**
* Maximum number of direct network paths to a given peer
*/
#define ZT_MAX_PEER_NETWORK_PATHS 16
/**
* What trust hierarchy role does this peer have?
*/
enum zts_peer_role
{
ZTS_PEER_ROLE_LEAF = 0, // ordinary node
ZTS_PEER_ROLE_MOON = 1, // moon root
ZTS_PEER_ROLE_PLANET = 2 // planetary root
};
/**
* A structure used to represent a virtual network route
*/
struct zts_virtual_network_route
{
/**
* Target network / netmask bits (in port field) or NULL or 0.0.0.0/0 for default
*/
struct sockaddr_storage target;
/**
* Gateway IP address (port ignored) or NULL (family == 0) for LAN-local (no gateway)
*/
struct sockaddr_storage via;
/**
* Route flags
*/
uint16_t flags;
/**
* Route metric (not currently used)
*/
uint16_t metric;
};
/**
* A structure used to convey network-specific details to the user application
*/
struct zts_network_details
{
/**
* Network ID
*/
uint64_t nwid;
/**
* Maximum Transmission Unit size for this network
*/
int mtu;
/**
* Number of addresses (actually) assigned to the node on this network
*/
short num_addresses;
/**
* Array of IPv4 and IPv6 addresses assigned to the node on this network
*/
struct sockaddr_storage addr[ZTS_MAX_ASSIGNED_ADDRESSES];
/**
* Number of routes
*/
unsigned int num_routes;
/**
* Array of IPv4 and IPv6 addresses assigned to the node on this network
*/
struct zts_virtual_network_route routes[ZTS_MAX_NETWORK_ROUTES];
};
/**
* Physical network path to a peer
*/
struct zts_physical_path
{
/**
* Address of endpoint
*/
struct sockaddr_storage address;
/**
* Time of last send in milliseconds or 0 for never
*/
uint64_t lastSend;
/**
* Time of last receive in milliseconds or 0 for never
*/
uint64_t lastReceive;
/**
* Is this a trusted path? If so this will be its nonzero ID.
*/
uint64_t trustedPathId;
/**
* Is path expired?
*/
int expired;
/**
* Is path preferred?
*/
int preferred;
};
/**
* Peer status result buffer
*/
struct zts_peer_details
{
/**
* ZeroTier address (40 bits)
*/
uint64_t address;
/**
* Remote major version or -1 if not known
*/
int versionMajor;
/**
* Remote minor version or -1 if not known
*/
int versionMinor;
/**
* Remote revision or -1 if not known
*/
int versionRev;
/**
* Last measured latency in milliseconds or -1 if unknown
*/
int latency;
/**
* What trust hierarchy role does this device have?
*/
enum zts_peer_role role;
/**
* Number of paths (size of paths[])
*/
unsigned int pathCount;
/**
* Known network paths to peer
*/
zts_physical_path paths[ZT_MAX_PEER_NETWORK_PATHS];
};
/**
* List of peers
*/
struct zts_peer_list
{
zts_peer_details *peers;
unsigned long peerCount;
};
//////////////////////////////////////////////////////////////////////////////
// ZeroTier Service Controls //
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
// Custom errno to prevent conflicts with platform's own errno /**
extern int zts_errno; * @brief Starts the ZeroTier service and notifies user application of events via callback
*
* @usage Should be called at the beginning of your application. Will blocks until all of the following conditions are met:
* - ZeroTier core service has been initialized
* - Cryptographic identity has been generated or loaded from directory specified by `path`
* - Virtual network is successfully joined
* - IP address is assigned by network controller service
* @param path path directory where cryptographic identities and network configuration files are stored and retrieved
* (`identity.public`, `identity.secret`)
* @param userCallbackFunc User-specified callback for ZeroTier events
* @return 0 if successful; or 1 if failed
*/
ZT_SOCKET_API int ZTCALL zts_start(const char *path, void (*userCallbackFunc)(uint64_t, int), int port = ZTS_DEFAULT_PORT);
/**
* @brief Stops the ZeroTier service, brings down all virtual interfaces in order to stop all traffic processing.
*
* @usage This should be called when the application anticipates not needing any sort of traffic processing for a
* prolonged period of time. The stack driver (with associated timers) will remain active in case future traffic
* processing is required. Note that the application must tolerate a multi-second startup time if zts_start()
* zts_startjoin() is called again. To stop this background thread and free all resources use zts_free() instead.
* @return Returns 0 on success, -1 on failure
*/
ZT_SOCKET_API int ZTCALL zts_stop();
/**
* @brief Stops all background services, brings down all interfaces, frees all resources. After calling this function
* an application restart will be required before the library can be used again. This is a blocking call.
*
* @usage This should be called at the end of your program or when you do not anticipate communicating over ZeroTier
* @return Returns 0 on success, -1 on failure
*/
ZT_SOCKET_API int ZTCALL zts_free();
/**
* @brief Return whether the ZeroTier service is currently running
*
* @usage Call this after zts_start()
* @return 1 if running, 0 if not running
*/
ZT_SOCKET_API int ZTCALL zts_core_running();
/**
* @brief Return the number of networks currently joined by this node
*
* @usage Call this after zts_start(), zts_startjoin() and/or zts_join()
* @return Number of networks joined by this node
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_get_num_joined_networks();
/**
* @brief Populates a structure with details for a given network
*
* @usage Call this from the application thread any time after the node has joined a network
* @param nwid A 16-digit hexidecimal virtual network ID
* @param nd Pointer to a zts_network_details structure to populate
* @return ZTS_ERR_SERVICE if failed, 0 if otherwise
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_get_network_details(uint64_t nwid, struct zts_network_details *nd);
/**
* @brief Populates an array of structures with details for any given number of networks
*
* @usage Call this from the application thread any time after the node has joined a network
* @param nds Pointer to an array of zts_network_details structures to populate
* @param num Number of zts_network_details structures available to copy data into, will be updated
* to reflect number of structures that were actually populated
* @return ZTS_ERR_SERVICE if failed, 0 if otherwise
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_get_all_network_details(struct zts_network_details *nds, int *num);
/**
* @brief Join a network
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param nwid A 16-digit hexidecimal virtual network ID
* @return 0 if successful, -1 for any failure
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_join(const uint64_t nwid);
/**
* @brief Leave a network
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param nwid A 16-digit hexidecimal virtual network ID
* @return 0 if successful, -1 for any failure
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_leave(const uint64_t nwid);
/**
* @brief Leaves all networks
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @return 0 if successful, -1 for any failure
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_leave_all();
/**
* @brief Orbits a given moon (user-defined root server)
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param moonWorldId A 16-digit hexidecimal world ID
* @param moonSeed A 16-digit hexidecimal seed ID
* @return ZTS_ERR_OK if successful, ZTS_ERR_SERVICE, ZTS_ERR_INVALID_ARG, ZTS_ERR_INVALID_OP if otherwise
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_orbit(uint64_t moonWorldId, uint64_t moonSeed);
/**
* @brief De-orbits a given moon (user-defined root server)
*
* @usage Call this from application thread. Only after zts_start() has succeeded
* @param moonWorldId A 16-digit hexidecimal world ID
* @return ZTS_ERR_OK if successful, ZTS_ERR_SERVICE, ZTS_ERR_INVALID_ARG, ZTS_ERR_INVALID_OP if otherwise
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_deorbit(uint64_t moonWorldId);
/**
* @brief Copies the configuration path used by ZeroTier into the provided buffer
*
* @usage Use this to determine where ZeroTier is storing identity files
* @param homePath Path to ZeroTier configuration files
* @param len Length of destination buffer
* @return 0 if no error, -1 if invalid argument was supplied
*/
ZT_SOCKET_API zts_err_t ZTCALL zts_get_path(char *homePath, size_t *len);
/**
* @brief Returns the node ID of this instance
*
* @usage Call this after zts_start() and/or when zts_running() returns true
* @return
*/
ZT_SOCKET_API uint64_t ZTCALL zts_get_node_id();
/**
* @brief Returns whether any address has been assigned to the SockTap for this network
*
* @usage This is used as an indicator of readiness for service for the ZeroTier core and stack
* @param nwid Network ID
* @return
*/
ZT_SOCKET_API int ZTCALL zts_has_address(const uint64_t nwid);
/**
* @brief Returns the number of addresses assigned to this node for the given nwid
*
* @param nwid Network ID
* @return The number of addresses assigned
*/
ZT_SOCKET_API int ZTCALL zts_get_num_assigned_addresses(const uint64_t nwid);
/**
* @brief Returns the assigned address located at the given index
*
* @usage The indices of each assigned address are not guaranteed and should only
* be used for iterative purposes.
* @param nwid Network ID
* @param index location of assigned address
* @return The number of addresses assigned
*/
ZT_SOCKET_API int ZTCALL zts_get_address_at_index(
const uint64_t nwid, const int index, struct sockaddr *addr, socklen_t *addrlen);
/**
* @brief Get IP address for this device on a given network
*
* @usage FIXME: Only returns first address found, good enough for most cases
* @param nwid Network ID
* @param addr Destination structure for address
* @param addrlen size of destination address buffer, will be changed to size of returned address
* @return 0 if an address was successfully found, -1 if failure
*/
ZT_SOCKET_API int ZTCALL zts_get_address(
const uint64_t nwid, struct sockaddr_storage *addr, const int address_family);
/**
* @brief Computes a 6PLANE IPv6 address for the given Network ID and Node ID
*
* @usage Can call any time
* @param addr Destination structure for address
* @param nwid Network ID
* @param nodeId Node ID
* @return
*/
ZT_SOCKET_API void ZTCALL zts_get_6plane_addr(
struct sockaddr_storage *addr, const uint64_t nwid, const uint64_t nodeId);
/**
* @brief Computes a RFC4193 IPv6 address for the given Network ID and Node ID
*
* @usage Can call any time
* @param addr Destination structure for address
* @param nwid Network ID
* @param nodeId Node ID
* @return
*/
ZT_SOCKET_API void ZTCALL zts_get_rfc4193_addr(
struct sockaddr_storage *addr, const uint64_t nwid, const uint64_t nodeId);
/**
* @brief Return the number of peers
*
* @usage Call this after zts_start() has succeeded
* @return
*/
ZT_SOCKET_API zts_err_t zts_get_peer_count();
ZT_SOCKET_API zts_err_t zts_get_peers(struct zts_peer_details *pds, int *num);
/**
* @brief Determines whether a peer is reachable via a P2P connection
* or is being relayed via roots.
*
* @usage
* @param nodeId The ID of the peer to check
* @return The status of a peer
*/
ZT_SOCKET_API zts_err_t zts_get_peer_status(uint64_t nodeId);
/**
* @brief Starts a ZeroTier service in the background
*
* @usage For internal use only.
* @param
* @return
*/
#if defined(_WIN32)
DWORD WINAPI _zts_start_service(LPVOID thread_id);
#else
void *_zts_start_service(void *thread_id);
#endif
/**
* @brief [Should not be called from user application] This function must be surrounded by
* ZT service locks. It will determine if it is currently safe and allowed to operate on
* the service.
* @usage Can be called at any time
* @return 1 or 0
*/
int _zts_can_perform_service_operation();
/**
* @brief [Should not be called from user application] Returns whether or not the node is
* online.
* @usage Can be called at any time
* @return 1 or 0
*/
int _zts_node_online();
int zts_ready();
//////////////////////////////////////////////////////////////////////////////
// Socket API //
//////////////////////////////////////////////////////////////////////////////
/** /**
* @brief Create a socket * @brief Create a socket
@@ -679,4 +1182,6 @@ ZT_SOCKET_API zts_err_t ZTCALL zts_del_dns_nameserver(struct sockaddr *addr);
} // extern "C" } // extern "C"
#endif #endif
} // namespace ZeroTier
#endif // _H #endif // _H

View File

@@ -1,7 +0,0 @@
cd ../../
cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=DEBUG
cmake --build build
copy bin\lib\Debug\*.lib packages\pypi
cd packages\pypi
pip3 install wheel twine
py setup.py bdist_wheel

View File

@@ -1,25 +0,0 @@
### Projects and scripts for building various packages
Pre-built binaries [here](https://download.zerotier.com/RELEASES/)
***
### To build entire distribution package:
Step 1: On a Windows host, run `make dist`. Outputs will be copied to `prebuilt/(debug|release)/(win32/win64)`
Step 2: On a Linux host, run `make dist`. Outputs will be copied to `prebuilt/linux-$ARCH`
Step 3: On a macOS host, run `make dist`. Outputs will be copied to `prebuilt/macos-$ARCH`
Step 4: Perform any necessary modifications to the generated projects (such as Xcode projects)
Step 5: Re-run `make dist`
Step 6: On a Unix-like host, run `make package`. This will zip everything up into a pair of `tar.gz` files in `products`
***
### iOS
- In `packages/xcode_ios`, change SDK from `macOS` to `iOS`
- Build
### Android
This project is not currently generated by CMake, but does utilize the `CMakeLists.txt` and generates a `.aar` Android Archive which can be imported into an Android Studio project as a library. An example of this library's usage can be found in [examples/android](examples/android). Further examples of the libzt JNI API can be seen in [examples/java](examples/java).

View File

@@ -1,10 +0,0 @@
*.iml
.gradle
/local.properties
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
.DS_Store
/build
/captures
.externalNativeBuild

17
packages/android/.project Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>android</name>
<comment>Project android created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View File

@@ -1 +0,0 @@
/build

View File

@@ -1,42 +0,0 @@
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
ndk {
// Tells Gradle to build outputs for the following ABIs and package
// them into your APK.
abiFilters 'armeabi-v7a'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "../../../CMakeLists.txt"
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

View File

@@ -1,21 +0,0 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -1,26 +0,0 @@
package com.example.zerotier;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.zerotier", appContext.getPackageName());
}
}

View File

@@ -1,25 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zerotier">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -1,54 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
package com.zerotier.libzt;
public class ZTFDSet
{
byte[] fds_bits = new byte[1024];
public void CLR(int fd)
{
fds_bits[fd] = 0x00;
}
public boolean ISSET(int fd)
{
return fds_bits[fd] == 0x01;
}
public void SET(int fd)
{
fds_bits[fd] = 0x01;
}
public void ZERO()
{
for (int i=0; i<1024; i++) {
fds_bits[i] = 0x00;
}
}
}

View File

@@ -1,92 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
package com.zerotier.libzt;
import com.zerotier.libzt.ZeroTier;
import java.net.InetAddress;
// Designed to transport address information across the JNI boundary
public class ZTSocketAddress
{
public byte[] _ip6 = new byte[16];
public byte[] _ip4 = new byte[4];
public int _family;
public int _port; // Also reused for netmask or prefix
public ZTSocketAddress() {}
public ZTSocketAddress(String ipStr, int port)
{
if(ipStr.contains(":")) {
_family = ZeroTier.AF_INET6;
try {
InetAddress ip = InetAddress.getByName(ipStr);
_ip6 = ip.getAddress();
}
catch (Exception e) { }
}
else if(ipStr.contains(".")) {
_family = ZeroTier.AF_INET;
try {
InetAddress ip = InetAddress.getByName(ipStr);
_ip4 = ip.getAddress();
}
catch (Exception e) { }
}
_port = port;
}
public int getPort() { return _port; }
public int getNetmask() { return _port; }
public int getPrefix() { return _port; }
private String ipString()
{
if (_family == ZeroTier.AF_INET) {
try {
InetAddress inet = InetAddress.getByAddress(_ip4);
return "" + inet.getHostAddress();
} catch (Exception e) {
System.out.println(e);
}
}
if (_family == ZeroTier.AF_INET6) {
try {
InetAddress inet = InetAddress.getByAddress(_ip6);
return "" + inet.getHostAddress();
} catch (Exception e) {
System.out.println(e);
}
}
return "";
}
public String toString() { return ipString() + ":" + _port; }
public String toCIDR() { return ipString() + "/" + _port; }
}

View File

@@ -1,82 +0,0 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* 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 <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
package com.zerotier.libzt;
import java.net.*;
public class ZeroTier {
public static int AF_INET = 2;
public static int AF_INET6 = 30;
public static int SOCK_STREAM = 1;
public static int SOCK_DGRAM = 2;
public static int O_APPEND = 1024;
public static int O_NONBLOCK = 2048;
public static int O_ASYNC = 8192;
public static int O_DIRECT = 65536;
public static int O_NOATIME = 262144;
public static int F_GETFL = 3;
public static int F_SETFL = 4;
public native void start(String homePath, boolean blocking);
public native void startjoin(String homePath, long nwid);
public native void stop();
public native boolean core_running();
public native boolean stack_running();
public native boolean ready();
public native int join(long nwid);
public native int leave(long nwid);
public native String get_path();
public native long get_node_id();
public native int get_num_assigned_addresses(long nwid);
public native boolean get_address_at_index(long nwid, int index, ZTSocketAddress addr);
public native boolean has_address(long nwid);
public native boolean get_address(long nwid, int address_family, ZTSocketAddress addr);
public native void get_6plane_addr(long nwid, long nodeId, ZTSocketAddress addr);
public native void get_rfc4193_addr(long nwid, long nodeId, ZTSocketAddress addr);
public native int socket(int family, int type, int protocol);
public native int connect(int fd, ZTSocketAddress addr);
public native int bind(int fd, ZTSocketAddress addr);
public native int listen(int fd, int backlog);
public native int accept(int fd, ZTSocketAddress addr);
public native int accept4(int fd, String addr, int port);
public native int close(int fd);
public native int setsockopt(int fd, int level, int optname, int optval, int optlen);
public native int getsockopt(int fd, int level, int optname, int optval, int optlen);
public native int sendto(int fd, byte[] buf, int flags, ZTSocketAddress addr);
public native int send(int fd, byte[] buf, int flags);
public native int recv(int fd, byte[] buf, int flags);
public native int recvfrom(int fd, byte[] buf, int flags, ZTSocketAddress addr);
public native int read(int fd, byte[] buf);
public native int write(int fd, byte[] buf);
public native int shutdown(int fd, int how);
public native boolean getsockname(int fd, ZTSocketAddress addr);
public native int getpeername(int fd, ZTSocketAddress addr);
public native int fcntl(int sock, int cmd, int flag);
public native int select(int nfds, ZTFDSet readfds, ZTFDSet writefds, ZTFDSet exceptfds, int timeout_sec, int timeout_usec);
}

View File

@@ -1,75 +0,0 @@
package com.example.zerotier;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.zerotier.libzt.ZeroTier;
import com.zerotier.libzt.ZTSocketAddress;
import com.zerotier.libzt.ZTFDSet;
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("zt");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ZeroTier libzt = new ZeroTier();
new Thread(new Runnable() {
public void run() {
final String path = getApplicationContext().getFilesDir() + "/zerotier";
long nwid = 0xac9afb023544b071L;
// Test modes
boolean blocking_start_call = true;
boolean client_mode = false;
boolean tcp = false;
boolean loop = true;
int fd = -1, client_fd = -1, err, r, w, length = 0, flags = 0;
byte[] rxBuffer;
byte[] txBuffer = "welcome to the machine".getBytes();
String remoteAddrStr = "11.7.7.224";
String localAddrStr = "1.2.3.4";
int portNo = 4040;
ZTSocketAddress remoteAddr, localAddr;
ZTSocketAddress sockname = new ZTSocketAddress();
ZTSocketAddress addr = new ZTSocketAddress();
// METHOD 1 (easy)
// Blocking call that waits for all components of the service to start
System.out.println("Starting ZT service...");
if (blocking_start_call) {
libzt.startjoin(path, nwid);
}
System.out.println("ZT service ready.");
// Device/Node address info
System.out.println("path=" + libzt.get_path());
long nodeId = libzt.get_node_id();
System.out.println("nodeId=" + Long.toHexString(nodeId));
int numAddresses = libzt.get_num_assigned_addresses(nwid);
System.out.println("this node has (" + numAddresses + ") assigned addresses on network " + Long.toHexString(nwid));
for (int i=0; i<numAddresses; i++) {
libzt.get_address_at_index(nwid, i, sockname);
//System.out.println("address[" + i + "] = " + sockname.toString()); // ip:port
System.out.println("address[" + i + "] = " + sockname.toCIDR());
}
libzt.get_6plane_addr(nwid, nodeId, sockname);
System.out.println("6PLANE address = " + sockname.toCIDR());
}
}).start();
}
}

View File

@@ -1,34 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>

View File

@@ -1,170 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>

View File

@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/sample_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

View File

@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

View File

@@ -1,3 +0,0 @@
<resources>
<string name="app_name">ZeroTier</string>
</resources>

View File

@@ -1,11 +0,0 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

View File

@@ -1,17 +0,0 @@
package com.example.zerotier;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}

View File

@@ -1,27 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@@ -1,13 +0,0 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

View File

@@ -1,6 +0,0 @@
#Wed Jul 18 09:57:38 PDT 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

View File

@@ -1,172 +0,0 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -1,84 +0,0 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1 +0,0 @@
include ':app'

View File

@@ -1,4 +0,0 @@
rd /S /Q bin
rd /S /Q build
rd /S /Q WinBuild32
rd /S /Q WinBuild64

View File

@@ -1,7 +0,0 @@
#!/bin/bash
rm -rf bin build products tmp
rm -f *.o *.s *.exp *.lib .depend* *.core core
rm -rf .depend
find . -type f \( -name '*.o' -o -name '*.o.d' -o -name \
'*.out' -o -name '*.log' -o -name '*.dSYM' -o -name '*.class' \) -delete

View File

@@ -1,88 +0,0 @@
REM Build all target configurations and copy results into "prebuilt"
set PrebuiltDebugWin32Dir=staging\debug\win32
set PrebuiltDebugWin64Dir=staging\debug\win64
set PrebuiltReleaseWin32Dir=staging\release\win32
set PrebuiltReleaseWin64Dir=staging\release\win64
mkdir %PrebuiltDebugWin32Dir%
mkdir %PrebuiltDebugWin64Dir%
mkdir %PrebuiltReleaseWin32Dir%
mkdir %PrebuiltReleaseWin64Dir%
set DebugWinBuildDir=bin\lib\Debug
set ReleaseWinBuildDir=bin\lib\Release
mkdir WinBuild32 & pushd WinBuild32
cmake -G "Visual Studio 15 2017" ../
popd
mkdir WinBuild64 & pushd WinBuild64
cmake -G "Visual Studio 15 2017 Win64" ../
popd
cmake --build WinBuild32 --config Release
cmake --build WinBuild32 --config Debug
copy %DebugWinBuildDir%\zt-static.lib %PrebuiltDebugWin32Dir%\zt.lib
copy %DebugWinBuildDir%\zt-shared.dll %PrebuiltDebugWin32Dir%\zt.dll
copy %ReleaseWinBuildDir%\zt-static.lib %PrebuiltReleaseWin32Dir%\zt.lib
copy %ReleaseWinBuildDir%\zt-shared.dll %PrebuiltReleaseWin32Dir%\zt.dll
cmake --build WinBuild64 --config Release
cmake --build WinBuild64 --config Debug
copy %DebugWinBuildDir%\zt-static.lib %PrebuiltDebugWin64Dir%\zt.lib
copy %DebugWinBuildDir%\zt-shared.dll %PrebuiltDebugWin64Dir%\zt.dll
copy %ReleaseWinBuildDir%\zt-static.lib %PrebuiltReleaseWin64Dir%\zt.lib
copy %ReleaseWinBuildDir%\zt-shared.dll %PrebuiltReleaseWin64Dir%\zt.dll
rd /S /Q bin
# Build with JNI
mkdir WinBuild32 & pushd WinBuild32
cmake -D JNI:BOOL=ON -G "Visual Studio 15 2017" ../
popd
mkdir WinBuild64 & pushd WinBuild64
cmake -D JNI:BOOL=ON -G "Visual Studio 15 2017 Win64" ../
popd
cmake --build WinBuild32 --config Release
cmake --build WinBuild32 --config Debug
REM Build JAR file
REM release variant
cd packages\java
del com/zerotier/libzt/*.class
move ..\..\%ReleaseWinBuildDir%\zt-shared.dll zt.dll
javac com/zerotier/libzt/*.java
jar cf zt.jar zt.dll com/zerotier/libzt/*.class
move zt.jar ..\..\%PrebuiltReleaseWin32Dir%
REM debug variant
del com/zerotier/libzt/*.class
move ..\..\%DebugWinBuildDir%\zt-shared.dll zt.dll
javac com/zerotier/libzt/*.java
jar cf zt.jar zt.dll com/zerotier/libzt/*.class
move zt.jar ..\..\%PrebuiltDebugWin32Dir%
popd
popd
cmake --build WinBuild64 --config Release
cmake --build WinBuild64 --config Debug
REM Build JAR file
REM release variant
cd packages\java
del com/zerotier/libzt/*.class
move ..\..\%ReleaseWinBuildDir%\zt-shared.dll zt.dll
javac com/zerotier/libzt/*.java
jar cf zt.jar zt.dll com/zerotier/libzt/*.class
move zt.jar ..\..\%PrebuiltReleaseWin64Dir%
REM debug variant
del com/zerotier/libzt/*.class
move ..\..\%DebugWinBuildDir%\zt-shared.dll zt.dll
javac com/zerotier/libzt/*.java
jar cf zt.jar zt.dll com/zerotier/libzt/*.class
move zt.jar ..\..\%PrebuiltDebugWin64Dir%
popd
popd

Some files were not shown because too many files have changed in this diff Show More