diff --git a/DesktopEdge/MainMenu.xaml.cs b/DesktopEdge/MainMenu.xaml.cs index 11a89570..1a28ca91 100644 --- a/DesktopEdge/MainMenu.xaml.cs +++ b/DesktopEdge/MainMenu.xaml.cs @@ -115,9 +115,10 @@ namespace ZitiDesktopEdge _downloadUrl = asset.Property("browser_download_url").Value.ToString(); break; } - } catch + } catch(Exception ex) { UpdateAvailable.Content = "An exception occurred while performing upgrade check"; + Debug.WriteLine("Error when checking for version: " + ex.Message); UpdateAvailable.Visibility = Visibility.Visible; } } diff --git a/DesktopEdge/MainWindow.xaml.cs b/DesktopEdge/MainWindow.xaml.cs index f6cc685d..229cb535 100644 --- a/DesktopEdge/MainWindow.xaml.cs +++ b/DesktopEdge/MainWindow.xaml.cs @@ -3,14 +3,14 @@ using System.Collections.Generic; using System.Windows; using System.Windows.Input; using System.IO; -using ZitiDesktopEdge.Models; -using ZitiDesktopEdge.ServiceClient; using System.ServiceProcess; using System.Linq; using System.Diagnostics; using System.Windows.Controls; using System.Drawing; +using ZitiDesktopEdge.Models; +using ZitiDesktopEdge.ServiceClient; namespace ZitiDesktopEdge { @@ -28,10 +28,9 @@ namespace ZitiDesktopEdge { private bool _isServiceInError = false; private int _right = 75; private int _left = 75; - private int _bottom = 0; private int _top = 30; private double _maxHeight = 800d; - private string[] suffixes = { "bps", "kbps", "mbps", "gbps", "tbps", "pbps" }; + private string[] suffixes = { "Bps", "kBps", "mBps", "gBps", "tBps", "pBps" }; private List identities { get { diff --git a/DesktopEdge/WinAPI.cs b/DesktopEdge/WinAPI.cs index 234bcf4e..942d4084 100644 --- a/DesktopEdge/WinAPI.cs +++ b/DesktopEdge/WinAPI.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using System; using System.Runtime.InteropServices; using System.Drawing; using System.ComponentModel; diff --git a/DesktopEdge/ZitiDesktopEdge.csproj b/DesktopEdge/ZitiDesktopEdge.csproj index 24f18ae0..88fec2a3 100644 --- a/DesktopEdge/ZitiDesktopEdge.csproj +++ b/DesktopEdge/ZitiDesktopEdge.csproj @@ -1,368 +1,372 @@ - - - - - Debug - AnyCPU - {FA4291EA-A97E-4854-959F-91EE7B330B37} - WinExe - Ziti.Desktop.Edge - ZitiDesktopEdge - v4.8 - 512 - {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 4 - true - true - - false - 1.0.0.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - https://support.netfoundry.io - en-US - Ziti Desktop Edge - NetFoundry - Ziti - true - 0 - 1.2.8.%2a - false - true - true - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - x64 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - app.manifest - - - 189AAD422A106DC81E8E79C7E0D2118CEB2E6321 - - - - - - - true - - - true - - - LocalIntranet - - - bin\Releases\ - - - ziti.ico - - - - ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll - - - - - - - - - ..\packages\System.Management.Automation.dll.10.0.10586.0\lib\net40\System.Management.Automation.dll - - - - - ..\packages\System.Net.NetworkInformation.4.3.0\lib\net46\System.Net.NetworkInformation.dll - True - True - - - - - - - - - - - - 4.0 - - - - - - - - MSBuild:Compile - Designer - - - ControllerScreen.xaml - - - IdentityDetails.xaml - - - MainMenu.xaml - - - - - ServiceInfo.xaml - - - MenuEditItem.xaml - - - - - RegistrationScreen.xaml - - - SubOptionItem.xaml - - - SubMenuItem.xaml - - - MenuItem.xaml - - - - - Toggler.xaml - - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - App.xaml - Code - - - IdentityItem.xaml - - - MainWindow.xaml - Code - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - Designer - MSBuild:Compile - - - MSBuild:Compile - Designer - - - Designer - MSBuild:Compile - - - - - Code - - - True - True - Resources.resx - - - True - Settings.settings - True - - - ResXFileCodeGenerator - Resources.Designer.cs - - - - - Always - - - Always - - - .editorconfig - - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Always - - - - - - False - Microsoft .NET Framework 4.8 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 - false - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + AnyCPU + {FA4291EA-A97E-4854-959F-91EE7B330B37} + WinExe + Ziti.Desktop.Edge + ZitiDesktopEdge + v4.8 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + true + + false + 1.0.0.0 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + https://support.netfoundry.io + en-US + Ziti Desktop Edge + NetFoundry + Ziti + true + 0 + 1.2.8.%2a + false + true + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + x64 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + app.manifest + + + 189AAD422A106DC81E8E79C7E0D2118CEB2E6321 + + + + + + + true + + + true + + + LocalIntranet + + + bin\Releases\ + + + ziti.ico + + + + ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + + + + + + + + + ..\packages\System.Management.Automation.dll.10.0.10586.0\lib\net40\System.Management.Automation.dll + + + + + ..\packages\System.Net.NetworkInformation.4.3.0\lib\net46\System.Net.NetworkInformation.dll + True + True + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + ControllerScreen.xaml + + + IdentityDetails.xaml + + + MainMenu.xaml + + + + + ServiceInfo.xaml + + + MenuEditItem.xaml + + + RegistrationScreen.xaml + + + SubOptionItem.xaml + + + SubMenuItem.xaml + + + MenuItem.xaml + + + + + Toggler.xaml + + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + IdentityItem.xaml + + + MainWindow.xaml + Code + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + Always + + + Always + + + .editorconfig + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Always + + + + + + False + Microsoft .NET Framework 4.8 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 + false + + + + + + + + + + + + + + + + + + + + + + + + {26b30979-99b5-4102-bd0b-129bedff0057} + ZitiDesktopEdge.Client + + + \ No newline at end of file diff --git a/Installer/ZitiDesktopEdge.aip b/Installer/ZitiDesktopEdge.aip index ca6b7e45..20c3834b 100644 --- a/Installer/ZitiDesktopEdge.aip +++ b/Installer/ZitiDesktopEdge.aip @@ -8,7 +8,6 @@ - @@ -22,10 +21,12 @@ + + @@ -48,10 +49,12 @@ - + + + @@ -66,7 +69,6 @@ - @@ -78,9 +80,10 @@ + + - @@ -211,6 +214,8 @@ + + @@ -265,11 +270,11 @@ - + - + diff --git a/Installer/build.ps1 b/Installer/build.ps1 index 907ae717..ee1b20ce 100644 --- a/Installer/build.ps1 +++ b/Installer/build.ps1 @@ -52,8 +52,15 @@ if($gituser -eq "ziti-ci") { } else { echo "detected ziti-ci - but no gh_deploy_key. push may fail" } - git commit -m "[ci skip] committing updated installer file" 2>&1 - git push 2>&1 + + $b="$env:GIT_BRANCH" + if( $b -match '(^master$|^release-[0-9]*\.[0-9]*\.[0-9]*)' ) { + echo "branch $b matches the required regex - committing and pushing" + git commit -m "[ci skip] committing updated installer file" 2>&1 + git push 2>&1 + } else { + echo "branch $b does not match the regex. no commit/no push" + } } else { echo "detected user [${gituser}] which is not ziti-ci - skipping installer commit" } diff --git a/ZitiDesktopEdge.Client/Properties/AssemblyInfo.cs b/ZitiDesktopEdge.Client/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..d538897f --- /dev/null +++ b/ZitiDesktopEdge.Client/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ZitiDesktopEdge.Client")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ZitiDesktopEdge.Client")] +[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("26b30979-99b5-4102-bd0b-129bedff0057")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DesktopEdge/ServiceClient/ClientImpl.cs b/ZitiDesktopEdge.Client/ServiceClient/ClientImpl.cs similarity index 90% rename from DesktopEdge/ServiceClient/ClientImpl.cs rename to ZitiDesktopEdge.Client/ServiceClient/ClientImpl.cs index d71b8bde..d2266d11 100644 --- a/DesktopEdge/ServiceClient/ClientImpl.cs +++ b/ZitiDesktopEdge.Client/ServiceClient/ClientImpl.cs @@ -9,9 +9,6 @@ using System.Security.AccessControl; using Newtonsoft.Json; using System.Threading; using System.Threading.Tasks; -using System.Runtime.Remoting.Contexts; -using System.Windows.Interop; -using System.Windows.Documents; /// /// The implementation will abstract away the setup of the communication to @@ -35,7 +32,7 @@ namespace ZitiDesktopEdge.ServiceClient VERBOSE = 6, } - internal class Client + public class Client { public const int EXPECTED_API_VERSION = 1; @@ -46,63 +43,48 @@ namespace ZitiDesktopEdge.ServiceClient public event EventHandler OnServiceEvent; public event EventHandler OnClientConnected; public event EventHandler OnClientDisconnected; + public event EventHandler OnShutdownEvent; + + public bool CleanShutdown { get; set; } + + protected virtual void ShutdownEvent(StatusEvent e) { + CleanShutdown = true; + OnShutdownEvent?.Invoke(this, e); + } protected virtual void TunnelStatusEvent(TunnelStatusEvent e) { - EventHandler handler = OnTunnelStatusEvent; - if (handler != null) - { - handler(this, e); - } + OnTunnelStatusEvent?.Invoke(this, e); } protected virtual void MetricsEvent(List e) { - EventHandler> handler = OnMetricsEvent; - if (handler != null) - { - handler(this, e); - } + OnMetricsEvent?.Invoke(this, e); } protected virtual void IdentityEvent(IdentityEvent e) { - EventHandler handler = OnIdentityEvent; - if (handler != null) - { - handler(this, e); - } + OnIdentityEvent?.Invoke(this, e); } protected virtual void ServiceEvent(ServiceEvent e) { - EventHandler handler = OnServiceEvent; - if (handler != null) - { - handler(this, e); - } + OnServiceEvent?.Invoke(this, e); } protected virtual void ClientConnected(object e) { Connected = true; - this.Reconnecting = false; - EventHandler handler = OnClientConnected; - if (handler != null) - { - handler(this, e); - } + Reconnecting = false; + CleanShutdown = true; + OnClientConnected?.Invoke(this, e); } protected virtual void ClientDisconnected(object e) { Reconnect(); Connected = false; - EventHandler handler = OnClientDisconnected; - if (handler != null) - { - handler(this, e); - } + OnClientDisconnected?.Invoke(this, e); } JsonSerializer serializer = new JsonSerializer(); @@ -121,7 +103,7 @@ namespace ZitiDesktopEdge.ServiceClient NamedPipeClientStream eventClient = null; #if DEBUG - bool _extendedDebug = true; //set this to true if you need to diagnose issues with the service comms + bool _extendedDebug = false; //set ZITI_EXTENDED_DEBUG env var to true if you want to diagnose issues with the service comms #else bool _extendedDebug = false; #endif @@ -156,6 +138,12 @@ namespace ZitiDesktopEdge.ServiceClient setupPipe(); } + public void WaitForConnection() { + while(Reconnecting || !Connected) { + Task.Delay(100).Wait(); + } + } + public void Reconnect() { if (Reconnecting) @@ -183,7 +171,7 @@ namespace ZitiDesktopEdge.ServiceClient if (Connected) { Debug.WriteLine("Connected to the service - exiting reconect loop"); - this.Connected = true; + Connected = true; Reconnecting = false; return; } @@ -192,10 +180,8 @@ namespace ZitiDesktopEdge.ServiceClient //ClientDisconnected(null); } } - catch - { - //fire the event and just try it all over.... - //ClientDisconnected(null); + catch (Exception ex) { + Debug.WriteLine("Service error: " + ex.Message); } Debug.WriteLine("Reconnect failed. Trying again..."); } @@ -344,11 +330,11 @@ namespace ZitiDesktopEdge.ServiceClient private void checkConnected() { - if (this.Reconnecting) + if (Reconnecting) { throw new ServiceException("Client is not connected", 2, "Cannot use the client at this time, it is reconnecting"); } - if (!this.Connected) + if (!Connected) { throw new ServiceException("Client is not connected", 2, "Cannot use the client at this time, it is not connected"); } @@ -500,9 +486,6 @@ namespace ZitiDesktopEdge.ServiceClient try { string respAsString = readMessage(reader); - debugServiceCommunication("----------------------------------------------------------------------"); - debugServiceCommunication(respAsString); - debugServiceCommunication("----------------------------------------------------------------------"); StatusEvent evt = (StatusEvent)serializer.Deserialize(new StringReader(respAsString), typeof(StatusEvent)); switch (evt.Op) @@ -512,7 +495,7 @@ namespace ZitiDesktopEdge.ServiceClient if (m != null) { - this.MetricsEvent(m.Identities); + MetricsEvent(m.Identities); } break; case "status": @@ -520,7 +503,7 @@ namespace ZitiDesktopEdge.ServiceClient if (se != null) { - this.TunnelStatusEvent(se); + TunnelStatusEvent(se); } break; case "identity": @@ -528,7 +511,7 @@ namespace ZitiDesktopEdge.ServiceClient if (id != null) { - this.IdentityEvent(id); + IdentityEvent(id); } break; case "service": @@ -536,8 +519,11 @@ namespace ZitiDesktopEdge.ServiceClient if (svc != null) { - this.ServiceEvent(svc); + ServiceEvent(svc); } + break; + case "shutdown": + break; default: Debug.WriteLine("unexpected operation! " + evt.Op); diff --git a/DesktopEdge/ServiceClient/DataStructures.cs b/ZitiDesktopEdge.Client/ServiceClient/DataStructures.cs similarity index 89% rename from DesktopEdge/ServiceClient/DataStructures.cs rename to ZitiDesktopEdge.Client/ServiceClient/DataStructures.cs index fe426aaa..bc2b7e1a 100644 --- a/DesktopEdge/ServiceClient/DataStructures.cs +++ b/ZitiDesktopEdge.Client/ServiceClient/DataStructures.cs @@ -7,7 +7,7 @@ using System.Collections.Generic; /// namespace ZitiDesktopEdge.ServiceClient { - class SvcResponse + public class SvcResponse { public int Code { get; set; } public string Message { get; set; } @@ -19,12 +19,12 @@ namespace ZitiDesktopEdge.ServiceClient } } - class StatusUpdateResponse : SvcResponse + public class StatusUpdateResponse : SvcResponse { public StatusUpdate Payload { get; set; } } - class StatusUpdate + public class StatusUpdate { public string Operation { get; set; } public TunnelStatus Status { get; set; } @@ -38,7 +38,7 @@ namespace ZitiDesktopEdge.ServiceClient public Identity Id { get; set; } } - class IdentityResponse : SvcResponse + public class IdentityResponse : SvcResponse { public Identity Payload { get; set; } } @@ -158,7 +158,7 @@ namespace ZitiDesktopEdge.ServiceClient public string AdditionalCAs { get; set; } } - class IpInfo + public class IpInfo { public string Ip { get; set; } public string Subnet { get; set; } @@ -166,7 +166,7 @@ namespace ZitiDesktopEdge.ServiceClient public string DNS { get; set; } } - class ServiceVersion + public class ServiceVersion { public string Version { get; set; } public string Revision { get; set; } @@ -178,12 +178,12 @@ namespace ZitiDesktopEdge.ServiceClient } } - class ZitiTunnelStatus : SvcResponse + public class ZitiTunnelStatus : SvcResponse { public TunnelStatus Status { get; set; } } - class TunnelStatus + public class TunnelStatus { public bool Active { get; set; } @@ -251,34 +251,34 @@ namespace ZitiDesktopEdge.ServiceClient public string AdditionalInfo { get; } } - class StatusEvent + public class StatusEvent { public string Op { get; set; } } - class ActionEvent : StatusEvent + public class ActionEvent : StatusEvent { public string Action { get; set; } } - class TunnelStatusEvent : StatusEvent + public class TunnelStatusEvent : StatusEvent { public TunnelStatus Status { get; set; } public int ApiVersion { get; set; } } - class MetricsEvent : StatusEvent + public class MetricsEvent : StatusEvent { public List Identities { get; set; } } - class ServiceEvent : ActionEvent + public class ServiceEvent : ActionEvent { public string Fingerprint { get; set; } public Service Service { get; set; } } - class IdentityEvent : ActionEvent + public class IdentityEvent : ActionEvent { public Identity Id { get; set; } } diff --git a/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj b/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj new file mode 100644 index 00000000..e8c9e326 --- /dev/null +++ b/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj @@ -0,0 +1,56 @@ + + + + + Debug + AnyCPU + {26B30979-99B5-4102-BD0B-129BEDFF0057} + Library + Properties + ZitiDesktopEdge.Client + ZitiDesktopEdge.Client + v4.7.2 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + True + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ZitiDesktopEdge.Client/packages.config b/ZitiDesktopEdge.Client/packages.config new file mode 100644 index 00000000..32637c2e --- /dev/null +++ b/ZitiDesktopEdge.Client/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/ZitiDesktopEdge.sln b/ZitiDesktopEdge.sln index 7ce876dc..3edaa021 100644 --- a/ZitiDesktopEdge.sln +++ b/ZitiDesktopEdge.sln @@ -1,77 +1,99 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29318.209 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D66B1C6A-ADFE-437E-B037-C4C849A6CA97}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - README.md = README.md - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZitiDesktopEdge", "DesktopEdge\ZitiDesktopEdge.csproj", "{FA4291EA-A97E-4854-959F-91EE7B330B37}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZitiUpdateService", "ZitiUpdateService\ZitiUpdateService.csproj", "{9AB81609-F5DD-40A6-87B5-F3279D48514D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM = Debug|ARM - Debug|ARM64 = Debug|ARM64 - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|ARM = Release|ARM - Release|ARM64 = Release|ARM64 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|ARM.ActiveCfg = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|ARM.Build.0 = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|ARM64.ActiveCfg = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|ARM64.Build.0 = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|x64.ActiveCfg = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|x64.Build.0 = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|x86.ActiveCfg = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|x86.Build.0 = Debug|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|Any CPU.Build.0 = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|ARM.ActiveCfg = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|ARM.Build.0 = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|ARM64.ActiveCfg = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|ARM64.Build.0 = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|x64.ActiveCfg = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|x64.Build.0 = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|x86.ActiveCfg = Release|Any CPU - {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|x86.Build.0 = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|ARM.ActiveCfg = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|ARM.Build.0 = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|ARM64.ActiveCfg = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|ARM64.Build.0 = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|x64.ActiveCfg = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|x64.Build.0 = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|x86.ActiveCfg = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|x86.Build.0 = Debug|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|Any CPU.Build.0 = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|ARM.ActiveCfg = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|ARM.Build.0 = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|ARM64.ActiveCfg = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|ARM64.Build.0 = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|x64.ActiveCfg = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|x64.Build.0 = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|x86.ActiveCfg = Release|Any CPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {3E499EAC-C1BA-41A0-8076-D660F8ACC977} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29318.209 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D66B1C6A-ADFE-437E-B037-C4C849A6CA97}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + README.md = README.md + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZitiDesktopEdge", "DesktopEdge\ZitiDesktopEdge.csproj", "{FA4291EA-A97E-4854-959F-91EE7B330B37}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZitiUpdateService", "ZitiUpdateService\ZitiUpdateService.csproj", "{9AB81609-F5DD-40A6-87B5-F3279D48514D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZitiDesktopEdge.Client", "ZitiDesktopEdge.Client\ZitiDesktopEdge.Client.csproj", "{26B30979-99B5-4102-BD0B-129BEDFF0057}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|ARM = Debug|ARM + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|ARM = Release|ARM + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|ARM.ActiveCfg = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|ARM.Build.0 = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|ARM64.Build.0 = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|x64.ActiveCfg = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|x64.Build.0 = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|x86.ActiveCfg = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|x86.Build.0 = Debug|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|Any CPU.Build.0 = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|ARM.ActiveCfg = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|ARM.Build.0 = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|ARM64.ActiveCfg = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|ARM64.Build.0 = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|x64.ActiveCfg = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|x64.Build.0 = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|x86.ActiveCfg = Release|Any CPU + {FA4291EA-A97E-4854-959F-91EE7B330B37}.Release|x86.Build.0 = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|ARM.ActiveCfg = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|ARM.Build.0 = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|ARM64.Build.0 = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|x64.ActiveCfg = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|x64.Build.0 = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|x86.ActiveCfg = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Debug|x86.Build.0 = Debug|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|Any CPU.Build.0 = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|ARM.ActiveCfg = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|ARM.Build.0 = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|ARM64.ActiveCfg = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|ARM64.Build.0 = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|x64.ActiveCfg = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|x64.Build.0 = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|x86.ActiveCfg = Release|Any CPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Release|x86.Build.0 = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|Any CPU.Build.0 = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|ARM.ActiveCfg = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|ARM.Build.0 = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|ARM64.Build.0 = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|x64.ActiveCfg = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|x64.Build.0 = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|x86.ActiveCfg = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Debug|x86.Build.0 = Debug|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|Any CPU.ActiveCfg = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|Any CPU.Build.0 = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|ARM.ActiveCfg = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|ARM.Build.0 = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|ARM64.ActiveCfg = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|ARM64.Build.0 = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|x64.ActiveCfg = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|x64.Build.0 = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|x86.ActiveCfg = Release|Any CPU + {26B30979-99B5-4102-BD0B-129BEDFF0057}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3E499EAC-C1BA-41A0-8076-D660F8ACC977} + EndGlobalSection +EndGlobal diff --git a/ZitiUpdateService/App.config b/ZitiUpdateService/App.config index 2c394ec6..ed981805 100644 --- a/ZitiUpdateService/App.config +++ b/ZitiUpdateService/App.config @@ -1,33 +1,34 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ZitiUpdateService/IUpdateCheck.cs b/ZitiUpdateService/IUpdateCheck.cs new file mode 100644 index 00000000..fb0a472d --- /dev/null +++ b/ZitiUpdateService/IUpdateCheck.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZitiUpdateService { + interface IUpdateCheck { + bool IsUpdateAvailable(Version current); + string FileName(); + void CopyUpdatePackage(string destinationFolder, string destinationName); + + bool AlreadyDownloaded(string destinationFolder, string destinationName); + } +} diff --git a/ZitiUpdateService/NLog.config b/ZitiUpdateService/NLog.config new file mode 100644 index 00000000..4115bea8 --- /dev/null +++ b/ZitiUpdateService/NLog.config @@ -0,0 +1,12 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/ZitiUpdateService/Program.cs b/ZitiUpdateService/Program.cs index 449ad561..6c482650 100644 --- a/ZitiUpdateService/Program.cs +++ b/ZitiUpdateService/Program.cs @@ -1,28 +1,51 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.ServiceProcess; -using System.Text; -using System.Threading.Tasks; - -namespace ZitiUpdateService { - static class Program { - /// - /// The main entry point for the application. - /// - static void Main() { - UpdateService updateSvc = new UpdateService(); -#if DEBUG - updateSvc.Debug(); - System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); -#else - ServiceBase[] ServicesToRun; - ServicesToRun = new ServiceBase[] - { - updateSvc - }; - ServiceBase.Run(ServicesToRun); -#endif - } - } -} +using System; +using System.ServiceProcess; +using NLog; +using NLog.Config; +using NLog.Targets; + +namespace ZitiUpdateService { + static class Program { + private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); + + /// + /// The main entry point for the application. + /// + static void Main() { + //Environment.SetEnvironmentVariable("ZITI_EXTENDED_DEBUG", "true"); + + var config = new LoggingConfiguration(); + var logname = "ziti-montior"; + // Targets where to log to: File and Console + var logfile = new FileTarget("logfile") { + FileName = $"{logname}.log", + ArchiveEvery = FileArchivePeriod.Day, + ArchiveNumbering = ArchiveNumberingMode.Rolling, + MaxArchiveFiles = 7, + //ArchiveAboveSize = 10000, + }; + var logconsole = new ConsoleTarget("logconsole"); + + // Rules for mapping loggers to targets + config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); + config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); + + // Apply config + LogManager.Configuration = config; + + UpdateService updateSvc = new UpdateService(); +#if DEBUG + + updateSvc.Debug(); + System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); +#else + ServiceBase[] ServicesToRun; + ServicesToRun = new ServiceBase[] + { + updateSvc + }; + ServiceBase.Run(ServicesToRun); +#endif + } + } +} diff --git a/ZitiUpdateService/Properties/AssemblyInfo.cs b/ZitiUpdateService/Properties/AssemblyInfo.cs index c0d20486..4f2b14db 100644 --- a/ZitiUpdateService/Properties/AssemblyInfo.cs +++ b/ZitiUpdateService/Properties/AssemblyInfo.cs @@ -1,36 +1,35 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ZitiUpdateService")] -[assembly: AssemblyDescription("Ziti Monitor and Update Service")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("NetFoundry")] -[assembly: AssemblyProduct("ZitiUpdateService")] -[assembly: AssemblyCopyright("Copyright © NetFoundry 2020")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9ab81609-f5dd-40a6-87b5-f3279d48514d")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.3.0.0")] -[assembly: AssemblyFileVersion("1.3.0.0")] +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ziti-monitor")] +[assembly: AssemblyDescription("Ziti Monitor and Update Service")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("NetFoundry")] +[assembly: AssemblyProduct("ZitiUpdateService")] +[assembly: AssemblyCopyright("Copyright © NetFoundry 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9ab81609-f5dd-40a6-87b5-f3279d48514d")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.3.0.0")] +[assembly: AssemblyFileVersion("1.3.0.0")] diff --git a/ZitiUpdateService/ServiceMonitor.cs b/ZitiUpdateService/ServiceMonitor.cs new file mode 100644 index 00000000..8d02bb03 --- /dev/null +++ b/ZitiUpdateService/ServiceMonitor.cs @@ -0,0 +1,27 @@ + +namespace ZitiUpdateService +{ + public class ServiceMonitor + { + public void MonitorSrevice() + { + //a simple method that opens a pipe to the data service and tries to read data + //from the pipe. If the pipe doesn't respond + } + + public void ResetNetwork() + { + + } + + public void ResetRouting() + { + + } + + public void ResetDNS() + { + + } + } +} \ No newline at end of file diff --git a/ZitiUpdateService/ServiceUpdater.cs b/ZitiUpdateService/ServiceUpdater.cs new file mode 100644 index 00000000..4853fccc --- /dev/null +++ b/ZitiUpdateService/ServiceUpdater.cs @@ -0,0 +1,8 @@ + +namespace ZitiUpdateService +{ + public class ServiceUpdater + { + + } +} \ No newline at end of file diff --git a/ZitiUpdateService/UpdateChecker.cs b/ZitiUpdateService/UpdateChecker.cs new file mode 100644 index 00000000..220d0475 --- /dev/null +++ b/ZitiUpdateService/UpdateChecker.cs @@ -0,0 +1,8 @@ + +namespace ZitiUpdateService +{ + public class UpdateChecker + { + + } +} \ No newline at end of file diff --git a/ZitiUpdateService/UpdateCheckers.cs b/ZitiUpdateService/UpdateCheckers.cs new file mode 100644 index 00000000..d478cff9 --- /dev/null +++ b/ZitiUpdateService/UpdateCheckers.cs @@ -0,0 +1,90 @@ +using System; +using System.IO; +using System.Net; + +using NLog; +using Newtonsoft.Json.Linq; + +namespace ZitiUpdateService { + internal class GithubCheck : IUpdateCheck { + private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); + string url; + string downloadUrl = null; + string downloadFileName = null; + + public GithubCheck(string url) { + this.url = url; + } + + public bool AlreadyDownloaded(string destinationFolder, string destinationName) { + return File.Exists(Path.Combine(destinationFolder, destinationName)); + } + + public void CopyUpdatePackage(string destinationFolder, string destinationName) { + WebClient webClient = new WebClient(); + string dest = Path.Combine(destinationFolder, destinationName); + Logger.Info("download started: {0}", downloadUrl); + webClient.DownloadFile(downloadUrl, dest); + Logger.Info("download complete. file at {0}", dest); + } + + public string FileName() { + return downloadFileName; + } + + public bool IsUpdateAvailable(Version current) { + HttpWebRequest httpWebRequest = WebRequest.CreateHttp(url); + httpWebRequest.Method = "GET"; + httpWebRequest.ContentType = "application/json"; + httpWebRequest.UserAgent = "OpenZiti UpdateService"; + HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); + StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()); + string result = streamReader.ReadToEnd(); + JObject json = JObject.Parse(result); + string serverVersion = json.Property("tag_name").Value.ToString() + ".0"; + + Version published = new Version(serverVersion); + int compare = current.CompareTo(published); + if (compare < 0) { + Logger.Info("an upgrade is available."); + } else if (compare > 0) { + Logger.Info("the version installed is newer than the released version"); + return false; + } + JArray assets = JArray.Parse(json.Property("assets").Value.ToString()); + foreach (JObject asset in assets.Children()) { + downloadUrl = asset.Property("browser_download_url").Value.ToString(); + break; + } + + if (downloadUrl == null) { + Logger.Error("DOWNLOAD URL not found at: {0}", url); + return false; + } + downloadFileName = downloadUrl.Substring(downloadUrl.LastIndexOf('/') + 1); + + return true; + } + } + + internal class FilesystemCheck : IUpdateCheck { + private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); + string dest = null; + public bool AlreadyDownloaded(string destinationFolder, string destinationName) { + return File.Exists(Path.Combine(destinationFolder, destinationName)); + } + + public void CopyUpdatePackage(string destinationFolder, string destinationName) { + dest = Path.Combine(destinationFolder, destinationName); + File.Copy(@"C:\git\github\openziti\desktop-edge-win\Installer\Output\" + FileName(), dest); + } + + public string FileName() { + return "Ziti Desktop Edge Client-1.3.0.exe"; + } + + public bool IsUpdateAvailable(Version current) { + return true; + } + } +} diff --git a/ZitiUpdateService/UpdateService.cs b/ZitiUpdateService/UpdateService.cs index 711269fa..2df6928c 100644 --- a/ZitiUpdateService/UpdateService.cs +++ b/ZitiUpdateService/UpdateService.cs @@ -1,258 +1,232 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Diagnostics; -using System.Linq; -using System.ServiceProcess; -using System.Text; -using System.Threading; -using System.IO; -using System.IO.Compression; -using System.Net; -using System.Timers; -using System.Management.Automation; -using System.Xml; -using System.Configuration; -using System.Collections.Specialized; - -namespace ZitiUpdateService { - public partial class UpdateService : ServiceBase { - - private int checkTimerDefault = 60000; - private int updateTimerDefault = 600000; - - private string _version = ""; - private bool _isNew = true; - /// private int _majorVersion = 1; - private string _versionUrl = "https://netfoundry.jfrog.io/netfoundry/ziti-maven-snapshot/ziti-tunnel-win/amd64/windows/ziti-tunnel-win/maven-metadata.xml"; - private string _serviceUrl = "https://netfoundry.jfrog.io/netfoundry/ziti-maven-snapshot/ziti-tunnel-win/amd64/windows/ziti-tunnel-win/${version}/ziti-tunnel-win-${version}.zip"; - private System.Timers.Timer _checkTimer = new System.Timers.Timer(); - private System.Timers.Timer _updateTimer = new System.Timers.Timer(); - private bool inUpdateCheck = false; - private bool inServiceCheck = false; - private string _rootDirectory = ""; - private string _logDirectory = ""; - private bool _isJustStopped = true; - private string _versionType = "latest"; - - ServiceController controller; - public UpdateService() { - InitializeComponent(); - } - - public void Debug() { - OnStart(null); - } - - protected override void OnStart(string[] args) { - try { - if (ConfigurationManager.AppSettings.Get("UpdateUrl") != null) _versionUrl = ConfigurationManager.AppSettings.Get("UpdateUrl"); - if (ConfigurationManager.AppSettings.Get("Version") != null) _versionType = ConfigurationManager.AppSettings.Get("Version"); - } catch (Exception e) { - Log(e.ToString()); - } - _rootDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "OpenZiti"); - if (!Directory.Exists(_rootDirectory)) Directory.CreateDirectory(_rootDirectory); - _logDirectory = Path.Combine(_rootDirectory, "Logs"); - if (!Directory.Exists(_logDirectory)) Directory.CreateDirectory(_logDirectory); - Log("Setup Watchers"); - SetupServiceWatchers(); - } - - protected override void OnStop() { - Log("Stopping update Service"); - } - - private void SetupServiceWatchers() { - Log("Setting Up Watchers"); - - var serviceTimerInterval = ConfigurationManager.AppSettings.Get("ServiceTimer"); - var serviceInt = TimeSpan.Zero; - if (!TimeSpan.TryParse(serviceTimerInterval, out serviceInt)) { - serviceInt = new TimeSpan(0, 1, 0); - } - - var updateTimerInterval = ConfigurationManager.AppSettings.Get("UpdateTimer"); - var upInt = TimeSpan.Zero; - if (!TimeSpan.TryParse(updateTimerInterval, out upInt)) { - upInt = new TimeSpan(0, 1, 0); - } - - Log("Ziti Update Setting Up Watchers"); - - _checkTimer = new System.Timers.Timer(); - _checkTimer.Elapsed += CheckService; - _checkTimer.Interval = serviceInt.TotalMilliseconds; - _checkTimer.Enabled = true; - _checkTimer.Start(); - Log("Service Checker is running"); - - _updateTimer = new System.Timers.Timer(); - _updateTimer.Elapsed += CheckUpdate; - _updateTimer.Interval = upInt.TotalMilliseconds; - _updateTimer.Enabled = true; - _updateTimer.Start(); - Log("Version Checker is running"); - CheckUpdate(null, null); //check immediately - } - - private void CheckUpdate(object sender, ElapsedEventArgs e) { - if (inUpdateCheck) return; - inUpdateCheck = true; //simple semaphone - try { - var request = WebRequest.Create(_versionUrl) as HttpWebRequest; - var response = request.GetResponse(); - Stream receiveStream = response.GetResponseStream(); - StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); - var result = readStream.ReadToEnd(); - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(result); - XmlNode node = xmlDoc.SelectSingleNode("metadata/versioning/" + _versionType); - string version = node.InnerText; - if (version != _version) { - Log("Version Checked: " + version + " on " + _version + " from " + _versionType); - UpdateServiceFiles(version); - } - } catch { - - } - inUpdateCheck = false; - } - - private void CheckService(object sender, ElapsedEventArgs e) { - if (inServiceCheck || inUpdateCheck) return; - inServiceCheck = true; //simple semaphone - try { - controller = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "ziti"); - if (controller == null) return; //means it's not installed or the user doesn't have privs - - if (controller.Status == ServiceControllerStatus.Stopped || controller.Status == ServiceControllerStatus.StopPending) { - if (_isJustStopped) { - _isJustStopped = false; - Log("Ziti Service has been stopped, update Network"); - //should not be necessary in v0.0.10+ RunScript(); - StartZiti(); - } - } else { - if (controller.Status == ServiceControllerStatus.Running) { - _isJustStopped = true; - } - } - } catch { - - } - inServiceCheck = false; - } - - private void UpdateServiceFiles(string currentVersion) { - var request = WebRequest.Create(_versionUrl) as HttpWebRequest; - var response = request.GetResponse(); - Stream receiveStream = response.GetResponseStream(); - StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); - var result = readStream.ReadToEnd(); - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(result); - XmlNode node = xmlDoc.SelectSingleNode("metadata/versioning/"+_versionType); - string version = node.InnerText; - Log("Got Version: " + version+" from "+_versionType); - - if (_version.Trim() == currentVersion.Trim()) { - _version = currentVersion; - Log("Version local is the same as the version remote: " + version); - return; - } - - StopZiti(); - string remoteService = _serviceUrl.Replace("${version}", version); - - if (!Directory.Exists(Path.Combine(_rootDirectory, "Service"))) Directory.CreateDirectory(Path.Combine(_rootDirectory, "Service")); - string[] files = Directory.GetFiles(Path.Combine(_rootDirectory, "Service")); - foreach (string file in files) { - try { - Log("Delete: " + file); - File.Delete(file); - } catch (Exception e) { - EventLog.WriteEntry("Ziti", e.ToString(), EventLogEntryType.Error); - } - } - WebClient webClient = new WebClient(); - Log("Get From: "+remoteService); - webClient.DownloadFile(remoteService, Path.Combine(_rootDirectory, "Service") + @"\windows-tunneler.zip"); - Log("Zip Downloaded"); - ZipFile.ExtractToDirectory(Path.Combine(_rootDirectory, "Service") + @"\windows-tunneler.zip", Path.Combine(_rootDirectory, "Service")); - - Log("Zip UnZipped"); - File.WriteAllText(Path.Combine(_rootDirectory, @"Service\Version.txt"), version); - _version = version; - - if (_isNew) { - Log("Installing Service " + _version); - ProcessStartInfo installService = new ProcessStartInfo(); - installService.CreateNoWindow = true; - installService.UseShellExecute = true; - installService.FileName = Path.Combine(_rootDirectory, "Service") + @"\ziti-tunnel.exe"; - installService.WindowStyle = ProcessWindowStyle.Hidden; - installService.Arguments = "install"; - Log("Install Using " + installService.FileName + " " + installService.Arguments); - try { - Process exeProcess = Process.Start(installService); - exeProcess.WaitForExit(); - Log("Installed " + installService.FileName + " " + installService.Arguments); - - } catch (Exception e) { - Log("Cannot Install Service - " + e.ToString()); - } - } else { - // nothing to do - } - StartZiti(); - } - - private void RunScript() { - string scriptText = "get-netipinterface|ForEach-Object { Set-DnsClientServerAddress-InterfaceIndex $_.ifIndex-ResetServerAddresses}"; - Log("Executing: " + scriptText); - using (PowerShell PowerShellInstance = PowerShell.Create()) { - PowerShellInstance.AddScript(scriptText); - IAsyncResult result = PowerShellInstance.BeginInvoke(); - while (result.IsCompleted == false) { - Thread.Sleep(1000); - } - } - } - - private void StartZiti() { - controller = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "ziti"); - if (controller != null && controller.Status != ServiceControllerStatus.Running && controller.Status != ServiceControllerStatus.StartPending && controller.Status != ServiceControllerStatus.ContinuePending) { - try { - Log("Starting Service"); - controller.Start(); - controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); - SetupServiceWatchers(); - } catch (Exception e) { - Log("Cannot Start Service - " + e.ToString()); - } - } - } - - private void StopZiti() { - controller = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "ziti"); - if (controller != null && controller.Status != ServiceControllerStatus.Stopped) { - try { - controller.Stop(); - controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); - } catch (Exception e) { - Log("Cannot Stop Service - " + e.ToString()); - } - } - } - - object logLock = new object(); - private void Log(string message) { - lock (logLock) { - File.AppendAllText(Path.Combine(_logDirectory, @"Log.log"), DateTime.Now.ToString() + " " + message + '\n'); - EventLog.WriteEntry("Ziti Update Service", message, EventLogEntryType.Information); - } - } - } -} +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.ServiceProcess; +using System.Text; +using System.Threading; +using System.IO; +using System.IO.Compression; +using System.Net; +using System.Timers; +using System.Management.Automation; +using System.Xml; +using System.Configuration; +using System.Threading.Tasks; + +using ZitiDesktopEdge.ServiceClient; +using NLog; +using Newtonsoft.Json.Linq; +using System.Reflection; +using NLog.Config; + +namespace ZitiUpdateService { + public partial class UpdateService : ServiceBase { + private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); + + private string _version = ""; + private bool _isNew = true; + + private System.Timers.Timer _updateTimer = new System.Timers.Timer(); + private bool inUpdateCheck = false; + private string _rootDirectory = ""; + private string _logDirectory = ""; + private string _versionType = "latest"; + + private Client svc = new Client(); + private bool running = false; + + ServiceController controller; + public UpdateService() { + InitializeComponent(); + + Logger.Info("Initializing"); + svc.OnClientConnected += Svc_OnClientConnected; + svc.OnTunnelStatusEvent += Svc_OnTunnelStatusEvent; + svc.OnClientDisconnected += Svc_OnClientDisconnected; + svc.OnShutdownEvent += Svc_OnShutdownEvent; + } + + public void Debug() { + OnStart(null); + } + + protected override void OnStart(string[] args) { + + try { + if (ConfigurationManager.AppSettings.Get("Version") != null) _versionType = ConfigurationManager.AppSettings.Get("Version"); + } catch (Exception e) { + Logger.Info(e.ToString()); + } + _rootDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "OpenZiti"); + if (!Directory.Exists(_rootDirectory)) Directory.CreateDirectory(_rootDirectory); + _logDirectory = Path.Combine(_rootDirectory, "Logs"); + if (!Directory.Exists(_logDirectory)) Directory.CreateDirectory(_logDirectory); + if (!running) { + running = true; + Task.Run(() => { + SetupServiceWatchers(); + }); + } + Logger.Info("initialized and running"); + } + + protected override void OnStop() { + Logger.Info("stopping update service"); + } + + private void SetupServiceWatchers() { + Logger.Info("setting up watches"); + + try { + svc.Connect(); + } catch { + //svc.Reconnect(); + } + + //svc.WaitForConnection(); + + var updateTimerInterval = ConfigurationManager.AppSettings.Get("UpdateTimer"); + var upInt = TimeSpan.Zero; + if (!TimeSpan.TryParse(updateTimerInterval, out upInt)) { + upInt = new TimeSpan(0, 1, 0); + } + + Logger.Info("Ziti Update Setting Up Watchers"); + + _updateTimer = new System.Timers.Timer(); + _updateTimer.Elapsed += CheckUpdate; + _updateTimer.Interval = upInt.TotalMilliseconds; + _updateTimer.Enabled = true; + _updateTimer.Start(); + Logger.Info("Version Checker is running"); + CheckUpdate(null, null); //check immediately + } + + private void CheckUpdate(object sender, ElapsedEventArgs e) { + if (inUpdateCheck) return; + inUpdateCheck = true; //simple semaphone + try { + Logger.Info("checking for update"); + var updateUrl = ConfigurationManager.AppSettings.Get("UpdateUrl"); + if (string.IsNullOrEmpty(updateUrl)) { + updateUrl = "https://api.github.com/repos/openziti/desktop-edge-win/releases/latest"; + } + IUpdateCheck check = new GithubCheck(updateUrl); + //IUpdateCheck check = new FilesystemCheck(); + + string currentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); //fetch from ziti? + Version installed = new Version(currentVersion); + if (!check.IsUpdateAvailable(installed)) { + Logger.Debug("update check complete. no update available"); + inUpdateCheck = false; + return; + } + + Logger.Info("update is available."); + + var curdir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + + var updateFolder = $"{curdir}{Path.DirectorySeparatorChar}updates"; + Directory.CreateDirectory(updateFolder); + + Logger.Info("copying update package"); + string filename = check.FileName(); + + if (check.AlreadyDownloaded(updateFolder, filename)) { + Logger.Info("package has already been downloaded - moving to install phase"); + } else { + Logger.Info("copying update package begins"); + check.CopyUpdatePackage(updateFolder, filename); + Logger.Info("copying update package complete"); + } + + StopZiti(); + + // shell out to a new process and run the uninstall, reinstall steps which SHOULD stop this current process as well + string fileDestination = Path.Combine(updateFolder, filename); + Process.Start(fileDestination, "/passive"); + } catch (Exception ex) { + Logger.Error(ex, "Unexpected error has occurred"); + } + inUpdateCheck = false; + } + + private void StartZiti() { + controller = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "ziti"); + if (controller != null && controller.Status != ServiceControllerStatus.Running && controller.Status != ServiceControllerStatus.StartPending && controller.Status != ServiceControllerStatus.ContinuePending) { + try { + Logger.Info("Starting Service"); + controller.Start(); + controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); + SetupServiceWatchers(); + } catch (Exception e) { + Logger.Info("Cannot Start Service - " + e.ToString()); + } + } + } + + private void StopZiti() { + Logger.Info("Stopping the ziti service..."); + controller = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "ziti"); + if (controller != null && controller.Status != ServiceControllerStatus.Stopped) { + try { + controller.Stop(); + controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); + } catch (Exception e) { + Logger.Error(e, "Timout while trying to stop service!"); + } + } + } + + private static void Svc_OnShutdownEvent(object sender, StatusEvent e) { + Logger.Info("the service is shutting down normally..."); + } + + private static void Svc_OnTunnelStatusEvent(object sender, TunnelStatusEvent e) { + string dns = e?.Status?.IpInfo?.DNS; + string version = e?.Status?.ServiceVersion.Version; + string op = e?.Op; + Logger.Info($"Operation {op}. running dns: {dns} at version {version}"); + } + + private static void Svc_OnClientConnected(object sender, object e) { + Logger.Info("successfully connected to service"); + } + + private static void Svc_OnClientDisconnected(object sender, object e) { + + Client svc = (Client)sender; + if (svc.CleanShutdown) { + //then this is fine and expected - the service is shutting down + Logger.Info("client disconnected due to clean service shutdown"); + } else { + Logger.Error("SERVICE IS DOWN and did not exit cleanly. initiating DNS cleanup"); + //EnumerateDNS(); + var ps = System.Management.Automation.PowerShell.Create(); + string script = "Get-NetIPInterface | ForEach-Object { Set-DnsClientServerAddress -InterfaceIndex $_.ifIndex -ResetServerAddresses }"; + ps.Commands.AddScript(script); + Logger.Info("No longer connected to the service. Resetting the network by executing reset script."); + Task.Delay(1000).Wait(); + ps.Invoke(); + Logger.Info("Reset script executed."); + //EnumerateDNS(); + } + } + + private static void EnumerateDNS() { + var ps = System.Management.Automation.PowerShell.Create(); + ps.AddScript("Get-DnsClientServerAddress"); + var results = ps.Invoke(); + + using (StringWriter sw = new StringWriter()) { + foreach (var r in results) { + string name = (string)r.Properties["InterfaceAlias"].Value; + string[] dnses = (string[])r.Properties["ServerAddresses"].Value; + sw.WriteLine($"Interface: {name}. DNS: {string.Join(",", dnses)}"); + } + Logger.Info("DNS RESULTS:\n{0}", sw.ToString()); + } + } + } +} diff --git a/ZitiUpdateService/ZitiUpdateService.csproj b/ZitiUpdateService/ZitiUpdateService.csproj index 896f9f87..9b676c36 100644 --- a/ZitiUpdateService/ZitiUpdateService.csproj +++ b/ZitiUpdateService/ZitiUpdateService.csproj @@ -1,140 +1,160 @@ - - - - - Debug - AnyCPU - {9AB81609-F5DD-40A6-87B5-F3279D48514D} - WinExe - ZitiUpdateService - ZitiUpdateService - v4.8 - 512 - true - true - false - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 1 - 1.0.0.%2a - false - true - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - x64 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - ziti-white.ico - - - 189AAD422A106DC81E8E79C7E0D2118CEB2E6321 - - - - - - - true - - - LocalIntranet - - - Properties\app.manifest - - - true - - - bin\Releases\ - - - - - - - - - - - ..\packages\Microsoft.PowerShell.5.ReferenceAssemblies.1.1.0\lib\net4\System.Management.Automation.dll - - - - - - - - - - - - Component - - - ProjectInstaller.cs - - - Component - - - UpdateService.cs - - - - - - - Always - - - - - - - - ProjectInstaller.cs - - - - - - - - False - Microsoft .NET Framework 4.8 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 - false - - - + + + + + Debug + AnyCPU + {9AB81609-F5DD-40A6-87B5-F3279D48514D} + WinExe + ZitiUpdateService + ZitiUpdateService + v4.8 + 512 + true + true + false + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 1 + 1.0.0.%2a + false + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + x64 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + ziti.ico + + + 189AAD422A106DC81E8E79C7E0D2118CEB2E6321 + + + + + + + true + + + LocalIntranet + + + Properties\app.manifest + + + true + + + bin\Releases\ + + + + ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + + + ..\packages\NLog.4.7.5\lib\net45\NLog.dll + + + + + + + + + + ..\packages\Microsoft.PowerShell.5.ReferenceAssemblies.1.1.0\lib\net4\System.Management.Automation.dll + + + + + + + + + + + + + + + + + + Component + + + ProjectInstaller.cs + + + + Component + + + UpdateService.cs + + + + + + Always + + + + + + + + + ProjectInstaller.cs + + + + + + + + + False + Microsoft .NET Framework 4.8 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 + false + + + + + {26b30979-99b5-4102-bd0b-129bedff0057} + ZitiDesktopEdge.Client + + + \ No newline at end of file diff --git a/ZitiUpdateService/packages.config b/ZitiUpdateService/packages.config index d5a74547..bba3d6da 100644 --- a/ZitiUpdateService/packages.config +++ b/ZitiUpdateService/packages.config @@ -1,4 +1,6 @@ - - - + + + + + \ No newline at end of file diff --git a/ZitiUpdateService/ziti-green.ico b/ZitiUpdateService/ziti-green.ico new file mode 100644 index 00000000..1773e4e9 Binary files /dev/null and b/ZitiUpdateService/ziti-green.ico differ diff --git a/ZitiUpdateService/ziti.ico b/ZitiUpdateService/ziti.ico new file mode 100644 index 00000000..141e513d Binary files /dev/null and b/ZitiUpdateService/ziti.ico differ diff --git a/service/cziti/ctun.go b/service/cziti/ctun.go index ef0f7972..860fe8d7 100644 --- a/service/cziti/ctun.go +++ b/service/cziti/ctun.go @@ -97,7 +97,7 @@ func HookupTun(dev tun.Device/*, dns []net.IP*/) error { writeQ: make(chan []byte, 64), readQ: make(chan []byte, 64), } - //devMap[name] = t + theTun = t opts := (*C.tunneler_sdk_options)(C.calloc(1, C.sizeof_tunneler_sdk_options)) @@ -143,11 +143,6 @@ func netifClose(h C.netif_handle) C.int { //export netifSetup func netifSetup(h C.netif_handle, l *C.uv_loop_t, packetCb C.packet_cb, ctx unsafe.Pointer) C.int { - /*t, found := devMap[C.GoString(h.id)] - if !found { - log.Error("should not be here") - return -1 - }*/ theTun.read = (*C.uv_async_t)(C.calloc(1, C.sizeof_uv_async_t)) C.uv_async_init(l, theTun.read, C.uv_async_cb(C.readAsync)) @@ -201,13 +196,6 @@ func (t *tunnel) runReadLoop() { //export readIdle func readIdle(idler *C.uv_prepare_t) { - /*dev := (*C.netif_handle_t)(idler.data) - - id := C.GoString(dev.id) - t, found := devMap[id] - if !found { - log.Panicf("An unexpected and unrecoverable error has occurred while looking for tun in devMap") - }*/ np := len(theTun.readQ) for i := np; i > 0; i-- { @@ -266,17 +254,8 @@ func RemoveIntercept(rwg *RemoveWG) { //export remove_intercepts func remove_intercepts(async *C.uv_async_t) { - //C.ZLOG(C.INFO, C.CString(fmt.Sprint("aaaa on uv thread - inside remove_intercepts: %d", &async.loop))) - //c := (*C.char)(async.data) rwg := (*RemoveWG)(async.data) - - /*for _, t := range devMap { - //C.ZLOG(C.INFO, C.CString("bbb on uv thread - inside remove_intercepts")) - C.ziti_tunneler_stop_intercepting(t.tunCtx, C.CString(rwg.SvcId)) - }*/ C.ziti_tunneler_stop_intercepting(theTun.tunCtx, C.CString(rwg.SvcId)) - //C.ZLOG(C.INFO, C.CString("ccc on uv thread - inside remove_intercepts")) C.uv_close((*C.uv_handle_t)(unsafe.Pointer(async)), C.uv_close_cb(C.free_async)) - C.ZLOG(C.INFO, C.CString("on uv thread - completed remove_intercepts")) rwg.Wg.Done() } diff --git a/service/cziti/dns-proxy.go b/service/cziti/dns-proxy.go index 2d7e2455..9352accb 100644 --- a/service/cziti/dns-proxy.go +++ b/service/cziti/dns-proxy.go @@ -159,8 +159,11 @@ func runListener(ip *net.IP, port int, reqch chan dnsreq) { server, err = net.ListenUDP(network, laddr) if err == nil { break - } else if attempts > maxAttempts{ + } else if attempts > maxAttempts { log.Panicf("An unexpected and unrecoverable error has occurred while %s: %v", "udp listening on network", err) + } else if attempts < (3 * maxAttempts / 4) { + // only log at debug until we hit 3/4 the max attempts to remove unnecessary warns from the log + log.Debugf("System not ready to listen on %v yet. Retrying after 500ms. This has happened %d times.", laddr, attempts) } else { log.Warnf("System not ready to listen on %v yet. Retrying after 500ms. This has happened %d times.", laddr, attempts) } diff --git a/service/cziti/dns.go b/service/cziti/dns.go index b6a4f688..0e11ba74 100644 --- a/service/cziti/dns.go +++ b/service/cziti/dns.go @@ -54,7 +54,12 @@ type intercept struct { isIp bool } func (i intercept) String() string { - return fmt.Sprintf("%s:%d", i.host, i.port) + if i.isIp { + //an ip does not need the host normalized + return fmt.Sprintf("%s:%d", i.host, i.port) + } else { + return fmt.Sprintf("%s:%d", normalizeDnsName(i.host), i.port) + } } type ctxIp struct { @@ -90,12 +95,6 @@ func (dns *dnsImpl) RegisterService(svcId string, dnsNameToReg string, port uint ip := net.ParseIP(dnsNameToReg) icept := intercept{isIp: false, port: port} - if ip == nil { - icept.host = normalizeDnsName(dnsNameToReg) - } else { - icept.host = ip.String() - icept.isIp = true - } key := icept.String() log.Infof("adding DNS for %s. service name %s@%s. is ip: %t", dnsNameToReg, svcName, key, icept.isIp) @@ -190,7 +189,6 @@ func (dns *dnsImpl) UnregisterService(host string, port uint16) { log.Warnf("Unexpected error removing route for %s", icept.host) } } else { - //delete(dns.hostnameMap, icept.host) dns.hostnameMap[icept.host].dnsEnabled = false } delete(dns.serviceMap, key) diff --git a/service/ziti-tunnel/dto/dtos.go b/service/ziti-tunnel/dto/dtos.go index 4c0f3a9e..385db8ac 100644 --- a/service/ziti-tunnel/dto/dtos.go +++ b/service/ziti-tunnel/dto/dtos.go @@ -88,6 +88,7 @@ type TunnelStatus struct { ServiceVersion ServiceVersion TunIpv4 string TunIpv4Mask int + Status string } type ServiceVersion struct { diff --git a/service/ziti-tunnel/main.go b/service/ziti-tunnel/main.go index 9a4b0fb9..d7b7c8f4 100644 --- a/service/ziti-tunnel/main.go +++ b/service/ziti-tunnel/main.go @@ -41,15 +41,6 @@ func main() { } logging.InitLogger("info") - //if len(os.Args) < 2 { - // // if no args supplied - expect to run as service - // os.Args = append(os.Args, "service") - //} - //cmd.Execute() - //if true { - // os.Exit(0) - //} - // passing no arguments is an indicator that this is expecting to be run 'as a service'. // using arg count instead of svc.IsAnInteractiveSession() as svc.IsAnInteractiveSession() // seems to return false even when run in an interactive shell as via `psexec -i -s cmd.exe` diff --git a/service/ziti-tunnel/service/ipc.go b/service/ziti-tunnel/service/ipc.go index afc912b0..588c25fd 100644 --- a/service/ziti-tunnel/service/ipc.go +++ b/service/ziti-tunnel/service/ipc.go @@ -110,6 +110,19 @@ func SubMain(ops chan string, changes chan<- svc.Status) error { requestShutdown("service shutdown") + // signal to any connected consumers that the service is shutting down normally + events.broadcast <- dto.StatusEvent { + Op: "shutdown", + } + + // wait 1 second for the shutdown to send to clients + shutdownDelay := make(chan bool) + go func() { + time.Sleep(1*time.Second) + shutdownDelay <- true + }() + <-shutdownDelay + log.Infof("shutting down connections...") pipes.shutdownConnections() @@ -327,15 +340,6 @@ func serveIpc(conn net.Conn) { defer log.Info("A connected IPC client has disconnected") defer closeConn(conn) //close the connection after this function invoked as go routine exits - if len(events.broadcast) == cap(events.broadcast) { - log.Warn("TunnelStatusEvent will be blocked. If this warning is continuously displayed please report") - } - events.broadcast <- dto.TunnelStatusEvent{ - StatusEvent: dto.StatusEvent{Op: "status"}, - Status: rts.ToStatus(), - ApiVersion: API_VERSION, - } - done := make(chan struct{}, 8) defer close(done) // ensure that goroutine exits @@ -366,8 +370,9 @@ func serveIpc(conn net.Conn) { enc := json.NewEncoder(writer) for { - log.Debug("beginning read") + log.Debug("ipc read begins") msg, err := reader.ReadString('\n') + log.Debug("ipc read ends") if err != nil { if err != winio.ErrFileClosed { if err == io.EOF { diff --git a/service/ziti-tunnel/util/iputil/iputil.go b/service/ziti-tunnel/util/iputil/iputil.go new file mode 100644 index 00000000..838664de --- /dev/null +++ b/service/ziti-tunnel/util/iputil/iputil.go @@ -0,0 +1,50 @@ +/* + * Copyright NetFoundry, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package iputil + +import ( + "encoding/binary" + "net" +) + +var allOnes = 0xFFFFFFFF + +func Ipv4Inc(ip net.IP, maskBits int) net.IP { + baseIpMask := 32 - maskBits + baseMask := (allOnes >> baseIpMask) << baseIpMask + ipMask := allOnes >> maskBits + + ipAsInt := Ipv4ToUint32(ip) + baseIp := ipAsInt & uint32(baseMask) + //fmt.Printf("actual ip: %b - %v ", ipAsInt, ip) + + newIpAsInt := ipAsInt + 1 + + return Uint32ToIpv4(baseIp + newIpAsInt & uint32(ipMask)) +} +func Ipv4ToUint32(ip net.IP) uint32 { + if len(ip) == 16 { + return binary.BigEndian.Uint32(ip[12:16]) + } + return binary.BigEndian.Uint32(ip) +} +func Uint32ToIpv4(nn uint32) net.IP { + ip := make(net.IP, 4) + binary.BigEndian.PutUint32(ip, nn) + return ip +}