diff options
Diffstat (limited to 'java/src')
26 files changed, 2191 insertions, 0 deletions
| diff --git a/java/src/com/zerotier/one/AndroidFileProvider.java b/java/src/com/zerotier/one/AndroidFileProvider.java new file mode 100644 index 00000000..9979001a --- /dev/null +++ b/java/src/com/zerotier/one/AndroidFileProvider.java @@ -0,0 +1,40 @@ +package com.zerotier.one; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; + +import android.content.Context; + +public class AndroidFileProvider implements DataStoreFileProvider { +	Context _ctx; +		 +	AndroidFileProvider(Context ctx) { +		this._ctx = ctx; +	} + +	@Override +	public FileInputStream getInputFileStream(String name) +			throws FileNotFoundException { +		// TODO Auto-generated method stub +		return _ctx.openFileInput(name); +	} + +	@Override +	public FileOutputStream getOutputFileStream(String name) +			throws FileNotFoundException { +		// TODO Auto-generated method stub +		return _ctx.openFileOutput(name, Context.MODE_PRIVATE); +	} + +	@Override +	public void deleteFile(String name) throws IOException { +		boolean success = _ctx.deleteFile(name); +		if(!success) +		{ +			throw new IOException("Unable to delete file."); +		} +	} + +} diff --git a/java/src/com/zerotier/one/DataStore.java b/java/src/com/zerotier/one/DataStore.java new file mode 100644 index 00000000..1604e93e --- /dev/null +++ b/java/src/com/zerotier/one/DataStore.java @@ -0,0 +1,73 @@ +package com.zerotier.one; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; + +import com.zerotier.sdk.DataStoreGetListener; +import com.zerotier.sdk.DataStorePutListener; + +public class DataStore implements DataStoreGetListener, DataStorePutListener { + +	private DataStoreFileProvider _provider; + +	DataStore(DataStoreFileProvider provider) { +		this._provider = provider; +	} +	 +	@Override +	public int onDataStorePut(String name, byte[] buffer, boolean secure) { +		System.out.println("Writing File: " + name); +		try { +			FileOutputStream fos = _provider.getOutputFileStream(name); +            fos.write(buffer); +            fos.close(); +            return buffer.length; +		} catch (FileNotFoundException fnf) { +			fnf.printStackTrace(); +			return -1; +		} catch (IOException io) { +			io.printStackTrace(); +			return -2; +		} +	} + +	@Override +	public int onDelete(String name) { +		System.out.println("Deleting File: " + name); +		try { +			_provider.deleteFile(name); +			return 0; +		} catch (IOException ex) { +			ex.printStackTrace(); +			return -1; +		} +	} + +	@Override +	public long onDataStoreGet(String name, byte[] out_buffer, +			long bufferIndex, long[] out_objectSize) { +		System.out.println("Reading File: " + name); +		try { +            FileInputStream fin = _provider.getInputFileStream(name); +			out_objectSize[0] = fin.getChannel().size(); +            if(bufferIndex > 0) +            { +                fin.skip(bufferIndex); +            } +            int read = fin.read(out_buffer); +            fin.close(); +            return read; +		} catch (FileNotFoundException fnf) { +			// Can't read a file that doesn't exist! +			out_objectSize[0] = 0; +			return 0; +		} catch (IOException io) { +			io.printStackTrace(); +			return -2; +		} +	} +	 + +} diff --git a/java/src/com/zerotier/one/DataStoreFileProvider.java b/java/src/com/zerotier/one/DataStoreFileProvider.java new file mode 100644 index 00000000..ffe078eb --- /dev/null +++ b/java/src/com/zerotier/one/DataStoreFileProvider.java @@ -0,0 +1,12 @@ +package com.zerotier.one; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; + +public interface DataStoreFileProvider { +	FileInputStream getInputFileStream(String name) throws FileNotFoundException; +	FileOutputStream getOutputFileStream(String name) throws FileNotFoundException; +	void deleteFile(String name) throws IOException; +} diff --git a/java/src/com/zerotier/one/JavaFileProvider.java b/java/src/com/zerotier/one/JavaFileProvider.java new file mode 100644 index 00000000..41889e2f --- /dev/null +++ b/java/src/com/zerotier/one/JavaFileProvider.java @@ -0,0 +1,46 @@ +package com.zerotier.one; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; + +public class JavaFileProvider implements DataStoreFileProvider { +	private String _path; + +	public JavaFileProvider(String path) { +		this._path = path; +	} +	 +	@Override +	public FileInputStream getInputFileStream(String name) +			throws FileNotFoundException { +		File f = new File(_path + File.separator + name); +		return new FileInputStream(f); +	} + +	@Override +	public FileOutputStream getOutputFileStream(String name) +			throws FileNotFoundException { +		File f = new File(_path + File.separator + name); +		if(!f.exists()) +		{ +			try { +				f.createNewFile(); +			} catch (IOException e) { +				e.printStackTrace(); +			} +		} +		return new FileOutputStream(f); +	} + +	@Override +	public void deleteFile(String name) throws IOException { +		File f = new File(_path + File.separator + name); +		boolean success = f.delete(); +		if(!success) { +			throw new IOException("Unable to delete file: " + _path + File.pathSeparator + name); +		} +	} +} diff --git a/java/src/com/zerotier/one/OneService.java b/java/src/com/zerotier/one/OneService.java new file mode 100644 index 00000000..0477b54d --- /dev/null +++ b/java/src/com/zerotier/one/OneService.java @@ -0,0 +1,205 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + + +package com.zerotier.one; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.SocketException; +import java.net.SocketTimeoutException; + +import com.zerotier.sdk.Event; +import com.zerotier.sdk.EventListener; +import com.zerotier.sdk.Node; +import com.zerotier.sdk.PacketSender; +import com.zerotier.sdk.ResultCode; +import com.zerotier.sdk.Version; +import com.zerotier.sdk.VirtualNetworkConfig; +import com.zerotier.sdk.VirtualNetworkConfigListener; +import com.zerotier.sdk.VirtualNetworkConfigOperation; +import com.zerotier.sdk.VirtualNetworkFrameListener; + +public class OneService extends Thread implements Runnable, PacketSender, +								   EventListener, VirtualNetworkConfigListener,  +								   VirtualNetworkFrameListener { +	private Node _node; +	private int _port; + +	private DatagramSocket _udpSocket; +	private ServerSocket _tcpSocket; +	private DataStore _ds; +	private long _nextBackgroundTaskDeadline = 0; +	 +	private final Thread _udpReceiveThread = new Thread() { +		@Override +		public void run() { +			try { +				long[] bgtask = new long[1]; +				byte[] buffer = new byte[16384]; +				while(true) { +	    			 +	    			bgtask[0] = 0; +	    			DatagramPacket p = new DatagramPacket(buffer, buffer.length); +	    			 +	    			try { +	    				_udpSocket.receive(p); +	    				if(p.getLength() > 0) +		    			{ +		    				System.out.println("Got Data From: " + p.getAddress().toString() +":" + p.getPort()); +		    				 +		    				_node.processWirePacket(System.currentTimeMillis(), new InetSocketAddress(p.getAddress(), p.getPort()), 0, p.getData(), bgtask); +		    				_nextBackgroundTaskDeadline = bgtask[0]; +		    			} +	    			} catch (SocketTimeoutException e) {} +				} +			} catch (Exception e) { +				e.printStackTrace(); +			} +		} +	}; +	 +	 +	public OneService(DataStoreFileProvider prov, int port) { +		this._port = port; +		this._ds = new DataStore(prov); +		 +		try { +			_udpSocket = new DatagramSocket(_port); +			_udpSocket.setSoTimeout(100); +			_tcpSocket = new ServerSocket(); +			_tcpSocket.bind(new InetSocketAddress("127.0.0.1", _port)); +		} catch (SocketException e) { +			e.printStackTrace(); +			return; +		} catch (IOException e) { +			e.printStackTrace(); +			return; +		} +		 +		_udpReceiveThread.start(); +		 +		_node = new Node( +				System.currentTimeMillis(), +				_ds, +				_ds, +				this, +				this, +				this, +				this); +	} + +	@Override +	public void run() { +		if(_node == null) +			return; +		 +		while(true) { +		    try { +		 +		        long dl = _nextBackgroundTaskDeadline; +		        long now = System.currentTimeMillis(); +		 +		        if (dl <= now) { +		            long[] returnDeadline = {0}; +		            ResultCode rc = _node.processBackgroundTasks(now, returnDeadline); +		            _nextBackgroundTaskDeadline = returnDeadline[0]; +		             +		            if(rc != ResultCode.RESULT_OK) { +		            	System.out.println(rc.toString()); +		            } +		        } +		         +		        long delay = (dl > now) ? (dl - now) : 100; +		        Thread.sleep(delay); +		 +		    } catch (Exception ex) { +		    	System.out.println("Exception in run loop: " + ex.getMessage()); +		    	ex.printStackTrace(); +		    } +        } +	} + +	@Override +	public int onSendPacketRequested(InetSocketAddress addr, +			int linkDesperation, byte[] packetData) { +		System.out.println("onSendPacketRequested to: " + addr.getHostString() +":"+ addr.getPort() + " "); + +    	if(_udpSocket == null) +    		return -1; +    	try { +    		DatagramPacket p = new DatagramPacket(packetData, packetData.length, addr); +    		_udpSocket.send(p); +    		System.out.println("Sent"); +    	} catch (Exception e) { +    		System.out.println("Error sending datagram: " + e.getMessage()); +    		return -1; +    	} +        return 0; +	} + +	@Override +	public void onVirtualNetworkFrame(long nwid, long srcMac, long destMac, +			long etherType, long vlanId, byte[] frameData) { +		// TODO Auto-generated method stub +		 +	} + +	@Override +	public int onNetworkConfigurationUpdated(long nwid, +			VirtualNetworkConfigOperation op, VirtualNetworkConfig config) { +		// TODO Auto-generated method stub +		return 0; +	} + +	@Override +	public void onEvent(Event event) { +		// TODO Auto-generated method stub +		 +	} + +	@Override +	public void onNetworkError(Event event, InetSocketAddress source) { +		// TODO Auto-generated method stub +		 +	} + +	@Override +	public void onOutOfDate(Version newVersion) { +		// TODO Auto-generated method stub +		 +	} + +	@Override +	public void onTrace(String message) { +		// TODO Auto-generated method stub +		 +	} +} diff --git a/java/src/com/zerotier/sdk/DataStoreGetListener.java b/java/src/com/zerotier/sdk/DataStoreGetListener.java new file mode 100644 index 00000000..b525be63 --- /dev/null +++ b/java/src/com/zerotier/sdk/DataStoreGetListener.java @@ -0,0 +1,58 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ +package com.zerotier.sdk; + +public interface DataStoreGetListener { + +    /** +     * Function to get an object from the data store +     * +     * <p>Object names can contain forward slash (/) path separators. They will +     * never contain .. or backslash (\), so this is safe to map as a Unix-style +     * path if the underlying storage permits. For security reasons we recommend +     * returning errors if .. or \ are used.</p> +     * +     * <p>The function must return the actual number of bytes read. If the object +     * doesn't exist, it should return -1. -2 should be returned on other errors +     * such as errors accessing underlying storage.</p> +     * +     * <p>If the read doesn't fit in the buffer, the max number of bytes should be +     * read. The caller may call the function multiple times to read the whole +     * object.</p> +     * +     * @param name Name of the object in the data store +     * @param out_buffer buffer to put the object in +     * @param bufferIndex index in the object to start reading +     * @param out_objectSize long[1] to be set to the actual size of the object if it exists. +     * @return the actual number of bytes read. +     */ +    public long onDataStoreGet( +            String name, +            byte[] out_buffer, +            long bufferIndex, +            long[] out_objectSize); +} diff --git a/java/src/com/zerotier/sdk/DataStorePutListener.java b/java/src/com/zerotier/sdk/DataStorePutListener.java new file mode 100644 index 00000000..77e55027 --- /dev/null +++ b/java/src/com/zerotier/sdk/DataStorePutListener.java @@ -0,0 +1,59 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ +package com.zerotier.sdk; + +public interface DataStorePutListener { + +    /** +     * Function to store an object in the data store +     * +     * <p>If secure is true, the file should be set readable and writable only +     * to the user running ZeroTier One. What this means is platform-specific.</p> +     * +     * <p>Name semantics are the same as {@link DataStoreGetListener}. This must return  +     * zero on success. You can return any OS-specific error code on failure, as these +     * may be visible in logs or error messages and might aid in debugging.</p> +     * +     * @param name Object name +     * @param buffer data to store +     * @param secure set to user read/write only. +     * @return 0 on success. +     */ +    public int onDataStorePut( +        String name, +        byte[] buffer, +        boolean secure); + +    /** +     * Function to delete an object from the data store +     *  +     * @param name Object name +     * @return 0 on success. +     */ +    public int onDelete( +        String name); +} diff --git a/java/src/com/zerotier/sdk/Event.java b/java/src/com/zerotier/sdk/Event.java new file mode 100644 index 00000000..d315990b --- /dev/null +++ b/java/src/com/zerotier/sdk/Event.java @@ -0,0 +1,123 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +public enum Event { +    /** +     * Node has been initialized +     * +     * This is the first event generated, and is always sent. It may occur +     * before Node's constructor returns. +     */ +	EVENT_UP, + +    /** +     * Node is offline -- network does not seem to be reachable by any available strategy +     */ +	EVENT_OFFLINE, + +    /** +     * Node is online -- at least one upstream node appears reachable +     * +     * Meta-data: none +     */ +    EVENT_ONLINE, + +    /** +     * Node is shutting down +     *  +     * <p>This is generated within Node's destructor when it is being shut down. +     * It's done for convenience, since cleaning up other state in the event +     * handler may appear more idiomatic.</p> +     */ +	EVENT_DOWN, + +    /** +     * Your identity has collided with another node's ZeroTier address +     *  +     * <p>This happens if two different public keys both hash (via the algorithm +     * in Identity::generate()) to the same 40-bit ZeroTier address.</p> +     *  +     * <p>This is something you should "never" see, where "never" is defined as +     * once per 2^39 new node initializations / identity creations. If you do +     * see it, you're going to see it very soon after a node is first +     * initialized.</p> +     *  +     * <p>This is reported as an event rather than a return code since it's +     * detected asynchronously via error messages from authoritative nodes.</p> +     *  +     * <p>If this occurs, you must shut down and delete the node, delete the +     * identity.secret record/file from the data store, and restart to generate +     * a new identity. If you don't do this, you will not be able to communicate +     * with other nodes.</p> +     *  +     * <p>We'd automate this process, but we don't think silently deleting +     * private keys or changing our address without telling the calling code +     * is good form. It violates the principle of least surprise.</p> +     *  +     * <p>You can technically get away with not handling this, but we recommend +     * doing so in a mature reliable application. Besides, handling this +     * condition is a good way to make sure it never arises. It's like how +     * umbrellas prevent rain and smoke detectors prevent fires. They do, right?</p> +     */ +	EVENT_FATAL_ERROR_IDENTITY_COLLISION, +     +    /** +     * A more recent version was observed on the network +     *  +     * <p>Right now this is only triggered if a hub or supernode reports a +     * more recent version, and only once. It can be used to trigger a +     * software update check.</p> +     *  +     * <p>Meta-data: {@link Version}, more recent version number</p> +     */ +    EVENT_SAW_MORE_RECENT_VERSION, + +    /** +     * A packet failed authentication +     * +     * <p>Meta-data: {@link InetSocketAddress} containing origin address of packet</p> +     */ +	EVENT_AUTHENTICATION_FAILURE, + +    /** +     * A received packet was not valid +     * +     * <p>Meta-data: {@link InetSocketAddress} containing origin address of packet</p> +     */ +	EVENT_INVALID_PACKET, + +    /** +     * Trace (debugging) message +     * +     * <p>These events are only generated if this is a TRACE-enabled build.</p> +     * +     * <p>Meta-data: {@link String}, TRACE message</p> +     */ +	EVENT_TRACE +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/EventListener.java b/java/src/com/zerotier/sdk/EventListener.java new file mode 100644 index 00000000..078023d9 --- /dev/null +++ b/java/src/com/zerotier/sdk/EventListener.java @@ -0,0 +1,67 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +import java.net.InetSocketAddress; +import java.lang.String; + +/** + * Interface to handle callbacks for ZeroTier One events. + */ +public interface EventListener { +    /** +     * Callback for events with no other associated metadata +     *  +     * @param event {@link Event} enum +     */ +    public void onEvent(Event event); +     +    /** +     * Callback for network error events: {@link Event.EVENT_AUTHENTICATION_FAILUER}, {link Event.EVENT_INVALID_PACKET} +     * +     * @param event {@link Event} enum +     * @param source {@link InetSocketAddress} containing the origin address of the packet +     */ +    public void onNetworkError(Event event, InetSocketAddress source); + +    /** +     * Callback when the node detects that it's out of date. +     * +     * @param newVersion {@link Version} object with the latest version of ZeroTier One +     */ +    public void onOutOfDate(Version newVersion); + +    /** +     * Trace messages +     *  +     * <p>These events are only generated if the underlying ZeroTierOne SDK is a TRACE-enabled build.</p> +     * +     * @param message the trace message +     */ +    public void onTrace(String message); +} diff --git a/java/src/com/zerotier/sdk/MulticastGroup.java b/java/src/com/zerotier/sdk/MulticastGroup.java new file mode 100644 index 00000000..5c4df87a --- /dev/null +++ b/java/src/com/zerotier/sdk/MulticastGroup.java @@ -0,0 +1,49 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ +package com.zerotier.sdk; + + +public final class MulticastGroup { +    private MulticastGroup() {} + +    private long mac; +    private long adi; + +    /** +     * MAC address (least significant 48 bits) +     */ +    public final long getMacAddress() { +        return mac; +    } + +    /** +     * Additional distinguishing information (usually zero) +     */ +    public final long getAdi() { +        return adi; +    } +} diff --git a/java/src/com/zerotier/sdk/NativeUtils.java b/java/src/com/zerotier/sdk/NativeUtils.java new file mode 100644 index 00000000..07e1ef5b --- /dev/null +++ b/java/src/com/zerotier/sdk/NativeUtils.java @@ -0,0 +1,93 @@ +package com.zerotier.sdk; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +  +/** + * Simple library class for working with JNI (Java Native Interface) + *  + * @see http://adamheinrich.com/2012/how-to-load-native-jni-library-from-jar + * + * @author Adam Heirnich <adam@adamh.cz>, http://www.adamh.cz + */ +public class NativeUtils { +  +    /** +     * Private constructor - this class will never be instanced +     */ +    private NativeUtils() { +    } +  +    /** +     * Loads library from current JAR archive +     *  +     * The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after exiting. +     * Method uses String as filename because the pathname is "abstract", not system-dependent. +     *  +     * @param filename The filename inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext +     * @throws IOException If temporary file creation or read/write operation fails +     * @throws IllegalArgumentException If source file (param path) does not exist +     * @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters (restriction of {@see File#createTempFile(java.lang.String, java.lang.String)}). +     */ +    public static void loadLibraryFromJar(String path) throws IOException { +  +        if (!path.startsWith("/")) { +            throw new IllegalArgumentException("The path has to be absolute (start with '/')."); +        } +  +        // Obtain filename from path +        String[] parts = path.split("/"); +        String filename = (parts.length > 1) ? parts[parts.length - 1] : null; +  +        // Split filename to prexif and suffix (extension) +        String prefix = ""; +        String suffix = null; +        if (filename != null) { +            parts = filename.split("\\.", 2); +            prefix = parts[0]; +            suffix = (parts.length > 1) ? "."+parts[parts.length - 1] : null; // Thanks, davs! :-) +        } +  +        // Check if the filename is okay +        if (filename == null || prefix.length() < 3) { +            throw new IllegalArgumentException("The filename has to be at least 3 characters long."); +        } +  +        // Prepare temporary file +        File temp = File.createTempFile(prefix, suffix); +        temp.deleteOnExit(); +  +        if (!temp.exists()) { +            throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist."); +        } +  +        // Prepare buffer for data copying +        byte[] buffer = new byte[1024]; +        int readBytes; +  +        // Open and check input stream +        InputStream is = NativeUtils.class.getResourceAsStream(path); +        if (is == null) { +            throw new FileNotFoundException("File " + path + " was not found inside JAR."); +        } +  +        // Open output stream and copy data between source file in JAR and the temporary file +        OutputStream os = new FileOutputStream(temp); +        try { +            while ((readBytes = is.read(buffer)) != -1) { +                os.write(buffer, 0, readBytes); +            } +        } finally { +            // If read/write fails, close streams safely before throwing an exception +            os.close(); +            is.close(); +        } +  +        // Finally, load the library +        System.load(temp.getAbsolutePath()); +    } +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/Node.java b/java/src/com/zerotier/sdk/Node.java new file mode 100644 index 00000000..c7581ca4 --- /dev/null +++ b/java/src/com/zerotier/sdk/Node.java @@ -0,0 +1,435 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.io.IOException; + +/** + * A ZeroTier One node + */ +public class Node { +	static { +        try { +    		System.loadLibrary("ZeroTierOneJNI"); +        } catch (UnsatisfiedLinkError e) { +            try {  +                if(System.getProperty("os.name").startsWith("Windows")) { +                    System.out.println("Arch: " + System.getProperty("sun.arch.data.model")); +                    if(System.getProperty("sun.arch.data.model").equals("64")) { +                        NativeUtils.loadLibraryFromJar("/lib/ZeroTierOneJNI_win64.dll"); +                    } else { +                        NativeUtils.loadLibraryFromJar("/lib/ZeroTierOneJNI_win32.dll"); +                    } +                } else if(System.getProperty("os.name").startsWith("Mac")) { +                    NativeUtils.loadLibraryFromJar("/lib/libZeroTierOneJNI.jnilib"); +                } else { +                    // TODO: Linux +                } +            } catch (IOException ioe) { +                ioe.printStackTrace(); +            } +        } +	} + +    private static final String TAG = "NODE"; + +    /** +     * Node ID for JNI purposes. +     * Currently set to the now value passed in at the constructor +     *  +     * -1 if the node has already been closed +     */ +    private long nodeId; + +    private final DataStoreGetListener getListener; +    private final DataStorePutListener putListener; +    private final PacketSender sender; +    private final EventListener eventListener; +    private final VirtualNetworkFrameListener frameListener; +    private final VirtualNetworkConfigListener configListener; +     +    /** +     * Create a new ZeroTier One node +     * +     * <p>Note that this can take a few seconds the first time it's called, as it +     * will generate an identity.</p> +     * +     * @param now Current clock in milliseconds +     * @param getListener User written instance of the {@link DataStoreGetListener} interface called to get objects from persistent storage.  This instance must be unique per Node object. +     * @param putListener User written intstance of the {@link DataStorePutListener} interface called to put objects in persistent storage.  This instance must be unique per Node object. +     * @param sender +     * @param eventListener User written instance of the {@link EventListener} interface to receive status updates and non-fatal error notices.  This instance must be unique per Node object. +     * @param frameListener  +     * @param configListener User written instance of the {@link VirtualNetworkConfigListener} interface to be called when virtual LANs are created, deleted, or their config parameters change.  This instance must be unique per Node object. +     */ +	public Node(long now, +                DataStoreGetListener getListener, +                DataStorePutListener putListener, +                PacketSender sender, +                EventListener eventListener, +                VirtualNetworkFrameListener frameListener, +                VirtualNetworkConfigListener configListener) throws NodeException +	{ +        this.nodeId = now; + +        this.getListener = getListener; +        this.putListener = putListener; +        this.sender = sender; +        this.eventListener = eventListener; +        this.frameListener = frameListener; +        this.configListener = configListener; + +        ResultCode rc = node_init(now); +        if(rc != ResultCode.RESULT_OK) +        { +            // TODO: Throw Exception +            throw new NodeException(rc.toString()); +        } +	} + +    /** +      * Close this Node. +      *  +      * <p>The Node object can no longer be used once this method is called.</p> +      */ +    public void close() { +        if(nodeId != -1) { +            node_delete(nodeId); +            nodeId = -1; +        } +    } + +    @Override +    protected void finalize() { +        close(); +    } + +    /** +     * Process a frame from a virtual network port +     * +     * @param now Current clock in milliseconds +     * @param nwid ZeroTier 64-bit virtual network ID +     * @param sourceMac Source MAC address (least significant 48 bits) +     * @param destMac Destination MAC address (least significant 48 bits) +     * @param etherType 16-bit Ethernet frame type +     * @param vlanId 10-bit VLAN ID or 0 if none +     * @param frameData Frame payload data +     * @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks() +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +    public ResultCode processVirtualNetworkFrame( +        long now, +        long nwid, +        long sourceMac, +        long destMac, +        int etherType, +        int vlanId, +        byte[] frameData, +        long[] nextBackgroundTaskDeadline) { +        return processVirtualNetworkFrame( +            nodeId, now, nwid, sourceMac, destMac, etherType, vlanId,  +            frameData, nextBackgroundTaskDeadline); +    } + +    /** +     * Process a packet received from the physical wire +     * +     * @param now Current clock in milliseconds +     * @param remoteAddress Origin of packet +     * @param linkDesperation Link desperation metric for link or protocol over which packet arrived +     * @param packetData Packet data +     * @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks() +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +    public ResultCode processWirePacket( +        long now, +        InetSocketAddress remoteAddress, +        int linkDesperation, +        byte[] packetData, +        long[] nextBackgroundTaskDeadline) { +        return processWirePacket( +            nodeId, now, remoteAddress, linkDesperation, packetData,  +            nextBackgroundTaskDeadline); +    } + +    /** +     * Perform periodic background operations +     * +     * @param now Current clock in milliseconds +     * @param nextBackgroundTaskDeadline Value/result: set to deadline for next call to processBackgroundTasks() +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +    public ResultCode processBackgroundTasks(long now, long[] nextBackgroundTaskDeadline) { +        return processBackgroundTasks(nodeId, now, nextBackgroundTaskDeadline); +    } + +    /** +     * Join a network +     * +     * <p>This may generate calls to the port config callback before it returns, +     * or these may be deffered if a netconf is not available yet.</p> +     * +     * <p>If we are already a member of the network, nothing is done and OK is +     * returned.</p> +     * +     * @param nwid 64-bit ZeroTier network ID +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +    public ResultCode join(long nwid) { +        return join(nodeId, nwid); +    } + +    /** +     * Leave a network +     * +     * <p>If a port has been configured for this network this will generate a call +     * to the port config callback with a NULL second parameter to indicate that +     * the port is now deleted.</p> +     * +     * @param nwid 64-bit network ID +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +    public ResultCode leave(long nwid) { +        return leave(nodeId, nwid); +    } + +    /** +     * Subscribe to an Ethernet multicast group +     * +     * <p>For IPv4 ARP, the implementation must subscribe to 0xffffffffffff (the +     * broadcast address) but with an ADI equal to each IPv4 address in host +     * byte order. This converts ARP from a non-scalable broadcast protocol to +     * a scalable multicast protocol with perfect address specificity.</p> +     * +     * <p>If this is not done, ARP will not work reliably.</p> +     * +     * <p>Multiple calls to subscribe to the same multicast address will have no +     * effect. It is perfectly safe to do this.</p> +     * +     * <p>This does not generate an update call to the {@link VirtualNetworkConfigListener#onNetworkConfigurationUpdated} method.</p> +     * +     * @param nwid 64-bit network ID +     * @param multicastGroup Ethernet multicast or broadcast MAC (least significant 48 bits) +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +    public ResultCode multicastSubscribe( +		long nwid, +		long multicastGroup) { +		return multicastSubscribe(nodeId, nwid, multicastGroup, 0); +	} + +    /** +     * Subscribe to an Ethernet multicast group +     * +     * <p>ADI stands for additional distinguishing information. This defaults to zero +     * and is rarely used. Right now its only use is to enable IPv4 ARP to scale, +     * and this must be done.</p> +     * +     * <p>For IPv4 ARP, the implementation must subscribe to 0xffffffffffff (the +     * broadcast address) but with an ADI equal to each IPv4 address in host +     * byte order. This converts ARP from a non-scalable broadcast protocol to +     * a scalable multicast protocol with perfect address specificity.</p> +     * +     * <p>If this is not done, ARP will not work reliably.</p> +     * +     * <p>Multiple calls to subscribe to the same multicast address will have no +     * effect. It is perfectly safe to do this.</p> +     * +     * <p>This does not generate an update call to the {@link VirtualNetworkConfigListener#onNetworkConfigurationUpdated} method.</p> +     * +     * @param nwid 64-bit network ID +     * @param multicastGroup Ethernet multicast or broadcast MAC (least significant 48 bits) +     * @param multicastAdi Multicast ADI (least significant 32 bits only, default: 0) +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +    public ResultCode multicastSubscribe( +        long nwid, +        long multicastGroup, +        long multicastAdi) { +        return multicastSubscribe(nodeId, nwid, multicastGroup, multicastAdi); +    } + + +    /** +     * Unsubscribe from an Ethernet multicast group (or all groups) +     * +     * <p>If multicastGroup is zero (0), this will unsubscribe from all groups. If +     * you are not subscribed to a group this has no effect.</p> +     * +     * <p>This does not generate an update call to the {@link VirtualNetworkConfigListener#onNetworkConfigurationUpdated} method.</p> +     * +     * @param nwid 64-bit network ID +     * @param multicastGroup Ethernet multicast or broadcast MAC (least significant 48 bits) +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +	public ResultCode multicastUnsubscribe( +		long nwid, +		long multicastGroup) { +		return multicastUnsubscribe(nodeId, nwid, multicastGroup, 0); +	} + +    /** +     * Unsubscribe from an Ethernet multicast group (or all groups) +     * +     * <p>If multicastGroup is zero (0), this will unsubscribe from all groups. If +     * you are not subscribed to a group this has no effect.</p> +     * +     * <p>This does not generate an update call to the {@link VirtualNetworkConfigListener#onNetworkConfigurationUpdated} method.</p> +     * +     * <p>ADI stands for additional distinguishing information. This defaults to zero +     * and is rarely used. Right now its only use is to enable IPv4 ARP to scale, +     * and this must be done.</p> +     * +     * @param nwid 64-bit network ID +     * @param multicastGroup Ethernet multicast or broadcast MAC (least significant 48 bits) +     * @param multicastAdi Multicast ADI (least significant 32 bits only, default: 0) +     * @return OK (0) or error code if a fatal error condition has occurred +     */ +    public ResultCode multicastUnsubscribe( +        long nwid, +        long multicastGroup, +        long multicastAdi) { +        return multicastUnsubscribe(nodeId, nwid, multicastGroup, multicastAdi); +    } + +    /** +     * Get this node's 40-bit ZeroTier address +     * +     * @return ZeroTier address (least significant 40 bits of 64-bit int) +     */ +    public long address() { +        return address(nodeId); +    } + +    /** +     * Get the status of this node +     * +     * @return @{link NodeStatus} struct with the current node status. +     */ +    public NodeStatus status() { +        return status(nodeId); +    } + +    /** +     * Get a list of known peer nodes +     * +     * @return List of known peers or NULL on failure +     */ +    public ArrayList<Peer> peers() { +        return peers(nodeId); +    } + +    /** +     * Get the status of a virtual network +     * +     * @param nwid 64-bit network ID +     * @return {@link VirtualNetworkConfig} or NULL if we are not a member of this network +     */ +    public VirtualNetworkConfig networkConfig(long nwid) { +        return networkConfig(nodeId, nwid); +    } + +    /** +     * Enumerate and get status of all networks +     * +     * @return List of networks or NULL on failure +     */ +    public ArrayList<VirtualNetworkConfig> networks() { +        return networks(nodeId); +    } + +    /** +     * Get ZeroTier One version +     * +     * @return {@link Version} object with ZeroTierOne version information. +     */ +    public Version getVersion() { +        return version(); +    } + +    // +    // function declarations for JNI +    // +    private native ResultCode node_init(long now); + +    private native void node_delete(long nodeId); + +    private native ResultCode processVirtualNetworkFrame( +        long nodeId, +        long now, +        long nwid, +        long sourceMac, +        long destMac, +        int etherType, +        int vlanId, +        byte[] frameData, +        long[] nextBackgroundTaskDeadline); + +    private native ResultCode processWirePacket( +        long nodeId, +        long now, +        InetSocketAddress remoteAddress, +        int linkDesperation, +        byte[] packetData, +        long[] nextBackgroundTaskDeadline); + +    private native ResultCode processBackgroundTasks( +        long nodeId, +        long now, +        long[] nextBackgroundTaskDeadline); + +    private native ResultCode join(long nodeId, long nwid); + +    private native ResultCode leave(long nodeId, long nwid); + +    private native ResultCode multicastSubscribe( +        long nodeId, +        long nwid, +        long multicastGroup, +        long multicastAdi); + +    private native ResultCode multicastUnsubscribe( +        long nodeId, +        long nwid, +        long multicastGroup, +        long multicastAdi); + +    private native long address(long nodeId); + +    private native NodeStatus status(long nodeId); + +    private native VirtualNetworkConfig networkConfig(long nodeId, long nwid); + +    private native Version version(); + +    private native ArrayList<Peer> peers(long nodeId); + +    private native ArrayList<VirtualNetworkConfig> networks(long nodeId); +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/NodeException.java b/java/src/com/zerotier/sdk/NodeException.java new file mode 100644 index 00000000..3071069a --- /dev/null +++ b/java/src/com/zerotier/sdk/NodeException.java @@ -0,0 +1,36 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +import java.lang.RuntimeException; + +class NodeException extends RuntimeException { +    NodeException(String message) { +        super(message); +    } +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/NodeStatus.java b/java/src/com/zerotier/sdk/NodeStatus.java new file mode 100644 index 00000000..94376d85 --- /dev/null +++ b/java/src/com/zerotier/sdk/NodeStatus.java @@ -0,0 +1,69 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +public final class NodeStatus { +	private long address; +	private String publicIdentity; +	private String secretIdentity; +	private boolean online; + +	private NodeStatus() {} + +	/** +	 * 40-bit ZeroTier address of this node +	 */ +	public final long getAddres() { +		return address; +	} + +	/** +	 * Public identity in string-serialized form (safe to send to others) +	 * +	 * <p>This identity will remain valid as long as the node exists.</p> +	 */ +	public final String getPublicIdentity() { +		return publicIdentity; +	} + +	/** +	 * Full identity including secret key in string-serialized form +	 * +	 * <p>This identity will remain valid as long as the node exists.</p> +	 */ +	public final String getSecretIdentity() { +		return secretIdentity; +	} + +	/** +	 * True if some kind of connectivity appears available +	 */ +	public final boolean isOnline() { +		return online; +	} +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/PacketSender.java b/java/src/com/zerotier/sdk/PacketSender.java new file mode 100644 index 00000000..d038b11d --- /dev/null +++ b/java/src/com/zerotier/sdk/PacketSender.java @@ -0,0 +1,49 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ +package com.zerotier.sdk; + +import java.net.InetSocketAddress; + + +public interface PacketSender { +    /** +     * Function to send a ZeroTier packet out over the wire +     * +     * <p>The function must return zero on success and may return any error code +     * on failure. Note that success does not (of course) guarantee packet +     * delivery. It only means that the packet appears to have been sent.</p> +     * +     * @param addr {@link InetSocketAddress} to send to +     * @param linkDesperation +     * @param packetData data to send +     * @return 0 on success, any error code on failure. +     */ +    public int onSendPacketRequested( +            InetSocketAddress addr, +            int linkDesperation, +            byte[] packetData); +} diff --git a/java/src/com/zerotier/sdk/Peer.java b/java/src/com/zerotier/sdk/Peer.java new file mode 100644 index 00000000..407e6cd4 --- /dev/null +++ b/java/src/com/zerotier/sdk/Peer.java @@ -0,0 +1,110 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +import java.util.ArrayList; + +/** + * Peer status result + */ +public final class Peer { +    private long address; +    private long lastUnicastFrame; +    private long lastMulticastFrame; +    private int versionMajor; +    private int versionMinor; +    private int versionRev; +    private int latency; +    private PeerRole role; +    private ArrayList<PeerPhysicalPath> paths; + +    private Peer() {} + +    /** +     * ZeroTier address (40 bits) +     */ +    public final long address() { +        return address; +    } + +    /** +     * Time we last received a unicast frame from this peer +     */ +    public final long lastUnicastFrame() { +        return lastUnicastFrame; +    } + +    /** +     * Time we last received a multicast rame from this peer +     */ +    public final long lastMulticastFrame() { +        return lastMulticastFrame; +    } + +    /** +     * Remote major version or -1 if not known +     */ +    public final int versionMajor() { +        return versionMajor; +    } + +    /** +     * Remote minor version or -1 if not known +     */ +    public final int versionMinor() { +        return versionMinor; +    } + +    /** +     * Remote revision or -1 if not known +     */ +    public final int versionRev() { +        return versionRev; +    } + +    /** +     * Last measured latency in milliseconds or zero if unknown +     */ +    public final int latency() { +        return latency; +    } + +    /** +     * What trust hierarchy role does this device have? +     */ +    public final PeerRole role() { +        return role; +    } + +    /** +     * Known network paths to peer +     */ +    public final ArrayList<PeerPhysicalPath> paths() { +        return paths; +    } +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/PeerPhysicalPath.java b/java/src/com/zerotier/sdk/PeerPhysicalPath.java new file mode 100644 index 00000000..d64ea56b --- /dev/null +++ b/java/src/com/zerotier/sdk/PeerPhysicalPath.java @@ -0,0 +1,86 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +import java.net.InetSocketAddress; + +/** + * Physical network path to a peer + */ +public final class PeerPhysicalPath { +    private InetSocketAddress address; +    private long lastSend; +    private long lastReceive; +    private boolean fixed; +    private boolean active; +    private boolean preferred; + +    private PeerPhysicalPath() {} + +    /** +     * Address of endpoint +     */ +    public final InetSocketAddress address() { +        return address; +    } + +    /** +     * Time of last send in milliseconds or 0 for never +     */ +    public final long lastSend() { +        return lastSend; +    } + +    /** +     * Time of last receive in milliseconds or 0 for never +     */ +    public final long lastReceive() { +        return lastReceive; +    } + +    /** +     * Is path fixed? (i.e. not learned, static) +     */ +    public final boolean isFixed() { +        return fixed; +    } + +    /** +     * Is path active? +     */ +    public final boolean isActive() { +        return active; +    } + +    /** +     * Is path preferred? +     */ +    public final boolean isPreferred() { +        return preferred; +    } +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/PeerRole.java b/java/src/com/zerotier/sdk/PeerRole.java new file mode 100644 index 00000000..56c3ac0c --- /dev/null +++ b/java/src/com/zerotier/sdk/PeerRole.java @@ -0,0 +1,45 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +public enum PeerRole { +    /** +     * An ordinary node +     */ +    PEER_ROLE_LEAF, + +    /** +     * Locally federated hub +     */ +    PEER_ROLE_HUB, + +    /** +     * planetary supernode +     */ +    PEER_ROLE_SUPERNODE +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/ResultCode.java b/java/src/com/zerotier/sdk/ResultCode.java new file mode 100644 index 00000000..5da82b31 --- /dev/null +++ b/java/src/com/zerotier/sdk/ResultCode.java @@ -0,0 +1,74 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +/** + * Function return code: OK (0) or error results + * + * <p>Use {@link ResultCode#isFatal) to check for a fatal error. If a fatal error + * occurs, the node should be considered to not be working correctly. These + * indicate serious problems like an inaccessible data store or a compile + * problem.</p> + */ +public enum ResultCode { +    /** +     * Operation completed normally +     */ +	RESULT_OK(0), + +    // Fatal errors (> 0, < 1000) +    /** +     * Ran out of memory +     */ +	RESULT_FATAL_ERROR_OUT_OF_MEMORY(1), + +    /** +     * Data store is not writable or has failed +     */ +	RESULT_FATAL_ERROR_DATA_STORE_FAILED(2), + +    /** +     * Internal error (e.g. unexpected exception indicating bug or build problem) +     */ +	RESULT_FATAL_ERROR_INTERNAL(3), + +    // non-fatal errors + +    /** +     * Network ID not valid +     */ +	RESULT_ERROR_NETWORK_NOT_FOUND(1000); +	 +	private final int id; +    ResultCode(int id) { this.id = id; } +    public int getValue() { return id; } + +    public boolean isFatal(int id) { +    	return (id > 0 && id < 1000); +    } +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/Version.java b/java/src/com/zerotier/sdk/Version.java new file mode 100644 index 00000000..d7fa0ce4 --- /dev/null +++ b/java/src/com/zerotier/sdk/Version.java @@ -0,0 +1,37 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +public final class Version { +    private Version() {} +     +	public int major = 0; +	public int minor = 0; +	public int revision = 0; +	public long featureFlags = 0; +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/VirtualNetworkConfig.java b/java/src/com/zerotier/sdk/VirtualNetworkConfig.java new file mode 100644 index 00000000..032ba267 --- /dev/null +++ b/java/src/com/zerotier/sdk/VirtualNetworkConfig.java @@ -0,0 +1,170 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +import java.lang.String; +import java.util.ArrayList; +import java.net.InetSocketAddress; + +public final class VirtualNetworkConfig { +    public static final int MAX_MULTICAST_SUBSCRIPTIONS = 4096; +    public static final int ZT1_MAX_ZT_ASSIGNED_ADDRESSES = 16; + +    private long nwid; +    private long mac; +    private String name; +    private VirtualNetworkStatus status; +    private VirtualNetworkType type; +    private int mtu; +    private boolean dhcp; +    private boolean bridge; +    private boolean broadcastEnabled; +    private int portError; +    private boolean enabled; +    private long netconfRevision; +    private ArrayList<MulticastGroup> multicastSubscriptions; +    private ArrayList<InetSocketAddress> assignedAddresses; + +    private VirtualNetworkConfig() { + +    } + +    /** +     * 64-bit ZeroTier network ID +     */ +    public final long networkId() { +        return nwid; +    } + +    /** +     * Ethernet MAC (40 bits) that should be assigned to port +     */ +    public final long macAddress() { +        return mac; +    } + +    /** +     * Network name (from network configuration master) +     */ +    public final String name() { +        return name; +    } + +    /** +     * Network configuration request status +     */ +    public final VirtualNetworkStatus networkStatus() { +        return status; +    } + +    /** +     * Network type +     */ +    public final VirtualNetworkType networkType() { +        return type; +    } + +    /** +     * Maximum interface MTU +     */ +    public final int mtu() { +        return mtu; +    } + +    /** +     * If the network this port belongs to indicates DHCP availability +     * +     * <p>This is a suggestion. The underlying implementation is free to ignore it +     * for security or other reasons. This is simply a netconf parameter that +     * means 'DHCP is available on this network.'</p> +     */ +    public final boolean isDhcpAvailable() { +        return dhcp; +    } + +    /** +     * If this port is allowed to bridge to other networks +     * +     * <p>This is informational. If this is false, bridged packets will simply +     * be dropped and bridging won't work.</p> +     */ +    public final boolean isBridgeEnabled() { +        return bridge; +    } + +    /** +     * If true, this network supports and allows broadcast (ff:ff:ff:ff:ff:ff) traffic +     */ +    public final boolean broadcastEnabled() { +        return broadcastEnabled; +    } + +    /** +     * If the network is in PORT_ERROR state, this is the error most recently returned by the port config callback +     */ +    public final int portError() { +        return portError; +    } + +    /** +     * Is this network enabled? If not, all frames to/from are dropped. +     */ +    public final boolean isEnabled() { +        return enabled; +    } + +    /** +     * Network config revision as reported by netconf master +     * +     * <p>If this is zero, it means we're still waiting for our netconf.</p> +     */ +    public final long netconfRevision() { +        return netconfRevision; +    } + +    /** +     * Multicast group subscriptions +     */ +    public final ArrayList<MulticastGroup> multicastSubscriptions() { +        return multicastSubscriptions; +    } + +    /** +     * ZeroTier-assigned addresses (in {@link java.net.InetSocketAddress} objects) +     * +     * For IP, the port number of the sockaddr_XX structure contains the number +     * of bits in the address netmask. Only the IP address and port are used. +     * Other fields like interface number can be ignored. +     * +     * This is only used for ZeroTier-managed address assignments sent by the +     * virtual network's configuration master. +     */ +    public final ArrayList<InetSocketAddress> assignedAddresses() { +        return assignedAddresses; +    } +} diff --git a/java/src/com/zerotier/sdk/VirtualNetworkConfigListener.java b/java/src/com/zerotier/sdk/VirtualNetworkConfigListener.java new file mode 100644 index 00000000..15ae301c --- /dev/null +++ b/java/src/com/zerotier/sdk/VirtualNetworkConfigListener.java @@ -0,0 +1,60 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + + +package com.zerotier.sdk; + + +public interface VirtualNetworkConfigListener { +    /** +     * Callback called to update virtual network port configuration +     * +     * <p>This can be called at any time to update the configuration of a virtual +     * network port. The parameter after the network ID specifies whether this +     * port is being brought up, updated, brought down, or permanently deleted. +     * +     * This in turn should be used by the underlying implementation to create +     * and configure tap devices at the OS (or virtual network stack) layer.</P> +     * +     * This should not call {@link Node#multicastSubscribe} or other network-modifying +     * methods, as this could cause a deadlock in multithreaded or interrupt +     * driven environments. +     * +     * This must return 0 on success. It can return any OS-dependent error code +     * on failure, and this results in the network being placed into the +     * PORT_ERROR state. +     * +     * @param nwid network id +     * @param op {@link VirtualNetworkConfigOperation} enum describing the configuration operation +     * @param config {@link VirtualNetworkConfig} object with the new configuration +     * @return 0 on success +     */ +    public int onNetworkConfigurationUpdated( +            long nwid, +            VirtualNetworkConfigOperation op, +            VirtualNetworkConfig config); +}
\ No newline at end of file diff --git a/java/src/com/zerotier/sdk/VirtualNetworkConfigOperation.java b/java/src/com/zerotier/sdk/VirtualNetworkConfigOperation.java new file mode 100644 index 00000000..b70eb478 --- /dev/null +++ b/java/src/com/zerotier/sdk/VirtualNetworkConfigOperation.java @@ -0,0 +1,49 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ +package com.zerotier.sdk; + +public enum VirtualNetworkConfigOperation { +    /** +     * Network is coming up (either for the first time or after service restart) +     */ +    VIRTUAL_NETWORK_CONFIG_OPERATION_UP, + +    /** +     * Network configuration has been updated +     */ +    VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE, + +    /** +     * Network is going down (not permanently) +     */ +    VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN, + +    /** +     * Network is going down permanently (leave/delete) +     */ +    VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY +} diff --git a/java/src/com/zerotier/sdk/VirtualNetworkFrameListener.java b/java/src/com/zerotier/sdk/VirtualNetworkFrameListener.java new file mode 100644 index 00000000..17c6540d --- /dev/null +++ b/java/src/com/zerotier/sdk/VirtualNetworkFrameListener.java @@ -0,0 +1,48 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +package com.zerotier.sdk; + +public interface VirtualNetworkFrameListener { +    /** +     * Function to send a frame out to a virtual network port +     *  +     * @param nwid ZeroTier One network ID +     * @param srcMac source MAC address +     * @param destMac destination MAC address +     * @param ethertype +     * @param vlanId +     * @param frameData data to send +     */ +    void onVirtualNetworkFrame( +                long nwid, +                long srcMac, +                long destMac, +                long etherType, +                long vlanId, +                byte[] frameData); +} diff --git a/java/src/com/zerotier/sdk/VirtualNetworkStatus.java b/java/src/com/zerotier/sdk/VirtualNetworkStatus.java new file mode 100644 index 00000000..2d00561a --- /dev/null +++ b/java/src/com/zerotier/sdk/VirtualNetworkStatus.java @@ -0,0 +1,59 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ +package com.zerotier.sdk; + +public enum VirtualNetworkStatus { +    /** +     * Waiting for network configuration (also means revision == 0) +     */ +    NETWORK_STATUS_REQUESTING_CONFIGURATION, + +    /** +     * Configuration received and we are authorized +     */ +    NETWORK_STATUS_OK, + +    /** +     * Netconf master told us 'nope' +     */ +    NETWORK_STATUS_ACCESS_DENIED, + +    /** +     * Netconf master exists, but this virtual network does not +     */ +    NETWORK_STATUS_NOT_FOUND, + +    /** +     * Initialization of network failed or other internal error +     */ +    NETWORK_STATUS_PORT_ERROR, + +    /** +     * ZeroTier One version too old +     */ +    NETWORK_STATUS_CLIENT_TOO_OLD +} diff --git a/java/src/com/zerotier/sdk/VirtualNetworkType.java b/java/src/com/zerotier/sdk/VirtualNetworkType.java new file mode 100644 index 00000000..ab1f4e08 --- /dev/null +++ b/java/src/com/zerotier/sdk/VirtualNetworkType.java @@ -0,0 +1,39 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015  ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program.  If not, see <http://www.gnu.org/licenses/>. + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ +package com.zerotier.sdk; + +public enum VirtualNetworkType { +    /** +     * Private networks are authorized via certificates of membership +     */ +    NETWORK_TYPE_PRIVATE, + +    /** +     * Public networks have no access control -- they'll always be AUTHORIZED +     */ +    NETWORK_TYPE_PUBLIC +} | 
