Unity3D integration updates

This commit is contained in:
Joseph Henry
2016-07-18 11:35:40 -07:00
parent 9df8a57dd0
commit b8747670b3
19 changed files with 115 additions and 1224 deletions

View File

@@ -6,7 +6,7 @@
<ProductVersion>10.0.20506</ProductVersion> <ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<RootNamespace></RootNamespace> <RootNamespace></RootNamespace>
<ProjectGuid>{24F9E71C-1810-2FEA-B9CC-4258EB20D4CD}</ProjectGuid> <ProjectGuid>{CCA76E42-E9D5-4CBF-3222-F488C499DCF3}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<AssemblyName>Assembly-CSharp-Editor</AssemblyName> <AssemblyName>Assembly-CSharp-Editor</AssemblyName>
@@ -19,7 +19,7 @@
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>Temp\bin\Debug\</OutputPath> <OutputPath>Temp\bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_5;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_STANDALONE_OSX;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_TEXTUREID_MAP;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_CLUSTERINPUT;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_OSX</DefineConstants> <DefineConstants>DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_5;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_STANDALONE_OSX;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_TEXTUREID_MAP;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_CLUSTERINPUT;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_OSX;UNITY_TEAM_LICENSE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<NoWarn>0169</NoWarn> <NoWarn>0169</NoWarn>
@@ -48,7 +48,7 @@
<Compile Include="Assets\OBJ-IO\Editor\OBJEditor.cs" /> <Compile Include="Assets\OBJ-IO\Editor\OBJEditor.cs" />
<None Include="Assets\OBJ-IO\Readme.txt" /> <None Include="Assets\OBJ-IO\Readme.txt" />
<Reference Include="Assembly-UnityScript"> <Reference Include="Assembly-UnityScript">
<HintPath>/Users/Joseph/ZeroTier-Unity3D-Test/Library/ScriptAssemblies/Assembly-UnityScript.dll</HintPath> <HintPath>/Users/Joseph/code/ZeroTierSDK/integrations/Unity3D/Library/ScriptAssemblies/Assembly-UnityScript.dll</HintPath>
</Reference> </Reference>
<Reference Include="UnityEngine.Networking"> <Reference Include="UnityEngine.Networking">
<HintPath>/Applications/Unity/Unity.app/Contents/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll</HintPath> <HintPath>/Applications/Unity/Unity.app/Contents/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll</HintPath>
@@ -95,7 +95,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="Assembly-CSharp.csproj"> <ProjectReference Include="Assembly-CSharp.csproj">
<Project>{5AB900A8-5B14-044A-A52D-10417305A5D2}</Project> <Name>Assembly-CSharp</Name> </ProjectReference> <Project>{7214E491-EE9D-B906-A42D-2F3EA3DCD8FE}</Project> <Name>Assembly-CSharp</Name> </ProjectReference>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.

View File

@@ -6,7 +6,7 @@
<ProductVersion>10.0.20506</ProductVersion> <ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<RootNamespace></RootNamespace> <RootNamespace></RootNamespace>
<ProjectGuid>{5AB900A8-5B14-044A-A52D-10417305A5D2}</ProjectGuid> <ProjectGuid>{7214E491-EE9D-B906-A42D-2F3EA3DCD8FE}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<AssemblyName>Assembly-CSharp</AssemblyName> <AssemblyName>Assembly-CSharp</AssemblyName>
@@ -19,7 +19,7 @@
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>Temp\bin\Debug\</OutputPath> <OutputPath>Temp\bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_5;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_STANDALONE_OSX;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_TEXTUREID_MAP;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_CLUSTERINPUT;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_OSX</DefineConstants> <DefineConstants>DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_5;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_STANDALONE_OSX;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_GAMECENTER;ENABLE_TEXTUREID_MAP;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_CLUSTERINPUT;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_OSX;UNITY_TEAM_LICENSE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<NoWarn>0169</NoWarn> <NoWarn>0169</NoWarn>
@@ -45,7 +45,6 @@
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Assets\Demo.cs" />
<Compile Include="Assets\MyZeroTier.cs" /> <Compile Include="Assets\MyZeroTier.cs" />
<Compile Include="Assets\OBJ-IO\Examples\Scripts\Example.cs" /> <Compile Include="Assets\OBJ-IO\Examples\Scripts\Example.cs" />
<Compile Include="Assets\OBJ-IO\Plugins\Extension\GameObjectExtension.cs" /> <Compile Include="Assets\OBJ-IO\Plugins\Extension\GameObjectExtension.cs" />
@@ -63,7 +62,8 @@
<Compile Include="Assets\OBJ-IO\Plugins\Mesh\OBJ\OBJMaterial.cs" /> <Compile Include="Assets\OBJ-IO\Plugins\Mesh\OBJ\OBJMaterial.cs" />
<Compile Include="Assets\OBJ-IO\Plugins\Utils\Int32Converter.cs" /> <Compile Include="Assets\OBJ-IO\Plugins\Utils\Int32Converter.cs" />
<Compile Include="Assets\WorldMain.cs" /> <Compile Include="Assets\WorldMain.cs" />
<Compile Include="Assets\ZeroTier.cs" /> <Compile Include="Assets\ZeroTierNetworkInterface.cs" />
<Compile Include="Assets\ZeroTierSockets_Demo.cs" />
<Compile Include="Assets\ZeroTierUtils.cs" /> <Compile Include="Assets\ZeroTierUtils.cs" />
<None Include="Assets\OBJ-IO\Readme.txt" /> <None Include="Assets\OBJ-IO\Readme.txt" />
<Reference Include="UnityEngine.Networking"> <Reference Include="UnityEngine.Networking">

View File

@@ -1,167 +0,0 @@
using UnityEngine;
using System.Collections;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.UI;
using UnityEngine.Networking;
public class Demo : MonoBehaviour
{
public float speed = 300f;
private ZeroTierNetworkInterface zt;
string nwid = "";
int server_connection_socket; // The "connection id"
// Demo button methods
public void Join()
{
GameObject go = GameObject.Find ("inputNetworkID");
InputField input = go.GetComponents<InputField> () [0];
Debug.Log ("Joining: " + input.text);
zt.JoinNetwork (input.text);
}
public void Leave()
{
GameObject go = GameObject.Find ("inputNetworkID");
InputField input = go.GetComponents<InputField> () [0];
Debug.Log ("Leaving: " + input.text);
zt.LeaveNetwork (input.text);
}
public void Connect()
{
GameObject addr_go = GameObject.Find ("inputServerAddress");
GameObject port_go = GameObject.Find ("inputServerPort");
InputField addr = addr_go.GetComponents<InputField> () [0];
InputField port = port_go.GetComponents<InputField> () [0];
Debug.Log ("Connecting to: " + addr.text + ":" + port.text);
Thread connectThread = new Thread(() => {
byte error = 0;
server_connection_socket = zt.Connect (0, addr.text, int.Parse (port.text), out error);
Debug.Log ("server_connection_socket = " + server_connection_socket);
Debug.Log ("Connect(): " + error);
});
connectThread.IsBackground = true;
connectThread.Start();
}
public void Disconnect()
{
GameObject addr_go = GameObject.Find ("inputServerAddress");
GameObject port_go = GameObject.Find ("inputServerAddress");
InputField addr = addr_go.GetComponents<InputField> () [0];
InputField port = port_go.GetComponents<InputField> () [0];
Debug.Log ("Disconnecting from: " + addr.text + ":" + port.text);
Debug.Log ("Disconnect(): " + zt.Disconnect (server_connection_socket));
}
public void SendMessage()
{
//zt_test_network ();
GameObject go = GameObject.Find ("inputMessage");
InputField msg = go.GetComponents<InputField> () [0];
Thread sendThread = new Thread(() => {
Debug.Log ("Sending Message: " + msg.text);
byte error = 0;
zt.Send (server_connection_socket, msg.text.ToCharArray (), msg.text.ToCharArray ().Length, out error);
Debug.Log ("Send(): " + error);
});
sendThread.IsBackground = true;
sendThread.Start();
}
void Start()
{
// Set defaults
InputField input;
GameObject go;
go = GameObject.Find ("inputNetworkID");
input = go.GetComponents<InputField> () [0];
input.text = "565799d8f6e1c11a";
go = GameObject.Find ("inputServerAddress");
input = go.GetComponents<InputField> () [0];
input.text = "172.22.211.245";
go = GameObject.Find ("inputServerPort");
input = go.GetComponents<InputField> () [0];
input.text = "8887";
go = GameObject.Find ("inputMessage");
input = go.GetComponents<InputField> () [0];
input.text = "Welcome to the machine";
// Create new instance of ZeroTier in separate thread
zt = new ZeroTierNetworkInterface ("/Users/Joseph/utest2/nc_565799d8f6e1c11a");
/* This new instance will communicate via a named pipe, so any
* API calls (ZeroTier.Connect(), ZeroTier.Send(), etc) will be sent to the service
* via this pipe.
*/
}
// Terminate the ZeroTier service when the application quits
void OnApplicationQuit() {
Debug.Log ("OnApplicationQuit()");
zt.Terminate ();
}
// Update is called once per frame
void Update () {
/*
if (text) {
text.text = IsRunning() ? "ZeroTier Status: Online" : "ZeroTier Status: Offline";
}
*/
// ---
int recHostId;
int connectionId;
int channelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkEventType recData = zt.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
switch (recData)
{
case NetworkEventType.Nothing: //1
break;
case NetworkEventType.ConnectEvent: //2
Debug.Log("NetworkEventType.ConnectEvent");
break;
case NetworkEventType.DataEvent: //3
Debug.Log("NetworkEventType.DataEvent");
break;
case NetworkEventType.DisconnectEvent: //4
Debug.Log("NetworkEventType.DisconnectEvent");
break;
}
// ---
/*
GameObject go = GameObject.Find ("_txtStatusIndicator");
Text text = go.GetComponents<Text> () [0];
text.text = zt.IsRunning () ? "ZeroTier Service: ONLINE" : "ZeroTier Service: OFFLINE";
*/
// Rotate ZTCube when ZT is running
/*
if (zt.IsRunning ()) {
go = GameObject.Find ("ZTCube");
Vector3 rotvec = new Vector3 (10f, 10f, 10f);
go.transform.Rotate (rotvec, speed * Time.deltaTime);
}
GameObject go = GameObject.Find("ZTCube");
Text text = go.GetComponents<Text> ()[0];
*/
}
}

View File

@@ -1,214 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <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/
*/
using UnityEngine;
using System.Collections;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.UI;
using UnityEngine.Networking;
// Demonstrates the usage of the ZeroTier LLAPI (modeled after the Unity LLAPI)
public class ZeroTierLLAPI_Demo : MonoBehaviour
{
public float speed = 300f;
private ZeroTierLLAPI zt;
string nwid = "";
int server_connection_socket; // The "connection id"
int host_socket;
// Demo button methods
public void Join()
{
GameObject go = GameObject.Find ("inputNetworkID");
InputField input = go.GetComponents<InputField> () [0];
Debug.Log ("Joining: " + input.text);
zt.JoinNetwork (input.text);
}
public void Leave()
{
GameObject go = GameObject.Find ("inputNetworkID");
InputField input = go.GetComponents<InputField> () [0];
Debug.Log ("Leaving: " + input.text);
zt.LeaveNetwork (input.text);
}
public void Connect()
{
GameObject addr_go = GameObject.Find ("inputServerAddress");
GameObject port_go = GameObject.Find ("inputServerPort");
InputField addr = addr_go.GetComponents<InputField> () [0];
InputField port = port_go.GetComponents<InputField> () [0];
Debug.Log ("Connecting to: " + addr.text + ":" + port.text);
Thread connectThread = new Thread(() => {
byte error = 0;
server_connection_socket = zt.Connect (0, addr.text, int.Parse (port.text), out error);
Debug.Log ("server_connection_socket = " + server_connection_socket);
Debug.Log ("Connect(): " + error);
});
connectThread.IsBackground = true;
connectThread.Start();
}
public void Bind()
{
GameObject addr_go = GameObject.Find ("inputServerAddress");
GameObject port_go = GameObject.Find ("inputServerPort");
InputField addr = addr_go.GetComponents<InputField> () [0];
InputField port = port_go.GetComponents<InputField> () [0];
Debug.Log ("Binding to: " + addr.text + ":" + port.text);
Thread connectThread = new Thread(() => {
byte error = 0;
host_socket = zt.AddHost (int.Parse (port.text));
Debug.Log ("host_socket = " + host_socket);
Debug.Log ("Bind(): " + error);
});
connectThread.IsBackground = true;
connectThread.Start();
}
public void Disconnect()
{
GameObject addr_go = GameObject.Find ("inputServerAddress");
GameObject port_go = GameObject.Find ("inputServerAddress");
InputField addr = addr_go.GetComponents<InputField> () [0];
InputField port = port_go.GetComponents<InputField> () [0];
Debug.Log ("Disconnecting from: " + addr.text + ":" + port.text);
Debug.Log ("Disconnect(): " + zt.Disconnect (server_connection_socket));
}
public void SendMessage()
{
//zt_test_network ();
GameObject go = GameObject.Find ("inputMessage");
InputField msg = go.GetComponents<InputField> () [0];
Thread sendThread = new Thread(() => {
Debug.Log ("Sending Message: " + msg.text);
byte error = 0;
zt.Send (server_connection_socket, msg.text.ToCharArray (), msg.text.ToCharArray ().Length, out error);
Debug.Log ("Send(): " + error);
});
sendThread.IsBackground = true;
sendThread.Start();
}
void Start()
{
// Set defaults
InputField input;
GameObject go;
go = GameObject.Find ("inputNetworkID");
input = go.GetComponents<InputField> () [0];
input.text = "565799d8f6e1c11a";
go = GameObject.Find ("inputServerAddress");
input = go.GetComponents<InputField> () [0];
input.text = "172.22.211.245";
go = GameObject.Find ("inputServerPort");
input = go.GetComponents<InputField> () [0];
input.text = "8887";
go = GameObject.Find ("inputMessage");
input = go.GetComponents<InputField> () [0];
input.text = "Welcome to the machine";
// Create new instance of ZeroTier in separate thread
zt = new ZeroTierLLAPI ("/Users/Joseph/utest2/nc_565799d8f6e1c11a");
/* This new instance will communicate via a named pipe, so any
* API calls (ZeroTier.Connect(), ZeroTier.Send(), etc) will be sent to the service
* via this pipe.
*/
}
// Terminate the ZeroTier service when the application quits
void OnApplicationQuit() {
Debug.Log ("OnApplicationQuit()");
zt.Terminate ();
}
// Update is called once per frame
void Update () {
/*
if (text) {
text.text = IsRunning() ? "ZeroTier Status: Online" : "ZeroTier Status: Offline";
}
*/
// ---
int recHostId;
int connectionId;
int channelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkEventType recData = zt.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
switch (recData)
{
case NetworkEventType.Nothing:
break;
case NetworkEventType.ConnectEvent:
Debug.Log("NetworkEventType.ConnectEvent");
break;
case NetworkEventType.DataEvent:
Debug.Log("NetworkEventType.DataEvent");
break;
case NetworkEventType.DisconnectEvent:
Debug.Log("NetworkEventType.DisconnectEvent");
break;
}
// ---
/*
GameObject go = GameObject.Find ("_txtStatusIndicator");
Text text = go.GetComponents<Text> () [0];
text.text = zt.IsRunning () ? "ZeroTier Service: ONLINE" : "ZeroTier Service: OFFLINE";
*/
// Rotate ZTCube when ZT is running
/*
if (zt.IsRunning ()) {
go = GameObject.Find ("ZTCube");
Vector3 rotvec = new Vector3 (10f, 10f, 10f);
go.transform.Rotate (rotvec, speed * Time.deltaTime);
}
GameObject go = GameObject.Find("ZTCube");
Text text = go.GetComponents<Text> ()[0];
*/
}
}

View File

@@ -1,332 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <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/
*/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
using C5;
public class ZeroTierNetworkInterface {
// Apple
#if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
const string DLL_PATH = "ZeroTierSDK_Unity3D_OSX";
#endif
#if UNITY_IOS || UNITY_IPHONE
const string DLL_PATH = "ZeroTierSDK_Unity3D_iOS";
#endif
// Windows
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
const string DLL_PATH = "ZeroTierSDK_Unity3D_WIN";
#endif
// Linux
#if UNITY_STANDALONE_LINUX
const string DLL_PATH = "ZeroTierSDK_Unity3D_LINUX";
#endif
// Android
#if UNITY_ANDROID
const string DLL_PATH = "ZeroTierSDK_Unity3D_ANDROID";
#endif
// Interop structures
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct sockaddr {
/// u_short->unsigned short
public ushort sa_family;
/// char[14]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=14)]
public string sa_data;
}
// ZeroTier background thread
private Thread ztThread;
private ArrayList<int> connections = new ArrayList<int> ();
// Virtual network interace config
private int MaxPacketSize;
private string rpc_path = "/does/this/work";
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void MyDelegate(string str);
static void CallBackFunction(string str) {
Debug.Log("Native ZT Plugin: " + str);
}
#region
// ZeroTier service / debug initialization
[DllImport (DLL_PATH)]
public static extern void SetDebugFunction( IntPtr fp );
[DllImport (DLL_PATH)]
private static extern int unity_start_service(string path);
// Connection calls
[DllImport (DLL_PATH)]
private static extern int zt_socket(int family, int type, int protocol);
[DllImport (DLL_PATH)]
unsafe private static extern int zt_bind(int sockfd, System.IntPtr addr, int addrlen);
[DllImport (DLL_PATH)]
unsafe private static extern int zt_connect(int sockfd, System.IntPtr addr, int addrlen);
[DllImport (DLL_PATH)]
private static extern int zt_accept(int sockfd);
[DllImport (DLL_PATH)]
private static extern int zt_listen(int sockfd, int backlog);
[DllImport (DLL_PATH)]
private static extern int zt_close(int sockfd);
// RX / TX
[DllImport (DLL_PATH)]
unsafe private static extern int zt_recv(int sockfd, string buf, int len);
[DllImport (DLL_PATH)]
unsafe private static extern int zt_send(int sockfd, IntPtr buf, int len);
[DllImport (DLL_PATH)]
unsafe private static extern int zt_set_nonblock(int sockfd);
// ZT Thread controls
[DllImport (DLL_PATH)]
private static extern bool zt_is_running();
[DllImport (DLL_PATH)]
private static extern void zt_terminate();
// ZT Network controls
[DllImport (DLL_PATH)]
private static extern bool zt_join_network(string nwid);
[DllImport (DLL_PATH)]
private static extern void zt_leave_network(string nwid);
#endregion
// Thread which starts the ZeroTier service
// The ZeroTier service may spin off a SOCKS5 proxy server
// if -DUSE_SOCKS_PROXY is set when building the bundle
private void zt_service_thread()
{
MyDelegate callback_delegate = new MyDelegate( CallBackFunction );
// Convert callback_delegate into a function pointer that can be
// used in unmanaged code.
IntPtr intptr_delegate =
Marshal.GetFunctionPointerForDelegate(callback_delegate);
// Call the API passing along the function pointer.
SetDebugFunction( intptr_delegate );
Debug.Log ("rpc_path = " + rpc_path);
unity_start_service (rpc_path);
}
// Start the ZeroTier service
private void Init()
{
// TODO: Handle exceptions from unmanaged code
ztThread = new Thread(() => {
try {
zt_service_thread();
} catch(Exception e) {
Debug.Log(e.Message.ToString());
}
});
ztThread.IsBackground = true; // Allow the thread to be aborted safely
ztThread.Start();
}
// Initialize the ZeroTier service with a given path
public ZeroTierNetworkInterface(string path)
{
rpc_path = path;
Init();
}
// Initialize the ZeroTier service
public ZeroTierNetworkInterface()
{
Init();
}
// Initialize the ZeroTier service
// Use the GlobalConfig to set things like the max packet size
public ZeroTierNetworkInterface(GlobalConfig gConfig)
{
MaxPacketSize = gConfig.MaxPacketSize; // TODO: Do something with this!
Init();
}
// Joins a ZeroTier virtual network
public void JoinNetwork(string nwid)
{
zt_join_network(nwid);
}
// Leaves a ZeroTier virtual network
public void LeaveNetwork(string nwid)
{
zt_leave_network(nwid);
}
// Creates a ZeroTier Socket and binds on the port provided
// A client instance can now connect to this "host"
public int AddHost(int port)
{
int sockfd = zt_socket ((int)AddressFamily.InterNetwork, (int)SocketType.Stream, (int)ProtocolType.Unspecified);
if (sockfd < 0) {
return -1;
}
GCHandle sockaddr_ptr = ZeroTierUtils.Generate_unmananged_sockaddr("0.0.0.0" + ":" + port);
IntPtr pSockAddr = sockaddr_ptr.AddrOfPinnedObject ();
int addrlen = Marshal.SizeOf (pSockAddr);
// Set socket to non-blocking for RX polling in Receive()
zt_set_nonblock(sockfd);
return zt_bind (sockfd, pSockAddr, addrlen);
}
// hostId - host socket ID for this connection
public int Connect(int hostId, string address, int port, out byte error)
{
int sockfd = zt_socket ((int)AddressFamily.InterNetwork, (int)SocketType.Stream, (int)ProtocolType.Unspecified);
Debug.Log ("sockfd = " + sockfd);
if (sockfd < 0) {
error = (byte)sockfd;
return -1;
}
GCHandle sockaddr_ptr = ZeroTierUtils.Generate_unmananged_sockaddr(address + ":" + port);
IntPtr pSockAddr = sockaddr_ptr.AddrOfPinnedObject ();
int addrlen = Marshal.SizeOf (pSockAddr);
error = (byte)zt_connect (sockfd, pSockAddr, addrlen);
// Set socket to non-blocking for RX polling in Receive()
zt_set_nonblock(sockfd);
return sockfd;
}
// Returns whether the ZeroTier service is currently running
public bool IsRunning()
{
return zt_is_running ();
}
// Terminates the ZeroTier service
public void Terminate()
{
zt_terminate ();
}
// Shutdown a given connection
public int Disconnect(int fd)
{
return zt_close (fd);
}
// Write data to a ZeroTier socket
/*
public int Send(int fd, char[] buf, int len, out byte error)
{
GCHandle buf_handle = GCHandle.Alloc (buf, GCHandleType.Pinned);
IntPtr pBufPtr = buf_handle.AddrOfPinnedObject ();
error = 0;
int bytes_written;
string str = new string (buf);
if((bytes_written = zt_send (fd, str, len)) < 0) {
error = (byte)bytes_written;
}
return bytes_written;
}
*/
// Write data to a ZeroTier socket
public int Send(int fd, char[] buf, int len, out byte error)
{
GCHandle handle = GCHandle.Alloc(buf, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
error = 0;
int bytes_written;
// FIXME: Sending a length of 2X the buffer size seems to fix the object pinning issue
if((bytes_written = zt_send(fd, ptr, len*2)) < 0) {
error = (byte)bytes_written;
}
return bytes_written;
}
// Checks for data to RX
/*
public enum NetworkEventType
{
DataEvent,
ConnectEvent,
DisconnectEvent,
Nothing,
BroadcastEvent
}
*/
public NetworkEventType Receive(out int hostId, out int connectionId, out int channelId, byte[] buffer, int bufferSize, out int receivedSize, out byte error)
{
/*
* If recBuffer is big enough to contain data, data will be copied in the buffer.
* If not, error will contain MessageToLong error and you will need reallocate
* buffer and call this function again. */
for (int i = 0; i < connections.Count; i++) {
}
int res;
res = zt_recv (connectionId, buffer, bufferSize);
// FIXME: Not quite semantically the same, but close enough for alpha release?
// FIXME: Get notifications of disconnect events?
if (res == -1) {
error = -1;
return NetworkEventType.DisconnectEvent;
}
if(res == 0) {
error = 0;
return NetworkEventType.Nothing; // No data read
}
if (res > 0) {
receivedSize = res;
Marshal.Copy(buffer, buffer, 0, res);
return NetworkEventType.DataEvent; // Data read into buffer
}
}
}

View File

@@ -1,175 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <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/
*/
using UnityEngine;
using System.Collections;
using System.Threading;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System;
using UnityEngine.Networking;
// Provides a familiar interface which is modeled after the Unity LLAPI
public class ZeroTierLLAPI : ZeroTierNetworkInterface {
// Initialize the ZeroTier service with a given path
public ZeroTierLLAPI(string path)
{
rpc_path = path;
Init();
}
// Creates a ZeroTier Socket and binds on the port provided
// A client instance can now connect to this "host"
public int AddHost(int port)
{
int sockfd = zt_socket ((int)AddressFamily.InterNetwork, (int)SocketType.Stream, (int)ProtocolType.Unspecified);
if (sockfd < 0) {
return -1;
}
GCHandle sockaddr_ptr = ZeroTierUtils.Generate_unmananged_sockaddr("0.0.0.0" + ":" + port);
IntPtr pSockAddr = sockaddr_ptr.AddrOfPinnedObject ();
int addrlen = Marshal.SizeOf (pSockAddr);
// Set socket to non-blocking for RX polling in Receive()
zt_set_nonblock(sockfd);
return zt_bind (sockfd, pSockAddr, addrlen);
}
// hostId - host socket ID for this connection
public int Connect(int hostId, string address, int port, out byte error)
{
int sockfd = zt_socket ((int)AddressFamily.InterNetwork, (int)SocketType.Stream, (int)ProtocolType.Unspecified);
Debug.Log ("sockfd = " + sockfd);
if (sockfd < 0) {
error = (byte)sockfd;
return -1;
}
GCHandle sockaddr_ptr = ZeroTierUtils.Generate_unmananged_sockaddr(address + ":" + port);
IntPtr pSockAddr = sockaddr_ptr.AddrOfPinnedObject ();
int addrlen = Marshal.SizeOf (pSockAddr);
error = (byte)zt_connect (sockfd, pSockAddr, addrlen);
// Set socket to non-blocking for RX polling in Receive()
zt_set_nonblock(sockfd);
return sockfd;
}
// Write data to a ZeroTier socket
public int Send(int fd, char[] buf, int len, out byte error)
{
error = 0;
return Write(fd, buf, len);
}
// Checks for data to RX
/*
public enum NetworkEventType
{
DataEvent,
ConnectEvent,
DisconnectEvent,
Nothing,
BroadcastEvent
}
*/
public NetworkEventType Receive(out int hostId, out int connectionId, out int channelId, byte[] buffer, int bufferSize, out int receivedSize, out byte error)
{
hostId = 0;
connectionId = 0;
channelId = 0;
receivedSize = 0;
error = 0;
// Read() ...
/*
* If recBuffer is big enough to contain data, data will be copied in the buffer.
* If not, error will contain MessageToLong error and you will need reallocate
* buffer and call this function again. */
//for (int i = 0; i < connections.Count; i++) {
//}
/*
int res;
res = zt_recv (connectionId, buffer, bufferSize);
// FIXME: Not quite semantically the same, but close enough for alpha release?
// FIXME: Get notifications of disconnect events?
if (res == -1) {
error = -1;
return NetworkEventType.DisconnectEvent;
}
if(res == 0) {
error = 0;
return NetworkEventType.Nothing; // No data read
}
if (res > 0) {
receivedSize = res;
Marshal.Copy(buffer, buffer, 0, res);
return NetworkEventType.DataEvent; // Data read into buffer
}
*/
return NetworkEventType.Nothing;
}
// Shutdown a given connection
public int Disconnect(int fd)
{
return zt_close (fd);
}
// Test serialization methods, should be removed for production
public static byte[] RawSerializeEx( object anything )
{
int rawsize = Marshal.SizeOf( anything );
byte[] rawdatas = new byte[ rawsize ];
GCHandle handle = GCHandle.Alloc( rawdatas, GCHandleType.Pinned );
IntPtr buffer = handle.AddrOfPinnedObject();
Marshal.StructureToPtr( anything, buffer, false );
handle.Free();
return rawdatas;
}
public static object RawDeserializeEx( byte[] rawdatas, Type anytype )
{
int rawsize = Marshal.SizeOf( anytype );
if( rawsize > rawdatas.Length )
return null;
GCHandle handle = GCHandle.Alloc( rawdatas, GCHandleType.Pinned );
IntPtr buffer = handle.AddrOfPinnedObject();
object retobj = Marshal.PtrToStructure( buffer, anytype );
handle.Free();
return retobj;
}
}

View File

@@ -59,6 +59,7 @@ public class ZeroTierNetworkInterface {
// Only allow one network at a time for BETA // Only allow one network at a time for BETA
protected bool joined_to_network = false; protected bool joined_to_network = false;
protected string nwid = ""; protected string nwid = "";
protected string path = "";
// Platform-specific paths and bundle/libary names // Platform-specific paths and bundle/libary names
#if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX #if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
@@ -88,6 +89,8 @@ public class ZeroTierNetworkInterface {
public static extern void SetDebugFunction( IntPtr fp ); public static extern void SetDebugFunction( IntPtr fp );
[DllImport (DLL_PATH)] [DllImport (DLL_PATH)]
private static extern int unity_start_service(string path); private static extern int unity_start_service(string path);
[DllImport (DLL_PATH)]
private static extern int unity_start_service_and_rpc(string path, string nwid);
// Connection calls // Connection calls
[DllImport (DLL_PATH)] [DllImport (DLL_PATH)]
@@ -153,8 +156,8 @@ public class ZeroTierNetworkInterface {
// Returns a path for RPC communications to the service // Returns a path for RPC communications to the service
private string rpcCommPath() private string rpcCommPath()
{ {
if(rpc_path != "" && nwid != "") { if(path != "" && nwid != "") {
return rpc_path + "nc_" + nwid; return path + "nc_" + nwid;
} }
return ""; return "";
} }
@@ -166,13 +169,18 @@ public class ZeroTierNetworkInterface {
MyDelegate callback_delegate = new MyDelegate( CallBackFunction ); MyDelegate callback_delegate = new MyDelegate( CallBackFunction );
IntPtr intptr_delegate = Marshal.GetFunctionPointerForDelegate(callback_delegate); IntPtr intptr_delegate = Marshal.GetFunctionPointerForDelegate(callback_delegate);
SetDebugFunction( intptr_delegate ); SetDebugFunction( intptr_delegate );
Debug.Log ("RPC = " + rpcCommPath());
// Start service // Start service
unity_start_service(rpcCommPath());
/* This new instance will communicate via a named pipe, so any /* This new instance will communicate via a named pipe, so any
* API calls (ZeroTier.Connect(), ZeroTier.Send(), etc) will be sent to the service * API calls (ZeroTier.Connect(), ZeroTier.Send(), etc) will be sent to the service
* via this pipe. * via this pipe.
*/ */
if(nwid.Length > 0) {
unity_start_service_and_rpc (path, nwid);
}
else {
unity_start_service(rpcCommPath());
}
} }
// Returns the nwid of the network you're currently connected to // Returns the nwid of the network you're currently connected to
@@ -200,12 +208,19 @@ public class ZeroTierNetworkInterface {
} }
// Initialize the ZeroTier service with a given path // Initialize the ZeroTier service with a given path
public ZeroTierNetworkInterface(string nwid) public ZeroTierNetworkInterface(string path, string nwid)
{ {
this.path = path;
this.nwid = nwid; this.nwid = nwid;
Init(); Init();
} }
public ZeroTierNetworkInterface (string path)
{
this.path = path;
Init();
}
// Initialize the ZeroTier service // Initialize the ZeroTier service
public ZeroTierNetworkInterface() public ZeroTierNetworkInterface()
{ {

View File

@@ -1,283 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <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/
*/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Collections.Generic;
// Provides a bare-bones interface to ZeroTier-administered sockets
public class ZeroTierNetworkInterface {
// Apple
#if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
const string DLL_PATH = "ZeroTierSDK_Unity3D_OSX";
#endif
#if UNITY_IOS || UNITY_IPHONE
const string DLL_PATH = "ZeroTierSDK_Unity3D_iOS";
#endif
// Windows
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
const string DLL_PATH = "ZeroTierSDK_Unity3D_WIN";
#endif
// Linux
#if UNITY_STANDALONE_LINUX
const string DLL_PATH = "ZeroTierSDK_Unity3D_LINUX";
#endif
// Android
#if UNITY_ANDROID
const string DLL_PATH = "ZeroTierSDK_Unity3D_ANDROID";
#endif
// Interop structures
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct sockaddr {
/// u_short->unsigned short
public ushort sa_family;
/// char[14]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=14)]
public string sa_data;
}
// ZeroTier background thread
protected Thread ztThread;
protected List<int> connections = new List<int> ();
protected int MaxPacketSize;
protected string rpc_path = "";
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void MyDelegate(string str);
static void CallBackFunction(string str) {
Debug.Log("Native ZT Plugin: " + str);
}
#region DLL Imports
// ZeroTier service / debug initialization
[DllImport (DLL_PATH)]
public static extern void SetDebugFunction( IntPtr fp );
[DllImport (DLL_PATH)]
private static extern int unity_start_service(string path);
// Connection calls
[DllImport (DLL_PATH)]
protected static extern int zt_socket(int family, int type, int protocol);
[DllImport (DLL_PATH)]
unsafe protected static extern int zt_bind(int sockfd, System.IntPtr addr, int addrlen);
[DllImport (DLL_PATH)]
unsafe protected static extern int zt_connect(int sockfd, System.IntPtr addr, int addrlen);
[DllImport (DLL_PATH)]
protected static extern int zt_accept(int sockfd);
[DllImport (DLL_PATH)]
protected static extern int zt_listen(int sockfd, int backlog);
[DllImport (DLL_PATH)]
protected static extern int zt_close(int sockfd);
// RX / TX
[DllImport (DLL_PATH)]
unsafe protected static extern int zt_recv(int sockfd, [In, Out] IntPtr buf, int len);
[DllImport (DLL_PATH)]
unsafe protected static extern int zt_send(int sockfd, IntPtr buf, int len);
[DllImport (DLL_PATH)]
unsafe protected static extern int zt_set_nonblock(int sockfd);
// ZT Thread controls
[DllImport (DLL_PATH)]
protected static extern bool zt_is_running();
[DllImport (DLL_PATH)]
protected static extern void zt_terminate();
// ZT Network controls
[DllImport (DLL_PATH)]
protected static extern bool zt_join_network(string nwid);
[DllImport (DLL_PATH)]
protected static extern void zt_leave_network(string nwid);
#endregion
// Thread which starts the ZeroTier service
// The ZeroTier service may spin off a SOCKS5 proxy server
// if -DUSE_SOCKS_PROXY is set when building the bundle
protected void zt_service_thread()
{
MyDelegate callback_delegate = new MyDelegate( CallBackFunction );
// Convert callback_delegate into a function pointer that can be
// used in unmanaged code.
IntPtr intptr_delegate =
Marshal.GetFunctionPointerForDelegate(callback_delegate);
// Call the API passing along the function pointer.
SetDebugFunction( intptr_delegate );
Debug.Log ("rpc_path = " + rpc_path);
unity_start_service (rpc_path);
}
// Start the ZeroTier service
protected void Init()
{
// TODO: Handle exceptions from unmanaged code
ztThread = new Thread(() => {
try {
zt_service_thread();
} catch(Exception e) {
Debug.Log(e.Message.ToString());
}
});
ztThread.IsBackground = true; // Allow the thread to be aborted safely
ztThread.Start();
}
// Initialize the ZeroTier service with a given path
public ZeroTierNetworkInterface(string path)
{
rpc_path = path;
Init();
}
// Initialize the ZeroTier service
public ZeroTierNetworkInterface()
{
Init();
}
// Initialize the ZeroTier service
// Use the GlobalConfig to set things like the max packet size
public ZeroTierNetworkInterface(GlobalConfig gConfig)
{
MaxPacketSize = gConfig.MaxPacketSize; // TODO: Do something with this!
Init();
}
#region Network Handling
// Joins a ZeroTier virtual network
public void JoinNetwork(string nwid)
{
zt_join_network(nwid);
}
// Leaves a ZeroTier virtual network
public void LeaveNetwork(string nwid)
{
zt_leave_network(nwid);
}
#endregion
// Low-level representations of ZeroTier sockets
// The ZeroTier LLAPI is built on top of these
// Creates a new ZeroTier-administered socket
public int Socket(int family, int type, int protocol)
{
return zt_socket (family, type, protocol);
}
// Binds to a specific address
public int Bind(int fd, string addr, int port)
{
GCHandle sockaddr_ptr = ZeroTierUtils.Generate_unmananged_sockaddr(addr + ":" + port);
IntPtr pSockAddr = sockaddr_ptr.AddrOfPinnedObject ();
int addrlen = Marshal.SizeOf (pSockAddr);
return zt_bind (fd, pSockAddr, addrlen);
}
// Listens for an incoming connection request
public int Listen(int fd, int backlog)
{
return zt_listen(fd, backlog);
}
// Accepts an incoming connection
public int Accept(int fd)
{
return zt_accept (fd);
}
// Closes a connection
public int Close(int fd)
{
return Close (fd);
}
// Connects to a remote host
public int Connect(int fd, string addr, int port)
{
GCHandle sockaddr_ptr = ZeroTierUtils.Generate_unmananged_sockaddr(addr + ":" + port);
IntPtr pSockAddr = sockaddr_ptr.AddrOfPinnedObject ();
int addrlen = Marshal.SizeOf (pSockAddr);
return zt_connect (fd, pSockAddr, addrlen);
}
public int Read(int fd, ref char[] buf, int len)
{
GCHandle handle = GCHandle.Alloc(buf, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
int bytes_read = zt_recv (fd, ptr, len*2);
string str = Marshal.PtrToStringAuto(ptr);
//Marshal.Copy (ptr, buf, 0, bytes_read);
buf = Marshal.PtrToStringAnsi(ptr).ToCharArray();
return bytes_read;
}
public int Write(int fd, char[] buf, int len)
{
GCHandle handle = GCHandle.Alloc(buf, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
//error = 0;
int bytes_written;
// FIXME: Sending a length of 2X the buffer size seems to fix the object pinning issue
if((bytes_written = zt_send(fd, ptr, len*2)) < 0) {
//error = (byte)bytes_written;
}
return bytes_written;
}
#region Service-Related calls
// Returns whether the ZeroTier service is currently running
public bool IsRunning()
{
return zt_is_running ();
}
// Terminates the ZeroTier service
public void Terminate()
{
zt_terminate ();
}
#endregion
}

View File

@@ -77,7 +77,6 @@ public class ZeroTierSockets_Demo : MonoBehaviour
Debug.Log ("Connecting to: " + addr.text + ":" + port.text); Debug.Log ("Connecting to: " + addr.text + ":" + port.text);
Thread connectThread = new Thread(() => { Thread connectThread = new Thread(() => {
int sockfd = zt.Socket ((int)AddressFamily.InterNetwork, (int)SocketType.Stream, (int)ProtocolType.Unspecified); int sockfd = zt.Socket ((int)AddressFamily.InterNetwork, (int)SocketType.Stream, (int)ProtocolType.Unspecified);
Debug.Log ("sockfd = " + sockfd); Debug.Log ("sockfd = " + sockfd);
int port_num; int port_num;
@@ -223,19 +222,19 @@ public class ZeroTierSockets_Demo : MonoBehaviour
GameObject go; GameObject go;
go = GameObject.Find ("inputNetworkID"); go = GameObject.Find ("inputNetworkID");
input = go.GetComponents<InputField> () [0]; input = go.GetComponents<InputField> () [0];
input.text = "565799d8f6e1c11a"; input.text = "565799d8f65063e5";
go = GameObject.Find ("inputServerAddress"); go = GameObject.Find ("inputServerAddress");
input = go.GetComponents<InputField> () [0]; input = go.GetComponents<InputField> () [0];
input.text = "172.22.211.245"; input.text = "10.9.9.203";
go = GameObject.Find ("inputServerPort"); go = GameObject.Find ("inputServerPort");
input = go.GetComponents<InputField> () [0]; input = go.GetComponents<InputField> () [0];
input.text = "5555"; input.text = "8080";
go = GameObject.Find ("inputMessage"); go = GameObject.Find ("inputMessage");
input = go.GetComponents<InputField> () [0]; input = go.GetComponents<InputField> () [0];
input.text = "Welcome to the machine"; input.text = "Welcome to the machine";
// Create new instance of ZeroTier in separate thread // Create new instance of ZeroTier in separate thread
zt = new ZeroTierNetworkInterface (); zt = new ZeroTierNetworkInterface ("/Users/Joseph/utest3", "565799d8f65063e5");
} }
// Terminate the ZeroTier service when the application quits // Terminate the ZeroTier service when the application quits

View File

@@ -0,0 +1,29 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2008
Project("{0BF2C6BC-4121-AE75-A3F9-F3A441421429}") = "Unity3D", "Assembly-CSharp.csproj", "{7214E491-EE9D-B906-A42D-2F3EA3DCD8FE}"
EndProject
Project("{0BF2C6BC-4121-AE75-A3F9-F3A441421429}") = "Unity3D", "Assembly-CSharp-Editor.csproj", "{CCA76E42-E9D5-4CBF-3222-F488C499DCF3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7214E491-EE9D-B906-A42D-2F3EA3DCD8FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7214E491-EE9D-B906-A42D-2F3EA3DCD8FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7214E491-EE9D-B906-A42D-2F3EA3DCD8FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7214E491-EE9D-B906-A42D-2F3EA3DCD8FE}.Release|Any CPU.Build.0 = Release|Any CPU
{CCA76E42-E9D5-4CBF-3222-F488C499DCF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CCA76E42-E9D5-4CBF-3222-F488C499DCF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CCA76E42-E9D5-4CBF-3222-F488C499DCF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CCA76E42-E9D5-4CBF-3222-F488C499DCF3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = Assembly-CSharp.csproj
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,17 @@
<Properties StartupItem="Assembly-CSharp.csproj">
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" PreferredExecutionTarget="Unity.Instance.Unity Editor" />
<MonoDevelop.Ide.Workbench ActiveDocument="Assets/ZeroTierNetworkInterface.cs">
<Files>
<File FileName="Assets/ZeroTierNetworkInterface.cs" Line="52" Column="1" />
<File FileName="Assets/ZeroTierSockets_Demo.cs" Line="213" Column="51" />
<File FileName="Assets/Demo.cs" Line="1" Column="1" />
<File FileName="Assets/MyZeroTier.cs" Line="1" Column="1" />
<File FileName="Assets/WorldMain.cs" Line="1" Column="1" />
<File FileName="Assets/ZeroTier.cs" Line="1" Column="1" />
</Files>
</MonoDevelop.Ide.Workbench>
<MonoDevelop.Ide.DebuggingService.Breakpoints>
<BreakpointStore />
</MonoDevelop.Ide.DebuggingService.Breakpoints>
<MonoDevelop.Ide.DebuggingService.PinnedWatches />
</Properties>

View File

@@ -1379,6 +1379,7 @@
"-D__UNITY_3D__", "-D__UNITY_3D__",
"-DSDK", "-DSDK",
"-DSDK_DEBUG", "-DSDK_DEBUG",
"-DUSE_SOCKS_PROXY",
); );
PRODUCT_BUNDLE_IDENTIFIER = "zerotier.ZeroTierSDK-Unity3D-iOS"; PRODUCT_BUNDLE_IDENTIFIER = "zerotier.ZeroTierSDK-Unity3D-iOS";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
@@ -1403,6 +1404,7 @@
OTHER_CFLAGS = ( OTHER_CFLAGS = (
"-D__UNITY_3D__", "-D__UNITY_3D__",
"-DSDK", "-DSDK",
"-DUSE_SOCKS_PROXY",
); );
PRODUCT_BUNDLE_IDENTIFIER = "zerotier.ZeroTierSDK-Unity3D-iOS"; PRODUCT_BUNDLE_IDENTIFIER = "zerotier.ZeroTierSDK-Unity3D-iOS";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
@@ -1560,6 +1562,8 @@
"-DSDK_DEBUG", "-DSDK_DEBUG",
"-DSDK", "-DSDK",
"-D__UNITY_3D__", "-D__UNITY_3D__",
"-DUSE_SOCKS_PROXY",
"-DSDK_BUNDLED",
); );
PRODUCT_BUNDLE_IDENTIFIER = "zerotier.ZeroTierSDK-Unity3D-OSX"; PRODUCT_BUNDLE_IDENTIFIER = "zerotier.ZeroTierSDK-Unity3D-OSX";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
@@ -1582,7 +1586,9 @@
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
OTHER_CFLAGS = ( OTHER_CFLAGS = (
"-DSDK", "-DSDK",
"-DUSE_SOCKS_PROXY",
"-D__UNITY_3D__", "-D__UNITY_3D__",
"-DSDK_BUNDLED",
); );
PRODUCT_BUNDLE_IDENTIFIER = "zerotier.ZeroTierSDK-Unity3D-OSX"; PRODUCT_BUNDLE_IDENTIFIER = "zerotier.ZeroTierSDK-Unity3D-OSX";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";

View File

@@ -148,6 +148,7 @@ tests: $(TEST_OBJDIR) $(TEST_TARGETS)
clean: clean:
-rm -rf $(BUILD)/* -rm -rf $(BUILD)/*
-rm -rf $(INT)/Unity3D/Assets/Plugins/*
-rm -rf zerotier-cli zerotier-idtool -rm -rf zerotier-cli zerotier-idtool
-find . -type f \( -name 'zerotier-one' -o -name 'zerotier-sdk-service' \) -delete -find . -type f \( -name 'zerotier-one' -o -name 'zerotier-sdk-service' \) -delete
-find . -type f \( -name '*.o' -o -name '*.so' -o -name '*.o.d' -o -name '*.out' -o -name '*.log' \) -delete -find . -type f \( -name '*.o' -o -name '*.so' -o -name '*.o.d' -o -name '*.out' -o -name '*.log' \) -delete

View File

@@ -78,6 +78,9 @@ ios_app_framework:
osx_unity3d_bundle: osx_unity3d_bundle:
cd $(INT)/apple/ZeroTierSDK_Apple; xcodebuild -scheme ZeroTierSDK_Unity3D_OSX build SYMROOT="../../../$(BUILD)/osx_unity3d_bundle" cd $(INT)/apple/ZeroTierSDK_Apple; xcodebuild -scheme ZeroTierSDK_Unity3D_OSX build SYMROOT="../../../$(BUILD)/osx_unity3d_bundle"
cp docs/osx_unity3d_zt_sdk.md $(BUILD)/osx_unity3d_bundle/README.md cp docs/osx_unity3d_zt_sdk.md $(BUILD)/osx_unity3d_bundle/README.md
chmod 755 $(BUILD)/osx_unity3d_bundle/Debug/ZeroTierSDK_Unity3D_OSX.bundle
cp -p -R $(BUILD)/osx_unity3d_bundle/Debug/ZeroTierSDK_Unity3D_OSX.bundle $(INT)/Unity3D/Assets/Plugins
ios_unity3d_bundle: ios_unity3d_bundle:
cd $(INT)/apple/ZeroTierSDK_Apple; xcodebuild -scheme ZeroTierSDK_Unity3D_iOS build SYMROOT="../../../$(BUILD)/ios_unity3d_bundle" cd $(INT)/apple/ZeroTierSDK_Apple; xcodebuild -scheme ZeroTierSDK_Unity3D_iOS build SYMROOT="../../../$(BUILD)/ios_unity3d_bundle"
cp docs/ios_unity3d_zt_sdk.md $(BUILD)/ios_unity3d_bundle/README.md cp docs/ios_unity3d_zt_sdk.md $(BUILD)/ios_unity3d_bundle/README.md
@@ -147,6 +150,7 @@ JAVAC := $(shell which javac)
clean: clean:
-rm -rf $(BUILD)/* -rm -rf $(BUILD)/*
-rm -rf $(INT)/Unity3D/Assets/Plugins/*
-rm -rf zerotier-cli zerotier-idtool -rm -rf zerotier-cli zerotier-idtool
-find . -type f \( -name 'zerotier-one' -o -name 'zerotier-sdk-service' \) -delete -find . -type f \( -name 'zerotier-one' -o -name 'zerotier-sdk-service' \) -delete
-find . -type f \( -name '*.o' -o -name '*.so' -o -name '*.o.d' -o -name '*.out' -o -name '*.log' \) -delete -find . -type f \( -name '*.o' -o -name '*.so' -o -name '*.o.d' -o -name '*.out' -o -name '*.log' \) -delete

View File

@@ -98,20 +98,20 @@ void dwr(int level, const char *fmt, ... )
#elif defined(__APPLE__) #elif defined(__APPLE__)
pid_t tid = pthread_mach_thread_np(pthread_self()); pid_t tid = pthread_mach_thread_np(pthread_self());
#endif #endif
#if defined(SDK_DEBUG_LOG_TO_FILE) //#if defined(SDK_DEBUG_LOG_TO_FILE)
if(!debug_logfile) { // Try to get logfile from env //if(!debug_logfile) { // Try to get logfile from env
debug_logfile = getenv("ZT_SDK_LOGFILE"); // debug_logfile = getenv("ZT_SDK_LOGFILE");
} //}
/*
if(debug_logfile) { //if(debug_logfile) {
FILE *file = fopen(debug_logfile,"a"); FILE *file = fopen("/Users/Joseph/code/unity.log","a");
fprintf(file, "%s [tid=%7d] ", timestring, tid); fprintf(file, "%s [tid=%7d] ", timestring, tid);
vfprintf(file, fmt, ap); vfprintf(file, fmt, ap);
fclose(file); fclose(file);
va_end(ap); va_end(ap);
} //}
*/
#endif //#endif
va_start(ap, fmt); va_start(ap, fmt);
fprintf(stderr, "%s [tid=%7d] ", timestring, tid); fprintf(stderr, "%s [tid=%7d] ", timestring, tid);
vfprintf(stderr, fmt, ap); vfprintf(stderr, fmt, ap);

View File

@@ -74,15 +74,22 @@ void zt_init_rpc(const char * path, const char * nwid);
// .NET Interop-friendly debug mechanism // .NET Interop-friendly debug mechanism
typedef void (*FuncPtr)( const char * ); typedef void (*FuncPtr)( const char * );
FuncPtr Debug; FuncPtr Debug;
void SetDebugFunction( FuncPtr fp ) { Debug = fp; } void SetDebugFunction( FuncPtr fp ) { Debug = fp; }
// Starts a service at the specified path // Starts a ZeroTier service at the given path
void unity_start_service(char * path, int len) { void unity_start_service(char * path, int len) {
Debug(path); std::string dstr = std::string(path);
zt_init_rpc(path,""); dstr = "unity_start_service(): path = " + dstr;
Debug(dstr.c_str());
init_service(INTERCEPT_DISABLED, path); init_service(INTERCEPT_DISABLED, path);
} }
// Starts a ZeroTier service and RPC
void unity_start_service_and_rpc(char * path, char *nwid, int len) {
std::string dstr = std::string(path);
dstr = "unity_start_service_and_rpc(): path = " + dstr;
Debug(dstr.c_str());
init_service_and_rpc(INTERCEPT_DISABLED, path, nwid);
}
#endif #endif
void join_network(const char * nwid) void join_network(const char * nwid)
@@ -100,13 +107,13 @@ void zt_init_rpc(const char * path, const char * nwid);
} }
void leave_network(const char *nwid) { zt1Service->leave(nwid); } void leave_network(const char *nwid) { zt1Service->leave(nwid); }
void zt_join_network(const char * nwid) { join_network(nwid); } void zt_join_network(const char * nwid) { join_network(nwid); }
void zt_leave_network(const char * nwid) { leave_network(nwid); } void zt_leave_network(const char * nwid) { leave_network(nwid); }
bool zt_is_running() { return zt1Service->isRunning(); } bool zt_is_running() { return zt1Service->isRunning(); }
void zt_terminate() { zt1Service->terminate(); } void zt_terminate() { zt1Service->terminate(); }
// Android JNI wrapper
#if defined(__ANDROID__) #if defined(__ANDROID__)
// JNI naming convention: Java_PACKAGENAME_CLASSNAME_METHODNAME // JNI naming convention: Java_PACKAGENAME_CLASSNAME_METHODNAME
JNIEXPORT void JNICALL Java_ZeroTier_SDK_joinNetwork(JNIEnv *env, jobject thisObj, jstring nwid) { JNIEXPORT void JNICALL Java_ZeroTier_SDK_joinNetwork(JNIEnv *env, jobject thisObj, jstring nwid) {
@@ -136,12 +143,10 @@ void zt_init_rpc(const char * path, const char * nwid);
if(zt1Service) if(zt1Service)
zt1Service->terminate(); zt1Service->terminate();
} }
#endif #endif
// Typically used on iOS/OSX
#if !defined(__ANDROID__) #if !defined(__ANDROID__)
/* /*
* Starts a service thread and performs basic setup tasks * Starts a service thread and performs basic setup tasks
@@ -153,13 +158,11 @@ void zt_init_rpc(const char * path, const char * nwid);
*intercept_thread_id = key; *intercept_thread_id = key;
pthread_create(&intercept_thread, NULL, startOneService, (void *)(intercept_thread_id)); pthread_create(&intercept_thread, NULL, startOneService, (void *)(intercept_thread_id));
} }
void init_service_and_rpc(int key, const char * path, const char * nwid) { void init_service_and_rpc(int key, const char * path, const char * nwid) {
rpcEnabled = true; rpcEnabled = true;
rpcNWID = nwid; rpcNWID = nwid;
init_service(key, path); init_service(key, path);
} }
/* /*
* Enables or disables intercept for current thread using key in thread-local storage * Enables or disables intercept for current thread using key in thread-local storage
*/ */
@@ -172,9 +175,6 @@ void zt_init_rpc(const char * path, const char * nwid);
} }
#endif #endif
/* /*
* Starts a new service instance * Starts a new service instance
*/ */
@@ -193,21 +193,12 @@ void zt_init_rpc(const char * path, const char * nwid);
set_intercept_status(INTERCEPT_DISABLED); set_intercept_status(INTERCEPT_DISABLED);
#endif #endif
// If no homeDir is provided, attempt a best guess of an appropriate ZeroTier
// homeDir according to platform and build type
if(!homeDir.length())
{
#if defined(__UNITY_3D__) && !defined(__ANDROID__) && !defined(__IOS__)
// Unity3D on a non-mobile platform
homeDir = current_dir; // homeDir shall be current dir
#endif
}
#if defined(__UNITY_3D__) #if defined(__UNITY_3D__)
int MAX_DIR_SZ = 256; int MAX_DIR_SZ = 256;
char current_dir[MAX_DIR_SZ]; char current_dir[MAX_DIR_SZ];
getcwd(current_dir, MAX_DIR_SZ); getcwd(current_dir, MAX_DIR_SZ);
chdir(service_path.c_str()); chdir(service_path.c_str());
homeDir = current_dir; // homeDir shall be current dir
#endif #endif
#if defined(__APPLE__) #if defined(__APPLE__)
@@ -276,7 +267,7 @@ void zt_init_rpc(const char * path, const char * nwid);
#endif #endif
//chdir(current_dir); // Return to previous current working directory (at the request of Unity3D) //chdir(current_dir); // Return to previous current working directory (at the request of Unity3D)
//Debug(homeDir.c_str()); Debug("Starting service...\n");
// Initialize RPC // Initialize RPC
if(rpcEnabled) { if(rpcEnabled) {

View File

@@ -42,7 +42,6 @@ extern "C" {
#define INTERCEPT_ENABLED 111 #define INTERCEPT_ENABLED 111
#define INTERCEPT_DISABLED 222 #define INTERCEPT_DISABLED 222
extern std::string homeDir; extern std::string homeDir;
#if defined(__ANDROID__) #if defined(__ANDROID__)

View File

@@ -119,6 +119,7 @@ int (*realclose)(CLOSE_SIG);
} }
#endif #endif
} }
dwr(MSG_DEBUG, "zt_init_rpc(): api_netpath = %s\n", api_netpath);
} }
void get_api_netpath() { zt_init_rpc("",""); } void get_api_netpath() { zt_init_rpc("",""); }