Flattened examples directory

This commit is contained in:
Joseph Henry
2018-07-19 17:35:42 -07:00
parent 71fe3c867e
commit 60549bc8a3
74 changed files with 785 additions and 831 deletions

View File

@@ -1,3 +0,0 @@
## Encrypted P2P chat in the terminal.
See: [https://github.com/zerotier/cathode](https://github.com/zerotier/cathode)

View File

@@ -1,5 +0,0 @@
## libzt C++ examples
***
- [simple_client_server](simple_client_server): No-frills C++ client and server using libzt sockets
- [cxproj_dll](cxproj_dll): Example of how to use libzt in DLL form in Visual Studio

View File

@@ -1,4 +0,0 @@
## libzt C# examples
***
- [csproj_dll](csproj_dll): Example of how to use libzt in DLL form in Visual Studio

View File

@@ -1,160 +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.
*/
// Simple Java example for libzt using JNI
import zerotier.ZeroTier;
import java.net.*;
import java.lang.Thread;
public class ExampleApp {
public native int loadsymbols();
public native void startOneService();
// load libzt.dylib or libzt.so
static {
System.loadLibrary("zt");
}
public static void main(String[] args) {
final ZeroTier libzt = new ZeroTier();
new Thread(new Runnable() {
public void run() {
String path = "/Users/joseph/op/zt/libzt/ztjni";
long nwid = 0xa09acf0233ac70fdL;
// METHOD 1 (easy)
// Blocking call that waits for the core, userspace stack and IP assignment before unblocking
if (true)
{
libzt.startjoin(path, nwid);
}
// METHOD 2
// Optionally-nonblocking call. You'll have to use the below process to determine when you
// are allowed to stack making socket calls. The advantage of this method is that you can
// get your nodeId before joining the network.
if (false) {
libzt.start(path, true);
// Wait for core service to start
while(!libzt.core_running()) {
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
System.out.println("core started");
long nodeId = libzt.get_node_id();
System.out.println("nodeId=" + Long.toHexString(nodeId));
libzt.join(nwid);
// Wait for userspace stack to start, we trigger this by joining a network
while(!libzt.stack_running()) {
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
System.out.println("core and stack started, now ready for socket API calls");
int num_addresses = libzt.get_num_assigned_addresses(nwid);
System.out.println("number of assigned addresses for this node on this network = " + String.valueOf(num_addresses));
// get IPv4 address
//InetAddress assigned = libzt.get_address(nwid, libzt.AF_INET6);
//System.out.println("assigned address = " + assigned.toString());
// get address at arbitrary (index < num_addresses)
//assigned = libzt.get_address_at_index(nwid, 0);
//System.out.println("assigned address = " + assigned.toString());
// get IPv6 address
//assigned = libzt.get_address(nwid, libzt.AF_INET6);
//System.out.println("assigned address = " + assigned.toString());
String homePath = libzt.get_path();
System.out.println("homePath=" + homePath);
while(!libzt.has_address(nwid)) {
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
//InetAddress assigned = libzt.get_address(nwid);
//System.out.println("assigned address = " + assigned.toString());
int fd = 0, err = 0;
if ((fd = libzt.socket(libzt.AF_INET, libzt.SOCK_STREAM, 0)) < 0) {
System.out.println("error creating socket");
return;
}
System.out.println("Created socket");
while(true)
{
try { Thread.sleep(3000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
/*
InetSocketAddress remoteAddr = new InetSocketAddress("172.27.54.9", 3434);
if ((err = libzt.connect(fd, remoteAddr)) < 0) {
System.out.println("error connecting");
return;
}
*/
/*
InetSocketAddress localAddr = new InetSocketAddress("0.0.0.0", 3434);
if ((err = libzt.bind(fd, addr)) < 0) {
System.out.println("error binding socket to virtual interface");
return;
}
*/
}
}).start();
while(true)
{
try { Thread.sleep(3000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
}

View File

@@ -1,6 +0,0 @@
node_modules/*
darwin
zto
include
libzt-build
package-lock.json

View File

@@ -1,5 +0,0 @@
# Setup
- Make sure you build libzt first
- `npm install`
- `node test.js`
- `npm run -- node-gyp rebuild` if you modify binding.cc or libzt

View File

@@ -1,8 +0,0 @@
# Automatically generated file. Edits will be lost.
# Based on: autogypi.json
{
"includes": [
"node_modules/nbind/src/nbind-common.gypi"
]
}

View File

@@ -1,11 +0,0 @@
# Automatically generated file. Edits will be lost.
# Based on: autogypi.json
{
"include_dirs": [
"node_modules/nan"
],
"includes": [
"node_modules/nbind/src/nbind.gypi"
]
}

View File

@@ -1,6 +0,0 @@
{
"dependencies": [
"nbind"
],
"includes": []
}

View File

@@ -1,72 +0,0 @@
#include <string>
#include <iostream>
#include "libzt.h"
struct ZT {
static int running() {
return zts_running();
}
static void simpleStart(const char *path, const char *nwid) {
zts_startjoin(path, nwid);
}
static void stop() {
zts_stop();
}
static char* getDeviceId() {
char* id = new char [ZT_ID_LEN + 1];
zts_get_id(id);
return id;
}
static char* getIpV4Address(const char *nwid) {
char* addr_str = new char [INET_ADDRSTRLEN];
zts_get_ipv4_address(nwid, addr_str, INET_ADDRSTRLEN);
return addr_str;
}
static int socket() {åå
return zts_socket(AF_INET, SOCK_STREAM, 0);
}
static int bind(int sockfd, const char *addrStr, int port) {
struct sockaddr_in addr;
addr.sin_addr.s_addr = inet_addr(addrStr);
addr.sin_family = AF_INET;
addr.sin_port = htons( port );
return zts_bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr));
}
static int listen(int sockfd) {
return zts_listen(sockfd, 1);
}
static int accept(int sockfd) {
struct sockaddr_in client;
int c = sizeof(struct sockaddr_in);
int accept_fd = zts_accept(sockfd, (struct sockaddr *)&client, (socklen_t*)&c);
return accept_fd;
}
};
#include "nbind/nbind.h"
NBIND_CLASS(ZT) {
method(accept);
method(bind);
method(getDeviceId);
method(getIpV4Address);
method(running);
method(simpleStart);
method(socket);
method(stop);
method(listen);
}

View File

@@ -1,11 +0,0 @@
{
"targets": [
{
"include_dirs": ["libzt/build/darwin", "libzt/include", "libzt/zto/include"],
"libraries": ["<!(pwd)/libzt/build/darwin/libzt.a"],
"includes": ["auto.gypi"],
"sources": ["binding.cc"]
}
],
"includes": ["auto-top.gypi"]
}

View File

@@ -1,28 +0,0 @@
var http = require('http')
var zt = require('./libzt')
var earth = '8056c2e21c000001'
var listenPort = 8766
zt.simpleStart('./tmp/' + earth, earth)
var addr = zt.getIpV4Address(earth).split('/')[0]
var socket = zt.socket()
zt.bindPort(socket, addr, listenPort)
// zt.listen(socket)
console.log('socket fd', socket)
console.log('ip a', addr)
console.log(`http://${addr}:${listenPort}`)
var server = http.createServer(function (request, response) {
response.writeHead(200, { 'Content-Type': 'text/plain' })
response.end('Hello World\n')
})
// attempt to listen to file descriptor.
// doesn't work, but would be cool!
server.listen({ fd: socket })
// listen on localhost:8765. works
// server.listen(8765)

View File

@@ -1,13 +0,0 @@
var nbind = require('nbind')
var ZT = nbind.init().lib.ZT
module.exports = {
accept: ZT.accept,
bindPort: ZT.bind,
getDeviceId: ZT.getDeviceId,
getIpV4Address: ZT.getIpV4Address,
listen: ZT.listen,
running: ZT.running,
simpleStart: ZT.simpleStart,
socket: ZT.socket
}

View File

@@ -1,35 +0,0 @@
{
"name": "node-libzt",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"autogypi": "autogypi",
"node-gyp": "node-gyp",
"format": "prettier-standard '*.js'",
"preinstall": "mkdir -p libzt; cd libzt; ln -sf ../../../include include; ln -sf ../../../zto zto; ln -sf ../../../build build",
"postinstall": "npm run -- node-gyp rebuild"
},
"lint-staged": {
"linters": {
"src/**/*.js": [
"prettier-standard",
"git add"
]
}
},
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": {
"husky": "^0.14.3",
"lint-staged": "^4.0.3",
"node-gyp": "^3.6.2",
"prettier-standard": "^6.0.0"
},
"dependencies": {
"autogypi": "^0.2.2",
"nbind": "^0.3.13"
}
}

View File

@@ -1,41 +0,0 @@
var fs = require('fs')
var zt = require('./libzt')
var running = zt.running()
console.log('running', running)
var earth = '8056c2e21c000001'
var listenPort = 1234
zt.simpleStart('./tmp/' + earth, earth)
var deviceId = zt.getDeviceId()
console.log('device id', deviceId)
var addr = zt.getIpV4Address(earth).split('/')[0]
console.log('ip a', addr)
var socket = zt.socket()
console.log('socket', socket)
var bindPort = zt.bindPort(socket, addr, listenPort)
console.log('bind', bindPort)
var listen = zt.listen(socket)
console.log('listen', listen)
console.log()
console.log('ready')
console.log(`run this in another terminal:\n\tnc ${addr} ${listenPort}`)
console.log(`then type something`)
console.log()
var fd = zt.accept(socket)
fd = fs.createReadStream(null, { fd: fd })
fd.pipe(process.stdout)
// Start reading from stdin so we don't exit.
process.stdin.resume()
// lib.ZT.stop()

View File

@@ -1,294 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 48;
objects = {
/* Begin PBXBuildFile section */
7CF6CAD01F997537002A1137 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 7CF6CACF1F997537002A1137 /* main.m */; };
7CF6CAD81F997575002A1137 /* libzt.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7CF6CAD71F997575002A1137 /* libzt.a */; };
7CF6CADB1F99762B002A1137 /* libztWrapper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7CF6CAD91F99762B002A1137 /* libztWrapper.cpp */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
7CF6CACA1F997537002A1137 /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
7CF6CACC1F997537002A1137 /* libztExampleApp */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = libztExampleApp; sourceTree = BUILT_PRODUCTS_DIR; };
7CF6CACF1F997537002A1137 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
7CF6CAD71F997575002A1137 /* libzt.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libzt.a; path = ../../../../build/darwin/libzt.a; sourceTree = "<group>"; };
7CF6CAD91F99762B002A1137 /* libztWrapper.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = libztWrapper.cpp; sourceTree = "<group>"; };
7CF6CADA1F99762B002A1137 /* libztWrapper.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = libztWrapper.hpp; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
7CF6CAC91F997537002A1137 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
7CF6CAD81F997575002A1137 /* libzt.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
7CF6CAC31F997537002A1137 = {
isa = PBXGroup;
children = (
7CF6CAD91F99762B002A1137 /* libztWrapper.cpp */,
7CF6CADA1F99762B002A1137 /* libztWrapper.hpp */,
7CF6CACE1F997537002A1137 /* libztExampleApp */,
7CF6CACD1F997537002A1137 /* Products */,
7CF6CAD61F997574002A1137 /* Frameworks */,
);
sourceTree = "<group>";
};
7CF6CACD1F997537002A1137 /* Products */ = {
isa = PBXGroup;
children = (
7CF6CACC1F997537002A1137 /* libztExampleApp */,
);
name = Products;
sourceTree = "<group>";
};
7CF6CACE1F997537002A1137 /* libztExampleApp */ = {
isa = PBXGroup;
children = (
7CF6CACF1F997537002A1137 /* main.m */,
);
path = libztExampleApp;
sourceTree = "<group>";
};
7CF6CAD61F997574002A1137 /* Frameworks */ = {
isa = PBXGroup;
children = (
7CF6CAD71F997575002A1137 /* libzt.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
7CF6CACB1F997537002A1137 /* libztExampleApp */ = {
isa = PBXNativeTarget;
buildConfigurationList = 7CF6CAD31F997537002A1137 /* Build configuration list for PBXNativeTarget "libztExampleApp" */;
buildPhases = (
7CF6CAC81F997537002A1137 /* Sources */,
7CF6CAC91F997537002A1137 /* Frameworks */,
7CF6CACA1F997537002A1137 /* CopyFiles */,
);
buildRules = (
);
dependencies = (
);
name = libztExampleApp;
productName = libztExampleApp;
productReference = 7CF6CACC1F997537002A1137 /* libztExampleApp */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
7CF6CAC41F997537002A1137 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0900;
ORGANIZATIONNAME = "ZeroTier, Inc.";
TargetAttributes = {
7CF6CACB1F997537002A1137 = {
CreatedOnToolsVersion = 9.0;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = 7CF6CAC71F997537002A1137 /* Build configuration list for PBXProject "libztExampleApp" */;
compatibilityVersion = "Xcode 8.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = 7CF6CAC31F997537002A1137;
productRefGroup = 7CF6CACD1F997537002A1137 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
7CF6CACB1F997537002A1137 /* libztExampleApp */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
7CF6CAC81F997537002A1137 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
7CF6CAD01F997537002A1137 /* main.m in Sources */,
7CF6CADB1F99762B002A1137 /* libztWrapper.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
7CF6CAD11F997537002A1137 /* 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_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = 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_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 = "-";
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;
MACOSX_DEPLOYMENT_TARGET = 10.12;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
};
name = Debug;
};
7CF6CAD21F997537002A1137 /* 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_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = 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_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 = "-";
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;
MACOSX_DEPLOYMENT_TARGET = 10.12;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
};
name = Release;
};
7CF6CAD41F997537002A1137 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
LIBRARY_SEARCH_PATHS = ../../../../build/darwin;
PRODUCT_NAME = "$(TARGET_NAME)";
USER_HEADER_SEARCH_PATHS = ../../../../include;
};
name = Debug;
};
7CF6CAD51F997537002A1137 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
LIBRARY_SEARCH_PATHS = ../../../../build/darwin;
PRODUCT_NAME = "$(TARGET_NAME)";
USER_HEADER_SEARCH_PATHS = ../../../../include;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
7CF6CAC71F997537002A1137 /* Build configuration list for PBXProject "libztExampleApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7CF6CAD11F997537002A1137 /* Debug */,
7CF6CAD21F997537002A1137 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
7CF6CAD31F997537002A1137 /* Build configuration list for PBXNativeTarget "libztExampleApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7CF6CAD41F997537002A1137 /* Debug */,
7CF6CAD51F997537002A1137 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 7CF6CAC41F997537002A1137 /* Project object */;
}

View File

@@ -1,19 +0,0 @@
//
// main.m
// libztExampleApp
//
// Created by Joseph Henry on 10/19/17.
// Copyright © 2017 ZeroTier, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
zts_startjoin("libzt_config_path", "XXXXXXXXXXXXXXXX");
zts_socket(2, 1, 0);
}
return 0;
}

View File

@@ -1,9 +0,0 @@
//
// libztWrapper.cpp
// libztExampleApp
//
// Created by Joseph Henry on 10/19/17.
// Copyright © 2017 ZeroTier, Inc. All rights reserved.
//
#include "libztWrapper.hpp"

View File

@@ -1,14 +0,0 @@
//
// libztWrapper.hpp
// libztExampleApp
//
// Created by Joseph Henry on 10/19/17.
// Copyright © 2017 ZeroTier, Inc. All rights reserved.
//
#ifndef libztWrapper_hpp
#define libztWrapper_hpp
#include <stdio.h>
#endif /* libztWrapper_hpp */

View File

@@ -1,6 +0,0 @@
## Processing
***
See the [Java](../java) eample.
*NOTE: Currently Processing requires that any JAR file contain only code compiled against JDK 1.6*

View File

@@ -1,4 +0,0 @@
libzt wrapper and PyPI package
***
See [libzt/packages/pypi](../../../packages/pypi)

View File

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

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>libztExampleApp.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
</dict>
</plist>

15
examples/cpp/dummy.cpp Normal file
View File

@@ -0,0 +1,15 @@
#include <stdio.h>
#include <unistd.h>
#include "libzt.h"
int main()
{
printf("Starting ZT service");
zts_startjoin("my_config_path",0x0000000000000000);
printf("Dummy. Going into infinite loop. Ping me or something\n");
while(1) {
sleep(1);
}
}

View File

@@ -0,0 +1,109 @@
/*
* 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.
*/
#include <stdio.h>
#include <string.h>
#include <string>
#include <inttypes.h>
#include <unistd.h>
#if defined(_WIN32)
#include <WinSock2.h>
#include <stdint.h>
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#include "libzt.h"
char *msg = (char*)"welcome to the machine";
int main(int argc, char **argv)
{
if (argc != 5) {
printf("\nlibzt example client\n");
printf("client [config_file_path] [nwid] [remote_addr] [remote_port]\n");
exit(0);
}
std::string path = argv[1];
std::string nwidstr = argv[2];
std::string remote_addr = argv[3];
int remote_port = atoi(argv[4]);
int r=0, w=0, err=0, sockfd;
char rbuf[32];
memset(rbuf, 0, sizeof rbuf);
struct sockaddr_in in4;
in4.sin_port = htons(remote_port);
in4.sin_addr.s_addr = INADDR_ANY;
in4.sin_family = AF_INET;
struct sockaddr_in remote4;
remote4.sin_port = htons(remote_port);
remote4.sin_addr.s_addr = inet_addr(remote_addr.c_str());
remote4.sin_family = AF_INET;
// --- BEGIN EXAMPLE CODE
DEBUG_TEST("Waiting for libzt to come online...\n");
uint64_t nwid = strtoull(nwidstr.c_str(),NULL,16);
printf("nwid=%llx\n", (unsigned long long)nwid);
zts_startjoin(path.c_str(), nwid);
uint64_t nodeId = zts_get_node_id();
DEBUG_TEST("I am %llx", (unsigned long long)nodeId);
if ((sockfd = zts_socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
DEBUG_ERROR("error creating ZeroTier socket");
}
if ((err = zts_bind(sockfd, (struct sockaddr *)&in4, sizeof(struct sockaddr_in)) < 0)) {
DEBUG_ERROR("error binding to interface (%d)", err);
}
int flags = 0;
int len = strlen(msg);
while(true) {
sleep(1);
if ((err = zts_sendto(sockfd, msg, len, flags, (const struct sockaddr *)&remote4, sizeof(remote4))) < 0) {
DEBUG_ERROR("error sending message to remote host (%d)", err);
}
DEBUG_TEST("sent=%d", err);
}
/*
DEBUG_TEST("reading from server...");
r = zts_read(sockfd, rbuf, strlen(msg));
DEBUG_TEST("Sent : %s", msg);
DEBUG_TEST("Received : %s", rbuf);
*/
err = zts_close(sockfd);
return err;
}

View File

@@ -0,0 +1,107 @@
/*
* 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.
*/
#include <stdio.h>
#include <string.h>
#include <string>
#include <inttypes.h>
#if defined(_WIN32)
#include <WinSock2.h>
#include <stdint.h>
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#include "libzt.h"
int main(int argc, char **argv)
{
if (argc != 4) {
printf("\nlibzt example server\n");
printf("server [config_file_path] [nwid] [bind_port]\n");
exit(0);
}
std::string path = argv[1];
std::string nwidstr = argv[2];
int bind_port = atoi(argv[3]);
int w=0, r=0, err=0, sockfd, accfd, flags = 0;
char rbuf[32];
memset(rbuf, 0, sizeof rbuf);
struct sockaddr_in in4, acc_in4;
in4.sin_port = htons(bind_port);
in4.sin_addr.s_addr = INADDR_ANY;
in4.sin_family = AF_INET;
// --- BEGIN EXAMPLE CODE
DEBUG_TEST("Waiting for libzt to come online...\n");
uint64_t nwid = strtoull(nwidstr.c_str(),NULL,16);
printf("nwid=%llx\n", (unsigned long long)nwid);
zts_startjoin(path.c_str(), nwid);
uint64_t nodeId = zts_get_node_id();
DEBUG_TEST("I am %llx", (unsigned long long)nodeId);
if ((sockfd = zts_socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
DEBUG_ERROR("error creating ZeroTier socket");
}
if ((err = zts_bind(sockfd, (struct sockaddr *)&in4, sizeof(struct sockaddr_in)) < 0)) {
DEBUG_ERROR("error binding to interface (%d)", err);
}
/*
socklen_t peer_addrlen = sizeof(struct sockaddr_storage);
zts_getpeername(accfd, (struct sockaddr*)&acc_in4, &peer_addrlen);
DEBUG_INFO("accepted connection from %s : %d", inet_ntoa(acc_in4.sin_addr), ntohs(acc_in4.sin_port));
*/
DEBUG_TEST("reading from client...");
socklen_t addrlen = sizeof(acc_in4);
memset(&acc_in4, 0, sizeof acc_in4);
while(true) {
memset(&rbuf, 0, sizeof rbuf);
r = zts_recvfrom(accfd, rbuf, sizeof(rbuf), flags, (struct sockaddr *)&acc_in4, &addrlen);
if (r >= 0) {
char *ip = inet_ntoa(acc_in4.sin_addr);
DEBUG_TEST("Received : r=%d, %s -- from: %s : %d", r, rbuf, ip, ntohs(acc_in4.sin_port));
}
}
/*
DEBUG_TEST("sending to client...");
w = zts_write(accfd, rbuf, strlen(rbuf));
*/
err = zts_close(sockfd);
return err;
}

View File

@@ -0,0 +1,246 @@
/*
* 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 zerotier.*;
import java.net.*;
import java.lang.Thread;
public class ExampleApp {
public native int loadsymbols();
public native void startOneService();
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 libzt = 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 = 0xf0b9acf0833f4b071L;
// 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
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) {
libzt.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) {
libzt.start(path, true);
while(!libzt.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");
libzt.join(nwid);
// Wait for userspace stack to start, we trigger this by joining a network
while(!libzt.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=" + libzt.get_path());
System.out.println("nodeId=" + Long.toHexString(libzt.get_node_id()));
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());
}
// Idle loop test
while(idle) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } }
// TCP
if (tcp) {
System.out.println("mode:tcp");
if ((fd = libzt.socket(libzt.AF_INET, libzt.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 = libzt.connect(fd, remoteAddr)) < 0) {
System.out.println("error connecting (err=" + err + ")");
return;
}
String echo_msg = "echo!";
w = libzt.write(fd, echo_msg.getBytes(), echo_msg.length());
rxBuffer = new byte[100];
lengthToRead = 100;
System.out.println("reading bytes...");
r = libzt.read(fd, rxBuffer, lengthToRead);
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 = libzt.bind(fd, localAddr)) < 0) {
System.out.println("error binding socket to virtual interface");
return;
} if ((err = libzt.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 = libzt.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 = libzt.read(client_fd, rxBuffer, lengthToRead);
System.out.println("r="+r);
System.out.println("string="+new String(rxBuffer));
System.out.println("writing bytes...");
String echo_msg = "echo!";
w = libzt.write(client_fd, echo_msg.getBytes(), echo_msg.length());
System.out.println("wrote (" + w + ") bytes");
}
}
// UDP
if (!tcp) {
System.out.println("mode:udp");
if ((fd = libzt.socket(libzt.AF_INET, libzt.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 = libzt.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 = libzt.sendto(fd, txBuffer, txBuffer.length, flags, remoteAddr)) < 0) {
System.out.println("error sending bytes");
} else {
System.out.println("sendto()=" + w);
}
}
} else {
if ((w = libzt.sendto(fd, txBuffer, txBuffer.length, 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 = libzt.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);
while(true) {
addr = new ZTSocketAddress();
r = libzt.recvfrom(fd, rxBuffer, rxBuffer.length, flags, remoteAddr);
System.out.println("read (" + r + ") bytes from " + remoteAddr.toString() + ", buffer = " + new String(rxBuffer));
}
}
}
libzt.close(client_fd);
libzt.close(fd);
}
}).start();
while(true)
{
try { Thread.sleep(3000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
}

View File

@@ -15,7 +15,7 @@ example_java_app_1.6:
javac -source 1.6 -bootclasspath /usr/lib/jvm/java-1.6.0-openjdk-1.6.0.41.x86_64/jre/lib/rt.jar -target 1.6 *.java
copy_dynamic_lib:
cp ../../../bin/lib/$(SHARED_LIB) .
cp ../../bin/lib/$(SHARED_LIB) .
jar:
jar cf libzt.jar libzt.dylib zerotier/ZeroTier.class

BIN
examples/java/libzt.jar Normal file

Binary file not shown.

View File

@@ -1,6 +1,6 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
* 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
@@ -24,33 +24,9 @@
* of your own application.
*/
#include "libzt.h"
package zerotier;
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <stdio.h>
#include <dlfcn.h>
int (*realsocket)(ZT_SOCKET_SIG) = 0;
extern void load_symbols()
public class fd_set
{
DEBUG_INFO();
realsocket = (int(*)(ZT_SOCKET_SIG))dlsym(RTLD_NEXT, "socket");
}
int socket(ZT_SOCKET_SIG)
{
DEBUG_INFO();
return zts_socket(socket_family, socket_type, protocol);
}
int main()
{
return 0;
byte[] fds_bits[1024 / 8];
}

View File

@@ -0,0 +1,93 @@
/*
* 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 zerotier;
import java.net.*;
// 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 long _ipdata;
public long _ipdata_ext;
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.ZeroTier.AF_INET6;
try {
InetAddress ip = InetAddress.getByName(ipStr);
_ip6 = ip.getAddress();
}
catch (Exception e) { }
}
else if(ipStr.contains(".")) {
_family = zerotier.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.ZeroTier.AF_INET) {
try {
InetAddress inet = InetAddress.getByAddress(_ip4);
return "" + inet.getHostAddress();
} catch (Exception e) {
System.out.println(e);
}
}
if (_family == zerotier.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,6 +1,6 @@
/*
* ZeroTier SDK - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
* 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
@@ -29,22 +29,19 @@ package zerotier;
import java.net.*;
public class ZeroTier {
// socket families
public static int AF_INET = 2;
public static int AF_INET6 = 30;
// socket types
public static int SOCK_STREAM = 1;
public static int SOCK_DGRAM = 2;
// fcntl flags
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;
// fcntl cmds
public static int F_GETFL = 3;
public static int F_SETFL = 4;
// service controls
public native void start(String homePath, boolean blocking);
public native void startjoin(String homePath, long nwid);
public native void stop();
@@ -56,37 +53,29 @@ public class ZeroTier {
public native String get_path();
public native long get_node_id();
public native int get_num_assigned_addresses(long nwid);
public native InetAddress get_address_at_index(long nwid, int index);
public native boolean get_address_at_index(long nwid, int index, ZTSocketAddress addr);
public native boolean has_address(long nwid);
public native InetAddress get_address(long nwid, int address_family);
public native boolean get_address(long nwid, int address_family, ZTSocketAddress addr);
public native void get_6plane_addr();
public native void get_rfc4193_addr();
// socket API
public native int socket(int family, int type, int protocol);
public native int connect(int fd, InetSocketAddress addr);
public native int bind(int fd, InetSocketAddress addr);
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, InetSocketAddress addr);
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();
//public native int getsockopt();
public native int sendto(int fd, byte[] buf, int len, int flags, InetSocketAddress addr);
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 len, int flags, ZTSocketAddress addr);
public native int send(int fd, byte[] buf, int len, int flags);
public native int recvfrom(int fd, byte[] buf, int len, int flags, InetSocketAddress addr);
public native int recv(int fd, byte[] buf, int len, int flags);
public native int recvfrom(int fd, byte[] buf, int len, int flags, ZTSocketAddress addr);
public native int read(int fd, byte[] buf, int len);
public native int write(int fd, byte[] buf, int len);
public native int shutdown(int fd, int how);
//public native int getsockname();
//public native int getpeername();
//public native int gethostname();
///public native int sethostname();
//public native int gethostbyname();
//public native int poll();
//public native int select();
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 ioctl(int fd, long request, ? );
// stack controls
public native int add_dns();
public native int del_dns();
}

194
examples/layer2/layer2.cpp Normal file
View File

@@ -0,0 +1,194 @@
// 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;
}