From 5532e4e205067db355453e93aba047d9591d21d4 Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Tue, 17 Nov 2020 07:32:13 -0500
Subject: [PATCH 01/25] target dotnet 4.7.2 vs 4.8 due to many users not havin
4.8 yet
---
DesktopEdge/App.config | 12 +-
DesktopEdge/Properties/Resources.Designer.cs | 126 +++++++++----------
DesktopEdge/Properties/Settings.Designer.cs | 52 ++++----
DesktopEdge/ZitiDesktopEdge.csproj | 10 +-
DesktopEdge/packages.config | 8 +-
Installer/ZitiDesktopEdge.aip | 6 +-
6 files changed, 102 insertions(+), 112 deletions(-)
diff --git a/DesktopEdge/App.config b/DesktopEdge/App.config
index 1451e8e03..de277144e 100644
--- a/DesktopEdge/App.config
+++ b/DesktopEdge/App.config
@@ -1,6 +1,6 @@
-
-
-
-
-
-
\ No newline at end of file
+
+
+
+
+
+
diff --git a/DesktopEdge/Properties/Resources.Designer.cs b/DesktopEdge/Properties/Resources.Designer.cs
index e73a18ffe..d8f00c553 100644
--- a/DesktopEdge/Properties/Resources.Designer.cs
+++ b/DesktopEdge/Properties/Resources.Designer.cs
@@ -1,63 +1,63 @@
-//------------------------------------------------------------------------------
-//
-// This code was generated by a tool.
-// Runtime Version:4.0.30319.42000
-//
-// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
-//
-//------------------------------------------------------------------------------
-
-namespace Ziti.Desktop.Edge.Properties {
- using System;
-
-
- ///
- /// A strongly-typed resource class, for looking up localized strings, etc.
- ///
- // This class was auto-generated by the StronglyTypedResourceBuilder
- // class via a tool like ResGen or Visual Studio.
- // To add or remove a member, edit your .ResX file then rerun ResGen
- // with the /str option, or rebuild your VS project.
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- internal class Resources {
-
- private static global::System.Resources.ResourceManager resourceMan;
-
- private static global::System.Globalization.CultureInfo resourceCulture;
-
- [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal Resources() {
- }
-
- ///
- /// Returns the cached ResourceManager instance used by this class.
- ///
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Resources.ResourceManager ResourceManager {
- get {
- if (object.ReferenceEquals(resourceMan, null)) {
- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ziti.Desktop.Edge.Properties.Resources", typeof(Resources).Assembly);
- resourceMan = temp;
- }
- return resourceMan;
- }
- }
-
- ///
- /// Overrides the current thread's CurrentUICulture property for all
- /// resource lookups using this strongly typed resource class.
- ///
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Globalization.CultureInfo Culture {
- get {
- return resourceCulture;
- }
- set {
- resourceCulture = value;
- }
- }
- }
-}
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace Ziti.Desktop.Edge.Properties {
+ using System;
+
+
+ ///
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ ///
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources() {
+ }
+
+ ///
+ /// Returns the cached ResourceManager instance used by this class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ziti.Desktop.Edge.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/DesktopEdge/Properties/Settings.Designer.cs b/DesktopEdge/Properties/Settings.Designer.cs
index bd88d5245..c70068f11 100644
--- a/DesktopEdge/Properties/Settings.Designer.cs
+++ b/DesktopEdge/Properties/Settings.Designer.cs
@@ -1,26 +1,26 @@
-//------------------------------------------------------------------------------
-//
-// This code was generated by a tool.
-// Runtime Version:4.0.30319.42000
-//
-// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
-//
-//------------------------------------------------------------------------------
-
-namespace Ziti.Desktop.Edge.Properties {
-
-
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.6.0.0")]
- internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
-
- private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
-
- public static Settings Default {
- get {
- return defaultInstance;
- }
- }
- }
-}
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace Ziti.Desktop.Edge.Properties {
+
+
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default {
+ get {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/DesktopEdge/ZitiDesktopEdge.csproj b/DesktopEdge/ZitiDesktopEdge.csproj
index 88fec2a3d..188d44eda 100644
--- a/DesktopEdge/ZitiDesktopEdge.csproj
+++ b/DesktopEdge/ZitiDesktopEdge.csproj
@@ -8,7 +8,7 @@
WinExe
Ziti.Desktop.Edge
ZitiDesktopEdge
- v4.8
+ v4.7.2
512
{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
4
@@ -94,16 +94,8 @@
-
- ..\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
-
diff --git a/DesktopEdge/packages.config b/DesktopEdge/packages.config
index d4d1038f5..b38f3c783 100644
--- a/DesktopEdge/packages.config
+++ b/DesktopEdge/packages.config
@@ -1,6 +1,4 @@
-
-
-
-
-
+
+
+
\ No newline at end of file
diff --git a/Installer/ZitiDesktopEdge.aip b/Installer/ZitiDesktopEdge.aip
index bf4eaabc4..7a60a08ef 100644
--- a/Installer/ZitiDesktopEdge.aip
+++ b/Installer/ZitiDesktopEdge.aip
@@ -290,12 +290,12 @@
-
+
-
+
-
+
From 4e39b1e2414aba108e0545d9a67d80dcef49b3de Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Tue, 17 Nov 2020 07:32:32 -0500
Subject: [PATCH 02/25] target dotnet 4.7.2 vs 4.8 due to many users not havin
4.8 yet
---
DesktopEdge/MainMenu.xaml.cs | 1 -
DesktopEdge/Models/ZitiService.cs | 109 +++++++++++++++---------------
2 files changed, 54 insertions(+), 56 deletions(-)
diff --git a/DesktopEdge/MainMenu.xaml.cs b/DesktopEdge/MainMenu.xaml.cs
index 678c29e00..09770e786 100644
--- a/DesktopEdge/MainMenu.xaml.cs
+++ b/DesktopEdge/MainMenu.xaml.cs
@@ -4,7 +4,6 @@
using System.Diagnostics;
using System;
using System.Threading;
-using System.Management.Automation;
using ZitiDesktopEdge.Models;
using System.Reflection;
using System.Web;
diff --git a/DesktopEdge/Models/ZitiService.cs b/DesktopEdge/Models/ZitiService.cs
index 9b8f75ebd..97daf0a2c 100644
--- a/DesktopEdge/Models/ZitiService.cs
+++ b/DesktopEdge/Models/ZitiService.cs
@@ -1,55 +1,54 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Management.Automation.Language;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace ZitiDesktopEdge.Models {
- public class ZitiService {
- public string Name { get; set; }
- public string AssignedIP { get; set; }
- public string Host { get; set; }
- public string Port { get; set; }
- public bool OwnsIntercept { get; set; }
- public string Url
- {
- get
- {
- if (this.OwnsIntercept)
- {
- return Host + ":" + Port;
- } else
- {
- return AssignedIP + ":" + Port;
- }
- }
- }
- public string Warning
- {
- get
- {
- if (this.OwnsIntercept)
- {
- return "";
- }
- else
- {
- return $"Another identity already mapped the specified hostname: {Host}.\nThis service is only available via IP";
- }
- }
- }
-
- public ZitiService() {
- }
-
- public ZitiService(ZitiDesktopEdge.ServiceClient.Service svc)
- {
- this.Name = svc.Name;
- this.AssignedIP = svc.AssignedIP;
- this.Host = svc.InterceptHost;
- this.Port = svc.InterceptPort.ToString();
- this.OwnsIntercept = svc.OwnsIntercept;
- }
- }
-}
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ZitiDesktopEdge.Models {
+ public class ZitiService {
+ public string Name { get; set; }
+ public string AssignedIP { get; set; }
+ public string Host { get; set; }
+ public string Port { get; set; }
+ public bool OwnsIntercept { get; set; }
+ public string Url
+ {
+ get
+ {
+ if (this.OwnsIntercept)
+ {
+ return Host + ":" + Port;
+ } else
+ {
+ return AssignedIP + ":" + Port;
+ }
+ }
+ }
+ public string Warning
+ {
+ get
+ {
+ if (this.OwnsIntercept)
+ {
+ return "";
+ }
+ else
+ {
+ return $"Another identity already mapped the specified hostname: {Host}.\nThis service is only available via IP";
+ }
+ }
+ }
+
+ public ZitiService() {
+ }
+
+ public ZitiService(ZitiDesktopEdge.ServiceClient.Service svc)
+ {
+ this.Name = svc.Name;
+ this.AssignedIP = svc.AssignedIP;
+ this.Host = svc.InterceptHost;
+ this.Port = svc.InterceptPort.ToString();
+ this.OwnsIntercept = svc.OwnsIntercept;
+ }
+ }
+}
From c4123ada4272eb734132b42c342242d536deab21 Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Tue, 17 Nov 2020 07:33:49 -0500
Subject: [PATCH 03/25] downgrade to dotnet 4.7.2 - add initial server stub for
'big button'
---
ZitiUpdateService/App.config | 18 +++---
ZitiUpdateService/IPC/IPCServer.cs | 65 ++++++++++++++++++++++
ZitiUpdateService/Program.cs | 13 +++--
ZitiUpdateService/ZitiUpdateService.csproj | 4 +-
4 files changed, 86 insertions(+), 14 deletions(-)
create mode 100644 ZitiUpdateService/IPC/IPCServer.cs
diff --git a/ZitiUpdateService/App.config b/ZitiUpdateService/App.config
index 29658eee5..c3a5ec29b 100644
--- a/ZitiUpdateService/App.config
+++ b/ZitiUpdateService/App.config
@@ -1,7 +1,7 @@
-
+
-
+
-
+
-
-
+
+
-
+
-
+
-
+
-
\ No newline at end of file
+
diff --git a/ZitiUpdateService/IPC/IPCServer.cs b/ZitiUpdateService/IPC/IPCServer.cs
new file mode 100644
index 000000000..5846b0951
--- /dev/null
+++ b/ZitiUpdateService/IPC/IPCServer.cs
@@ -0,0 +1,65 @@
+using System;
+using System.Threading.Tasks;
+using System.IO;
+using System.IO.Pipes;
+using Newtonsoft.Json;
+
+namespace ZitiUpdateService.IPC {
+ public class IPCServer {
+ /*
+ InteractivelyLoggedInUser = "(A;;GRGW;;;IU)" //generic read/write. We will want to tune this to a specific group but that is not working with Windows 10 home at the moment
+ System = "(A;;FA;;;SY)"
+ BuiltinAdmins = "(A;;FA;;;BA)"
+ LocalService = "(A;;FA;;;LS)"
+ */
+ private string pipeName;
+ public IPCServer(string pipeName) {
+ this.pipeName = pipeName;
+ }
+
+ async public Task acceptAsync() {
+ int idx = 0;
+ while (true) {
+ var namedPipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte);
+ await namedPipeServer.WaitForConnectionAsync();
+ var t = Task.Run(async ()=>{
+ await handleClientAsync(namedPipeServer, idx);
+ idx--;
+ });
+ idx++;
+ }
+ }
+
+ async public Task handleClientAsync(NamedPipeServerStream ss, int clientIndex) {
+ using (ss) {
+ try {
+ var streamReader = new StreamReader(ss);
+ var line = await streamReader.ReadLineAsync();
+
+ var writer = new StreamWriter(ss);
+ for (int i = 0; i < 10; i++) {
+ writer.Write($"Hello from c# : {clientIndex}:{i} - Thread:{System.Threading.Thread.CurrentThread.ManagedThreadId}" );
+ writer.Write("\n");
+ writer.Flush();
+ }
+ ss.WaitForPipeDrain();
+
+ Console.WriteLine($"read from pipe client: {streamReader.ReadLine()}");
+ ss.Dispose();
+ } catch(Exception e) {
+ Console.WriteLine("meh - error: " + e.Message);
+ }
+ }
+ }
+
+ public static object DeserializeFromStream(Stream stream) {
+ var serializer = new JsonSerializer();
+
+ using (var sr = new StreamReader(stream))
+ using (var jsonTextReader = new JsonTextReader(sr)) {
+
+ return serializer.Deserialize(jsonTextReader);
+ }
+ }
+ }
+}
diff --git a/ZitiUpdateService/Program.cs b/ZitiUpdateService/Program.cs
index 47b17a830..53a18ec01 100644
--- a/ZitiUpdateService/Program.cs
+++ b/ZitiUpdateService/Program.cs
@@ -8,6 +8,8 @@
namespace ZitiUpdateService {
static class Program {
+ private static string PipeName = @"OpenZiti\tunneler\ipc";
+
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
///
@@ -42,19 +44,22 @@ static void Main() {
LogManager.Configuration = config;
}
Logger.Info("service started - logger initialized");
+
+ IPC.IPCServer svr = new IPC.IPCServer(PipeName);
+ svr.acceptAsync().Wait();
+
UpdateService updateSvc = new UpdateService();
+ updateSvc.AutoLog = true;
#if DEBUG
-
updateSvc.Debug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
- ServiceBase[] ServicesToRun;
- ServicesToRun = new ServiceBase[]
+ ServiceBase[] ServicesToRun = new ServiceBase[]
{
updateSvc
};
ServiceBase.Run(ServicesToRun);
#endif
}
- }
+ }
}
diff --git a/ZitiUpdateService/ZitiUpdateService.csproj b/ZitiUpdateService/ZitiUpdateService.csproj
index 52a43b791..e57efc065 100644
--- a/ZitiUpdateService/ZitiUpdateService.csproj
+++ b/ZitiUpdateService/ZitiUpdateService.csproj
@@ -8,7 +8,7 @@
WinExe
ZitiUpdateService
ZitiUpdateService
- v4.8
+ v4.7.2
512
true
true
@@ -28,6 +28,7 @@
false
true
true
+
AnyCPU
@@ -103,6 +104,7 @@
+
From 57a6fe4913b685d8823ee5e0ae23464d66a0317f Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Tue, 17 Nov 2020 10:48:32 -0500
Subject: [PATCH 04/25] wip commit
---
ZitiUpdateService/App.config | 24 ++++++++++-----
ZitiUpdateService/IPC/IPCServer.cs | 34 ++++++++++++----------
ZitiUpdateService/UpdateCheckers.cs | 16 +++++-----
ZitiUpdateService/ZitiUpdateService.csproj | 26 +++++++++++++++--
ZitiUpdateService/packages.config | 10 ++++++-
5 files changed, 77 insertions(+), 33 deletions(-)
diff --git a/ZitiUpdateService/App.config b/ZitiUpdateService/App.config
index c3a5ec29b..d795b592e 100644
--- a/ZitiUpdateService/App.config
+++ b/ZitiUpdateService/App.config
@@ -1,7 +1,7 @@
-
+
-
+
-
+
-
-
+
+
-
+
-
+
-
+
+
+
+
+
+
+
+
+
diff --git a/ZitiUpdateService/IPC/IPCServer.cs b/ZitiUpdateService/IPC/IPCServer.cs
index 5846b0951..9f3a8d236 100644
--- a/ZitiUpdateService/IPC/IPCServer.cs
+++ b/ZitiUpdateService/IPC/IPCServer.cs
@@ -2,10 +2,13 @@
using System.Threading.Tasks;
using System.IO;
using System.IO.Pipes;
-using Newtonsoft.Json;
+using NLog;
+using System.Text.Json;
namespace ZitiUpdateService.IPC {
public class IPCServer {
+ private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+
/*
InteractivelyLoggedInUser = "(A;;GRGW;;;IU)" //generic read/write. We will want to tune this to a specific group but that is not working with Windows 10 home at the moment
System = "(A;;FA;;;SY)"
@@ -32,34 +35,35 @@ async public Task acceptAsync() {
async public Task handleClientAsync(NamedPipeServerStream ss, int clientIndex) {
using (ss) {
- try {
- var streamReader = new StreamReader(ss);
- var line = await streamReader.ReadLineAsync();
+ try {
+ //var streamReader = new StreamReader(ss);
+ //var line = await streamReader.ReadLineAsync();
+ /*
var writer = new StreamWriter(ss);
for (int i = 0; i < 10; i++) {
writer.Write($"Hello from c# : {clientIndex}:{i} - Thread:{System.Threading.Thread.CurrentThread.ManagedThreadId}" );
writer.Write("\n");
writer.Flush();
}
+ */
+ JsonDocument d;
+ while((d = await DeserializeFromStream(ss)) != null) {
+ Logger.Info("json object received: " + d.ToString());
+ }
+
ss.WaitForPipeDrain();
- Console.WriteLine($"read from pipe client: {streamReader.ReadLine()}");
- ss.Dispose();
+ //Logger.Debug($"read from pipe client: {streamReader.ReadLine()}");
} catch(Exception e) {
- Console.WriteLine("meh - error: " + e.Message);
+ Logger.Error(e, "Unexpected erorr when reading from or writing to a client pipe.");
}
}
}
- public static object DeserializeFromStream(Stream stream) {
- var serializer = new JsonSerializer();
-
- using (var sr = new StreamReader(stream))
- using (var jsonTextReader = new JsonTextReader(sr)) {
-
- return serializer.Deserialize(jsonTextReader);
- }
+ public async static Task DeserializeFromStream(Stream stream) {
+ JsonDocument jd = await JsonSerializer.DeserializeAsync(stream);
+ return jd;
}
}
}
diff --git a/ZitiUpdateService/UpdateCheckers.cs b/ZitiUpdateService/UpdateCheckers.cs
index 34c265b12..f3ccff0c8 100644
--- a/ZitiUpdateService/UpdateCheckers.cs
+++ b/ZitiUpdateService/UpdateCheckers.cs
@@ -1,9 +1,9 @@
using System;
using System.IO;
using System.Net;
+using System.Text.Json;
using NLog;
-using Newtonsoft.Json.Linq;
namespace ZitiUpdateService {
internal class GithubCheck : IUpdateCheck {
@@ -40,8 +40,8 @@ public bool IsUpdateAvailable(Version current) {
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";
+ JsonDocument json = JsonDocument.Parse(result);
+ string serverVersion = json.RootElement.GetProperty("tag_name").GetString() + ".0";
Version published = new Version(serverVersion);
int compare = current.CompareTo(published);
@@ -54,10 +54,12 @@ public bool IsUpdateAvailable(Version current) {
Logger.Debug("current version {0} is the same as the latest release {0}", current, published);
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;
+
+ foreach (JsonElement asset in json.RootElement.GetProperty("assets").EnumerateArray()) {
+ downloadUrl = asset.GetProperty("browser_download_url").GetString();
+ if (downloadUrl != null) {
+ break;
+ }
}
if (downloadUrl == null) {
diff --git a/ZitiUpdateService/ZitiUpdateService.csproj b/ZitiUpdateService/ZitiUpdateService.csproj
index e57efc065..81fa115f1 100644
--- a/ZitiUpdateService/ZitiUpdateService.csproj
+++ b/ZitiUpdateService/ZitiUpdateService.csproj
@@ -75,13 +75,16 @@
bin\Releases\
-
- ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll
+
+ ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll
..\packages\NLog.4.7.5\lib\net45\NLog.dll
+
+ ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll
+
@@ -91,8 +94,27 @@
..\packages\Microsoft.PowerShell.5.ReferenceAssemblies.1.1.0\lib\net4\System.Management.Automation.dll
+
+ ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll
+
+
+
+ ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll
+
+
+ ..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll
+
+
+ ..\packages\System.Text.Encodings.Web.5.0.0\lib\net461\System.Text.Encodings.Web.dll
+
+
+ ..\packages\System.Text.Json.5.0.0\lib\net461\System.Text.Json.dll
+
+
+ ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll
+
diff --git a/ZitiUpdateService/packages.config b/ZitiUpdateService/packages.config
index bba3d6dad..86e6bcc16 100644
--- a/ZitiUpdateService/packages.config
+++ b/ZitiUpdateService/packages.config
@@ -1,6 +1,14 @@
+
-
+
+
+
+
+
+
+
+
\ No newline at end of file
From fb22f642db17f1d0f83b98f961469a206b7ebdac Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Wed, 18 Nov 2020 15:16:23 -0500
Subject: [PATCH 05/25] fixes #218 - issue when config is 0-length
---
service/ziti-tunnel/config/config.go | 4 +++
service/ziti-tunnel/service/state.go | 53 ++++++++++++++++++----------
2 files changed, 39 insertions(+), 18 deletions(-)
diff --git a/service/ziti-tunnel/config/config.go b/service/ziti-tunnel/config/config.go
index 9b19c1505..58de2012b 100644
--- a/service/ziti-tunnel/config/config.go
+++ b/service/ziti-tunnel/config/config.go
@@ -31,3 +31,7 @@ func Path() string {
func LogFile() string {
return Path() + "ziti-tunneler.log"
}
+
+func BackupFile() string {
+ return File() + ".backup"
+}
diff --git a/service/ziti-tunnel/service/state.go b/service/ziti-tunnel/service/state.go
index 166a57333..c17f42f51 100644
--- a/service/ziti-tunnel/service/state.go
+++ b/service/ziti-tunnel/service/state.go
@@ -54,7 +54,7 @@ func (t *RuntimeState) SaveState() {
// overwrite file if it exists
_ = os.MkdirAll(config.Path(), 0644)
- log.Debugf("copying original config onto config.json.backup")
+ log.Debugf("backing up config")
backup,err := backupConfig()
if err != nil {
log.Warnf("could not backup config file! %v", err)
@@ -252,29 +252,46 @@ func (t *RuntimeState) LoadIdentity(id *Id) {
}
func (t *RuntimeState) LoadConfig() {
- log.Infof("reading config file located at: %s", config.File())
- file, err := os.OpenFile(config.File(), os.O_RDONLY, 0644)
+ err := readConfig(t, config.File())
if err != nil {
- t.state = &dto.TunnelStatus{}
- return
+ err = readConfig(t, config.BackupFile())
+ if err != nil {
+ log.Panicf("config file is not valid nor is backup file!")
+ }
}
- r := bufio.NewReader(file)
- dec := json.NewDecoder(r)
+ for _, id := range t.ids {
+ id.Active = false
+ }
+}
- err = dec.Decode(&rts.state)
- if err != nil {
- log.Panicf("unexpected error reading config file. %v", err)
+func readConfig(t *RuntimeState, filename string) error {
+ log.Infof("reading config file located at: %s", filename)
+ info, err := os.Stat(filename)
+ if os.IsNotExist(err) {
+ log.Infof("the config file does not exist. this is normal if this is a new install or if the config file was removed manually")
+ return nil
}
- err = file.Close()
+ if info.Size() == 0 {
+ return fmt.Errorf("the config file at contains no bytes and is considered invalid: %s", filename)
+ }
+
+ file, err := os.OpenFile(filename, os.O_RDONLY, 0644)
if err != nil {
- log.Errorf("could not close configuration file. this is not normal! %v", err)
+ return fmt.Errorf("unexpected error opening config file: %v", err)
}
- for _, id := range t.ids {
- id.Active = false
+ r := bufio.NewReader(file)
+ dec := json.NewDecoder(r)
+
+ err = dec.Decode(&t.state)
+ defer file.Close()
+
+ if err != nil {
+ return fmt.Errorf("unexpected error reading config file: %v", err)
}
+ return nil
}
func (t *RuntimeState) UpdateIpv4Mask(ipv4mask int){
@@ -312,14 +329,14 @@ func iPv6Disabled() bool {
}
}
-func (r *RuntimeState) AddRoute(destination net.IPNet, nextHop net.IP, metric uint32) error {
- nativeTunDevice := (*r.tun).(*tun.NativeTun)
+func (t *RuntimeState) AddRoute(destination net.IPNet, nextHop net.IP, metric uint32) error {
+ nativeTunDevice := (*t.tun).(*tun.NativeTun)
luid := winipcfg.LUID(nativeTunDevice.LUID())
return luid.AddRoute(destination, nextHop, metric)
}
-func (r *RuntimeState) RemoveRoute(destination net.IPNet, nextHop net.IP) error {
- nativeTunDevice := (*r.tun).(*tun.NativeTun)
+func (t *RuntimeState) RemoveRoute(destination net.IPNet, nextHop net.IP) error {
+ nativeTunDevice := (*t.tun).(*tun.NativeTun)
luid := winipcfg.LUID(nativeTunDevice.LUID())
return luid.DeleteRoute(destination, nextHop)
}
From ee0a91207d611cfd8a0a86bf92061c24f6112de7 Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Wed, 18 Nov 2020 18:49:33 -0500
Subject: [PATCH 06/25] wip - added separate client - refactorings
---
DesktopEdge/IdentityDetails.xaml.cs | 9 +-
DesktopEdge/MainMenu.xaml.cs | 10 +-
DesktopEdge/MainWindow.xaml.cs | 12 +-
DesktopEdge/Models/ZitiIdentity.cs | 2 +-
DesktopEdge/Models/ZitiService.cs | 108 ++--
DesktopEdge/Properties/Settings.Designer.cs | 52 +-
.../Views/ItemRenderers/IdentityItem.xaml.cs | 9 +-
DesktopEdge/ZitiDesktopEdge.csproj | 10 +-
.../DataStructures.cs | 13 +-
ZitiDesktopEdge.Client/Server/IPCServer.cs | 108 ++++
.../Server/ServiceActions.cs | 30 ++
.../ServiceClient/AbstractClient.cs | 10 +
.../{ClientImpl.cs => DataClient.cs} | 43 +-
.../ServiceClient/MonitorClient.cs | 491 ++++++++++++++++++
.../ZitiDesktopEdge.Client.csproj | 10 +-
ZitiDesktopEdge.sln | 79 ++-
ZitiUpdateService/Program.cs | 12 +-
ZitiUpdateService/UpdateCheckers.cs | 17 +-
ZitiUpdateService/UpdateService.cs | 44 +-
ZitiUpdateService/ZitiUpdateService.csproj | 30 +-
ZitiUpdateService/packages.config | 10 +-
service/ziti-tunnel/service/pkg-vars.go | 2 +-
22 files changed, 898 insertions(+), 213 deletions(-)
rename ZitiDesktopEdge.Client/{ServiceClient => DataStructures}/DataStructures.cs (93%)
create mode 100644 ZitiDesktopEdge.Client/Server/IPCServer.cs
create mode 100644 ZitiDesktopEdge.Client/Server/ServiceActions.cs
create mode 100644 ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
rename ZitiDesktopEdge.Client/ServiceClient/{ClientImpl.cs => DataClient.cs} (92%)
create mode 100644 ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
diff --git a/DesktopEdge/IdentityDetails.xaml.cs b/DesktopEdge/IdentityDetails.xaml.cs
index 68635e7d4..41819a801 100644
--- a/DesktopEdge/IdentityDetails.xaml.cs
+++ b/DesktopEdge/IdentityDetails.xaml.cs
@@ -14,7 +14,8 @@
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZitiDesktopEdge.Models;
-
+using ZitiDesktopEdge.ServiceClient;
+
namespace ZitiDesktopEdge {
///
/// Interaction logic for IdentityDetails.xaml
@@ -110,7 +111,7 @@ public void UpdateView() {
}
private void IdToggle(bool on) {
- ServiceClient.Client client = (ServiceClient.Client)Application.Current.Properties["ServiceClient"];
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
client.IdentityOnOff(_identity.Fingerprint, on);
SelectedIdentity.ToggleSwitch.Enabled = on;
_identity.IsEnabled = on;
@@ -140,7 +141,7 @@ private void CancelConfirmButton_Click(object sender, RoutedEventArgs e) {
private void ConfirmButton_Click(object sender, RoutedEventArgs e) {
this.Visibility = Visibility.Collapsed;
- ServiceClient.Client client = (ServiceClient.Client)Application.Current.Properties["ServiceClient"];
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
try {
client.RemoveIdentity(_identity.Fingerprint);
@@ -156,7 +157,7 @@ private void ConfirmButton_Click(object sender, RoutedEventArgs e) {
if (OnForgot != null) {
OnForgot(forgotten);
}
- } catch (ServiceClient.ServiceException se) {
+ } catch (DataStructures.ServiceException se) {
OnError(se.Message);
} catch (Exception ex) {
OnError(ex.Message);
diff --git a/DesktopEdge/MainMenu.xaml.cs b/DesktopEdge/MainMenu.xaml.cs
index 09770e786..7520dc8bf 100644
--- a/DesktopEdge/MainMenu.xaml.cs
+++ b/DesktopEdge/MainMenu.xaml.cs
@@ -11,8 +11,8 @@
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
-using System.Threading.Tasks;
-
+using ZitiDesktopEdge.ServiceClient;
+
namespace ZitiDesktopEdge
{
///
@@ -149,7 +149,7 @@ private void UpdateState() {
string version = "";
try {
- ServiceClient.TunnelStatus s = (ServiceClient.TunnelStatus)Application.Current.Properties["CurrentTunnelStatus"];
+ DataStructures.TunnelStatus s = (DataStructures.TunnelStatus)Application.Current.Properties["CurrentTunnelStatus"];
version = $"{s.ServiceVersion.Version}@{s.ServiceVersion.Revision}";
} catch (Exception e) {
#if DEBUG
@@ -169,7 +169,7 @@ private void UpdateState() {
LicensesItems.Visibility = Visibility.Visible;
BackArrow.Visibility = Visibility.Visible;
} else if (menuState=="Logs") {
- ServiceClient.Client client = (ServiceClient.Client)Application.Current.Properties["ServiceClient"];
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
MenuTitle.Content = "Service Logs";
LogsItems.Text = client.GetLogs();
LogsItems.Visibility = Visibility.Visible;
@@ -218,7 +218,7 @@ private void ShowTerms(object sender, MouseButtonEventArgs e) {
Process.Start(new ProcessStartInfo("https://netfoundry.io/terms") { UseShellExecute = true });
}
private void ShowFeedback(object sender, MouseButtonEventArgs e) {
- ServiceClient.Client client = (ServiceClient.Client)Application.Current.Properties["ServiceClient"];
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress("ziti-support@netfoundry.io");
mailMessage.Subject = "Ziti Support";
diff --git a/DesktopEdge/MainWindow.xaml.cs b/DesktopEdge/MainWindow.xaml.cs
index 07387ee49..a4cbe8205 100644
--- a/DesktopEdge/MainWindow.xaml.cs
+++ b/DesktopEdge/MainWindow.xaml.cs
@@ -4,13 +4,13 @@
using System.Windows.Input;
using System.IO;
using ZitiDesktopEdge.Models;
-using ZitiDesktopEdge.ServiceClient;
+using ZitiDesktopEdge.DataStructures;
using System.ServiceProcess;
using System.Linq;
using System.Diagnostics;
using System.Windows.Controls;
using System.Drawing;
-
+using ZitiDesktopEdge.ServiceClient;
namespace ZitiDesktopEdge {
@@ -23,7 +23,7 @@ public partial class MainWindow:Window {
public string Position = "Bottom";
private DateTime _startDate;
private System.Windows.Forms.Timer _timer;
- private Client serviceClient = null;
+ private DataClient serviceClient = null;
private bool _isAttached = true;
private bool _isServiceInError = false;
private int _right = 75;
@@ -150,7 +150,7 @@ private void UpdateServiceView() {
private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
// add a new service client
- serviceClient = new Client();
+ serviceClient = new DataClient();
serviceClient.OnClientConnected += ServiceClient_OnClientConnected;
serviceClient.OnClientDisconnected += ServiceClient_OnClientDisconnected;
serviceClient.OnIdentityEvent += ServiceClient_OnIdentityEvent;
@@ -289,7 +289,7 @@ private void ServiceClient_OnTunnelStatusEvent(object sender, TunnelStatusEvent
Application.Current.Properties.Add("CurrentTunnelStatus", e.Status);
e.Status.Dump(Console.Out);
this.Dispatcher.Invoke(() => {
- if(e.ApiVersion != Client.EXPECTED_API_VERSION) {
+ if(e.ApiVersion != DataClient.EXPECTED_API_VERSION) {
SetCantDisplay("Version mismatch!", "The version of the Service is not compatible");
return;
}
@@ -518,7 +518,7 @@ private void AddIdentity(object sender, MouseButtonEventArgs e) {
try {
Identity createdId = serviceClient.AddIdentity(System.IO.Path.GetFileName(jwtDialog.FileName), false, fileContent);
- ServiceClient.Client client = (ServiceClient.Client)Application.Current.Properties["ServiceClient"];
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
client.IdentityOnOff(createdId.FingerPrint, true);
if (createdId != null) {
diff --git a/DesktopEdge/Models/ZitiIdentity.cs b/DesktopEdge/Models/ZitiIdentity.cs
index 187066f86..81ae0cd55 100644
--- a/DesktopEdge/Models/ZitiIdentity.cs
+++ b/DesktopEdge/Models/ZitiIdentity.cs
@@ -30,7 +30,7 @@ public ZitiIdentity(string Name, string ControllerUrl, bool IsEnabled, List
-// This code was generated by a tool.
-// Runtime Version:4.0.30319.42000
-//
-// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
-//
-//------------------------------------------------------------------------------
-
-namespace Ziti.Desktop.Edge.Properties {
-
-
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")]
- internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
-
- private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
-
- public static Settings Default {
- get {
- return defaultInstance;
- }
- }
- }
-}
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace Ziti.Desktop.Edge.Properties {
+
+
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default {
+ get {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/DesktopEdge/Views/ItemRenderers/IdentityItem.xaml.cs b/DesktopEdge/Views/ItemRenderers/IdentityItem.xaml.cs
index eeda5c57d..ab55ea10b 100644
--- a/DesktopEdge/Views/ItemRenderers/IdentityItem.xaml.cs
+++ b/DesktopEdge/Views/ItemRenderers/IdentityItem.xaml.cs
@@ -13,7 +13,8 @@
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZitiDesktopEdge.Models;
-
+using ZitiDesktopEdge.ServiceClient;
+
namespace ZitiDesktopEdge {
///
/// User Control to list Identities and give status
@@ -56,15 +57,15 @@ private void ToggleIdentity(bool on) {
if (OnStatusChanged != null) {
OnStatusChanged(on);
}
- ServiceClient.Client client = (ServiceClient.Client)Application.Current.Properties["ServiceClient"];
- ServiceClient.Identity id = client.IdentityOnOff(_identity.Fingerprint, on);
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
+ DataStructures.Identity id = client.IdentityOnOff(_identity.Fingerprint, on);
this.Identity.IsEnabled = on;
if (on) {
ToggleStatus.Content = "ENABLED";
} else {
ToggleStatus.Content = "DISABLED";
}
- } catch (ServiceClient.ServiceException se) {
+ } catch (DataStructures.ServiceException se) {
MessageBox.Show(se.AdditionalInfo, se.Message);
} catch (Exception ex) {
MessageBox.Show("Error", ex.Message);
diff --git a/DesktopEdge/ZitiDesktopEdge.csproj b/DesktopEdge/ZitiDesktopEdge.csproj
index 188d44eda..88fec2a3d 100644
--- a/DesktopEdge/ZitiDesktopEdge.csproj
+++ b/DesktopEdge/ZitiDesktopEdge.csproj
@@ -8,7 +8,7 @@
WinExe
Ziti.Desktop.Edge
ZitiDesktopEdge
- v4.7.2
+ v4.8
512
{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
4
@@ -94,8 +94,16 @@
+
+ ..\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
+
diff --git a/ZitiDesktopEdge.Client/ServiceClient/DataStructures.cs b/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs
similarity index 93%
rename from ZitiDesktopEdge.Client/ServiceClient/DataStructures.cs
rename to ZitiDesktopEdge.Client/DataStructures/DataStructures.cs
index bc2b7e1a5..ae02f49c8 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/DataStructures.cs
+++ b/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs
@@ -5,8 +5,17 @@
/// These classes represent the data structures that are passed back and forth
/// between the service and the client.
///
-namespace ZitiDesktopEdge.ServiceClient
-{
+namespace ZitiDesktopEdge.DataStructures {
+ public enum LogLevelEnum {
+ FATAL = 0,
+ ERROR = 1,
+ WARN = 2,
+ INFO = 3,
+ DEBUG = 4,
+ TRACE = 5,
+ VERBOSE = 6,
+ }
+
public class SvcResponse
{
public int Code { get; set; }
diff --git a/ZitiDesktopEdge.Client/Server/IPCServer.cs b/ZitiDesktopEdge.Client/Server/IPCServer.cs
new file mode 100644
index 000000000..c91319965
--- /dev/null
+++ b/ZitiDesktopEdge.Client/Server/IPCServer.cs
@@ -0,0 +1,108 @@
+using System;
+using System.Threading.Tasks;
+using System.IO;
+using System.IO.Pipes;
+using System.Security.Principal;
+using System.Security.AccessControl;
+
+using Newtonsoft.Json;
+using NLog;
+
+using ZitiDesktopEdge.DataStructures;
+
+namespace ZitiDesktopEdge.Server {
+ public class IPCServer {
+ public static string PipeName = @"OpenZiti\tunneler\monitoripc";
+
+ private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+ private static int BUFFER_SIZE = 16 * 1024;
+
+ private JsonSerializer serializer = new JsonSerializer() { Formatting = Formatting.None };
+
+ /*
+ InteractivelyLoggedInUser = "(A;;GRGW;;;IU)" //generic read/write. We will want to tune this to a specific group but that is not working with Windows 10 home at the moment
+ System = "(A;;FA;;;SY)"
+ BuiltinAdmins = "(A;;FA;;;BA)"
+ LocalService = "(A;;FA;;;LS)"
+ */
+ private string pipeName;
+ public IPCServer() {
+ this.pipeName = IPCServer.PipeName;
+ }
+
+ async public Task acceptAsync() {
+ int idx = 0;
+
+ PipeSecurity pipeSecurity = new PipeSecurity();
+ var id = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
+
+ // Allow AuthenticatedUserSid read and write access to the pipe.
+ pipeSecurity.SetAccessRule(new PipeAccessRule(id, PipeAccessRights.ReadWrite, AccessControlType.Allow));
+
+ while (true) {
+ var namedPipeServer = new NamedPipeServerStream(
+ pipeName,
+ PipeDirection.InOut,
+ NamedPipeServerStream.MaxAllowedServerInstances,
+ PipeTransmissionMode.Byte,
+ PipeOptions.Asynchronous,
+ BUFFER_SIZE,
+ BUFFER_SIZE,
+ pipeSecurity );
+
+ await namedPipeServer.WaitForConnectionAsync();
+ _ = Task.Run(async ()=>{
+ await handleClientAsync(namedPipeServer);
+ idx--;
+ Logger.Info("Total clients now at: {0}", idx);
+ });
+ }
+ }
+
+ async public Task handleClientAsync(NamedPipeServerStream ss) {
+ using (ss) {
+ try {
+ StreamReader reader = new StreamReader(ss);
+ StreamWriter writer = new StreamWriter(ss);
+
+ string line = await reader.ReadLineAsync();
+
+ while (line != null) {
+ await processMessage(line, writer);
+ line = await reader.ReadLineAsync();
+ }
+
+ Logger.Info("reading from pipe is complete");
+ } catch(Exception e) {
+ Logger.Error(e, "Unexpected erorr when reading from or writing to a client pipe.");
+ }
+ }
+ }
+
+ async public Task processMessage(string msg, StreamWriter writer) {
+ Logger.Debug("message received: {0}", msg);
+ try {
+ ServiceFunction func = serializer.Deserialize(new JsonTextReader(new StringReader(msg)));
+ Logger.Info("function: {0}", func.Function);
+ switch (func.Function) {
+ case "stop":
+ ServiceActions.StopService();
+ break;
+ case "start":
+ ServiceActions.StartService();
+ break;
+ case "status":
+ msg = ServiceActions.ServiceStatus();
+ break;
+ default:
+ Logger.Error("UNKNOWN ACTION received: {0}", func.Function);
+ break;
+ }
+ } catch (Exception e) {
+ Logger.Error(e, "Unexpected erorr in processMessage!");
+ }
+ await writer.WriteLineAsync(msg);
+ await writer.FlushAsync();
+ }
+ }
+}
diff --git a/ZitiDesktopEdge.Client/Server/ServiceActions.cs b/ZitiDesktopEdge.Client/Server/ServiceActions.cs
new file mode 100644
index 000000000..b995467c7
--- /dev/null
+++ b/ZitiDesktopEdge.Client/Server/ServiceActions.cs
@@ -0,0 +1,30 @@
+using System.ServiceProcess;
+
+using NLog;
+
+namespace ZitiDesktopEdge.Server {
+ internal static class ServiceActions {
+ private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+
+
+ private static ServiceController sc = new ServiceController("ziti");
+ public static string ServiceStatus() {
+ var status = sc.Status;
+ return status.ToString();
+ }
+
+ public static string StartService() {
+ Logger.Info("request to start ziti service received... processing...");
+ sc.Start();
+ Logger.Info("request to start ziti service received... complete...");
+ return ServiceStatus();
+ }
+
+ public static string StopService() {
+ Logger.Info("request to stop ziti service received... processing...");
+ sc.Start();
+ Logger.Info("request to stop ziti service received... complete...");
+ return ServiceStatus();
+ }
+ }
+}
diff --git a/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs b/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
new file mode 100644
index 000000000..3e1fc7bc8
--- /dev/null
+++ b/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
@@ -0,0 +1,10 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ZitiDesktopEdge.Server {
+ class AbstractClient {
+ }
+}
diff --git a/ZitiDesktopEdge.Client/ServiceClient/ClientImpl.cs b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
similarity index 92%
rename from ZitiDesktopEdge.Client/ServiceClient/ClientImpl.cs
rename to ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
index 38ecef697..883df63d1 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/ClientImpl.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
@@ -1,17 +1,17 @@
using System;
-using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Security.Principal;
using System.Security.AccessControl;
-
-using Newtonsoft.Json;
using System.Threading;
using System.Threading.Tasks;
+using Newtonsoft.Json;
using NLog;
+using ZitiDesktopEdge.DataStructures;
+
///
/// The implementation will abstract away the setup of the communication to
/// the service. This implementation will communicate to the service over a
@@ -23,18 +23,7 @@
///
namespace ZitiDesktopEdge.ServiceClient
{
- public enum LogLevelEnum
- {
- FATAL = 0,
- ERROR = 1,
- WARN = 2,
- INFO = 3,
- DEBUG = 4,
- TRACE = 5,
- VERBOSE = 6,
- }
-
- public class Client {
+ public class DataClient {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public const int EXPECTED_API_VERSION = 1;
@@ -47,6 +36,8 @@ public class Client {
public event EventHandler
-
-
+
+
+
+
+
diff --git a/ZitiDesktopEdge.sln b/ZitiDesktopEdge.sln
index 3edaa021d..8167e22a5 100644
--- a/ZitiDesktopEdge.sln
+++ b/ZitiDesktopEdge.sln
@@ -11,10 +11,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
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
+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
@@ -27,6 +27,11 @@ Global
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
+ Releases|Any CPU = Releases|Any CPU
+ Releases|ARM = Releases|ARM
+ Releases|ARM64 = Releases|ARM64
+ Releases|x64 = Releases|x64
+ Releases|x86 = Releases|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FA4291EA-A97E-4854-959F-91EE7B330B37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@@ -49,26 +54,16 @@ Global
{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
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|Any CPU.ActiveCfg = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|Any CPU.Build.0 = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|ARM.ActiveCfg = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|ARM.Build.0 = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|ARM64.ActiveCfg = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|ARM64.Build.0 = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|x64.ActiveCfg = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|x64.Build.0 = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|x86.ActiveCfg = Releases|Any CPU
+ {FA4291EA-A97E-4854-959F-91EE7B330B37}.Releases|x86.Build.0 = Releases|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
@@ -89,6 +84,46 @@ Global
{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
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|Any CPU.ActiveCfg = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|Any CPU.Build.0 = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|ARM.ActiveCfg = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|ARM.Build.0 = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|ARM64.ActiveCfg = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|ARM64.Build.0 = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|x64.ActiveCfg = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|x64.Build.0 = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|x86.ActiveCfg = Release|Any CPU
+ {26B30979-99B5-4102-BD0B-129BEDFF0057}.Releases|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
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|Any CPU.ActiveCfg = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|Any CPU.Build.0 = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|ARM.ActiveCfg = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|ARM.Build.0 = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|ARM64.ActiveCfg = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|ARM64.Build.0 = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|x64.ActiveCfg = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|x64.Build.0 = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|x86.ActiveCfg = Releases|Any CPU
+ {9AB81609-F5DD-40A6-87B5-F3279D48514D}.Releases|x86.Build.0 = Releases|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/ZitiUpdateService/Program.cs b/ZitiUpdateService/Program.cs
index 53a18ec01..da4f2c952 100644
--- a/ZitiUpdateService/Program.cs
+++ b/ZitiUpdateService/Program.cs
@@ -1,14 +1,16 @@
-using System;
-using System.IO;
+using System.IO;
+using System.Linq;
using System.Reflection;
-using System.ServiceProcess;
+using System.Security.Cryptography.X509Certificates;
+
using NLog;
using NLog.Config;
using NLog.Targets;
+using ZitiDesktopEdge.Server;
+
namespace ZitiUpdateService {
static class Program {
- private static string PipeName = @"OpenZiti\tunneler\ipc";
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
@@ -45,7 +47,7 @@ static void Main() {
}
Logger.Info("service started - logger initialized");
- IPC.IPCServer svr = new IPC.IPCServer(PipeName);
+ IPCServer svr = new IPCServer();
svr.acceptAsync().Wait();
UpdateService updateSvc = new UpdateService();
diff --git a/ZitiUpdateService/UpdateCheckers.cs b/ZitiUpdateService/UpdateCheckers.cs
index f3ccff0c8..296d0c261 100644
--- a/ZitiUpdateService/UpdateCheckers.cs
+++ b/ZitiUpdateService/UpdateCheckers.cs
@@ -1,9 +1,9 @@
using System;
using System.IO;
using System.Net;
-using System.Text.Json;
using NLog;
+using Newtonsoft.Json.Linq;
namespace ZitiUpdateService {
internal class GithubCheck : IUpdateCheck {
@@ -40,8 +40,8 @@ public bool IsUpdateAvailable(Version current) {
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream());
string result = streamReader.ReadToEnd();
- JsonDocument json = JsonDocument.Parse(result);
- string serverVersion = json.RootElement.GetProperty("tag_name").GetString() + ".0";
+ JObject json = JObject.Parse(result);
+ string serverVersion = json.Property("tag_name").Value.ToString() + ".0";
Version published = new Version(serverVersion);
int compare = current.CompareTo(published);
@@ -54,12 +54,11 @@ public bool IsUpdateAvailable(Version current) {
Logger.Debug("current version {0} is the same as the latest release {0}", current, published);
return false;
}
-
- foreach (JsonElement asset in json.RootElement.GetProperty("assets").EnumerateArray()) {
- downloadUrl = asset.GetProperty("browser_download_url").GetString();
- if (downloadUrl != null) {
- break;
- }
+
+ 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) {
diff --git a/ZitiUpdateService/UpdateService.cs b/ZitiUpdateService/UpdateService.cs
index 96c43d7ef..df9478d59 100644
--- a/ZitiUpdateService/UpdateService.cs
+++ b/ZitiUpdateService/UpdateService.cs
@@ -7,12 +7,17 @@
using System.Configuration;
using System.Threading.Tasks;
-using ZitiDesktopEdge.ServiceClient;
+using ZitiDesktopEdge.DataStructures;
using NLog;
using System.Reflection;
+using System.Security.Cryptography.X509Certificates;
+using ZitiDesktopEdge.ServiceClient;
namespace ZitiUpdateService {
public partial class UpdateService : ServiceBase {
+ private static string[] expected_hashes = new string[] { "39636E9F5E80308DE370C914CE8112876ECF4E0C" };
+ private static string[] expected_subject = new string[] { @"CN=""NetFoundry, Inc."", O=""NetFoundry, Inc."", L=Herndon, S=Virginia, C=US" };
+
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private Timer _updateTimer = new Timer();
@@ -21,7 +26,7 @@ public partial class UpdateService : ServiceBase {
private string _logDirectory = "";
private string _versionType = "latest";
- private Client svc = new Client();
+ private DataClient svc = new DataClient();
private bool running = false;
ServiceController controller;
@@ -93,10 +98,7 @@ private void CheckUpdate(object sender, ElapsedEventArgs e) {
inUpdateCheck = true; //simple semaphone
try {
Logger.Debug("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";
- }
+ string updateUrl = "https://api.github.com/repos/openziti/desktop-edge-win/releases/latest"; //hardcoded on purpose
IUpdateCheck check = new GithubCheck(updateUrl);
//IUpdateCheck check = new FilesystemCheck();
@@ -126,10 +128,36 @@ private void CheckUpdate(object sender, ElapsedEventArgs e) {
Logger.Info("copying update package complete");
}
+ string fileDestination = Path.Combine(updateFolder, filename);
+
+ // check digital signature
+ var signer = X509Certificate.CreateFromSignedFile(fileDestination);
+ /* keep these commented out lines - just in case we need all the certs from the file use this
+ var coll = new X509Certificate2Collection();
+ coll.Import(filePath);
+ */
+
+ var subject = signer.Subject;
+ if (!expected_subject.Contains(subject)) {
+ Logger.Error("the file downloaded uses a subject that is unknown! the installation will not proceed. [subject:{0}]", subject);
+ return;
+
+ } else {
+ Logger.Info("the file downloaded uses a known subject. installation and can proceed. [subject:{0}]", subject);
+ }
+
+ var hash = signer.GetCertHashString();
+ if (!expected_hashes.Contains(hash)) {
+ Logger.Error("the file downloaded is signed by an unknown certificate! the installation will not proceed. [hash:{0}]", hash);
+ return;
+
+ } else {
+ Logger.Info("the file downloaded is signed by a known certificate. installation and can proceed. [subject:{0}]", subject);
+ }
+
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");
@@ -180,7 +208,7 @@ private static void Svc_OnClientConnected(object sender, object e) {
}
private static void Svc_OnClientDisconnected(object sender, object e) {
- Client svc = (Client)sender;
+ DataClient svc = (DataClient)sender;
if (svc.CleanShutdown) {
//then this is fine and expected - the service is shutting down
Logger.Info("client disconnected due to clean service shutdown");
diff --git a/ZitiUpdateService/ZitiUpdateService.csproj b/ZitiUpdateService/ZitiUpdateService.csproj
index 81fa115f1..52a43b791 100644
--- a/ZitiUpdateService/ZitiUpdateService.csproj
+++ b/ZitiUpdateService/ZitiUpdateService.csproj
@@ -8,7 +8,7 @@
WinExe
ZitiUpdateService
ZitiUpdateService
- v4.7.2
+ v4.8
512
true
true
@@ -28,7 +28,6 @@
false
true
true
-
AnyCPU
@@ -75,16 +74,13 @@
bin\Releases\
-
- ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll
+
+ ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll
..\packages\NLog.4.7.5\lib\net45\NLog.dll
-
- ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll
-
@@ -94,27 +90,8 @@
..\packages\Microsoft.PowerShell.5.ReferenceAssemblies.1.1.0\lib\net4\System.Management.Automation.dll
-
- ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll
-
-
-
- ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll
-
-
- ..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll
-
-
- ..\packages\System.Text.Encodings.Web.5.0.0\lib\net461\System.Text.Encodings.Web.dll
-
-
- ..\packages\System.Text.Json.5.0.0\lib\net461\System.Text.Json.dll
-
-
- ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll
-
@@ -126,7 +103,6 @@
-
diff --git a/ZitiUpdateService/packages.config b/ZitiUpdateService/packages.config
index 86e6bcc16..bba3d6dad 100644
--- a/ZitiUpdateService/packages.config
+++ b/ZitiUpdateService/packages.config
@@ -1,14 +1,6 @@
-
+
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/service/ziti-tunnel/service/pkg-vars.go b/service/ziti-tunnel/service/pkg-vars.go
index 039dc0e2c..4d915515f 100644
--- a/service/ziti-tunnel/service/pkg-vars.go
+++ b/service/ziti-tunnel/service/pkg-vars.go
@@ -25,7 +25,7 @@ import (
"time"
)
var Version dto.ServiceVersion
-var pipeBase = `\\.\pipe\NetFoundry\tunneler\`
+var pipeBase = `\\.\pipe\OpenZiti\ziti\`
var rts = RuntimeState{
ids: make(map[string]*Id),
From 51ad1d314fd0749b8be683d54dacaa9e41eb6e19 Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Thu, 19 Nov 2020 12:59:22 -0500
Subject: [PATCH 07/25] wip - services converted. pipes renamed. initial
bigbutton works. moving to UI work
---
DesktopEdge/MainWindow.xaml | 648 +++++++++---------
DesktopEdge/MainWindow.xaml.cs | 144 ++--
ZitiDesktopEdge.Client/Server/IPCServer.cs | 139 +++-
.../Server/ServiceActions.cs | 5 +-
.../ServiceClient/AbstractClient.cs | 255 ++++++-
.../ServiceClient/DataClient.cs | 383 +++--------
.../ServiceClient/MonitorClient.cs | 456 +-----------
.../ZitiDesktopEdge.Client.csproj | 2 +-
ZitiUpdateService/Program.cs | 8 +-
ZitiUpdateService/UpdateService.cs | 2 +-
10 files changed, 888 insertions(+), 1154 deletions(-)
diff --git a/DesktopEdge/MainWindow.xaml b/DesktopEdge/MainWindow.xaml
index 42c7e442e..6ac248011 100644
--- a/DesktopEdge/MainWindow.xaml
+++ b/DesktopEdge/MainWindow.xaml
@@ -1,323 +1,325 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/DesktopEdge/MainWindow.xaml.cs b/DesktopEdge/MainWindow.xaml.cs
index a4cbe8205..70bdb1b40 100644
--- a/DesktopEdge/MainWindow.xaml.cs
+++ b/DesktopEdge/MainWindow.xaml.cs
@@ -3,13 +3,15 @@
using System.Windows;
using System.Windows.Input;
using System.IO;
-using ZitiDesktopEdge.Models;
-using ZitiDesktopEdge.DataStructures;
using System.ServiceProcess;
using System.Linq;
using System.Diagnostics;
using System.Windows.Controls;
using System.Drawing;
+using System.Threading.Tasks;
+
+using ZitiDesktopEdge.Models;
+using ZitiDesktopEdge.DataStructures;
using ZitiDesktopEdge.ServiceClient;
namespace ZitiDesktopEdge {
@@ -17,13 +19,14 @@ namespace ZitiDesktopEdge {
///
/// Interaction logic for MainWindow.xaml
///
- public partial class MainWindow:Window {
+ public partial class MainWindow : Window {
public System.Windows.Forms.NotifyIcon notifyIcon;
public string Position = "Bottom";
private DateTime _startDate;
- private System.Windows.Forms.Timer _timer;
+ private System.Windows.Forms.Timer _tunnelUptimeTimer;
private DataClient serviceClient = null;
+ MonitorClient monitorClient = null;
private bool _isAttached = true;
private bool _isServiceInError = false;
private int _right = 75;
@@ -38,27 +41,15 @@ private List identities {
}
}
- private void LaunchOrInstall() {
- ServiceController ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName=="ziti");
- if (ctl==null) {
- SetCantDisplay();
- } else {
- if (ctl.Status!=ServiceControllerStatus.Running) {
- try {
- ctl.Start();
- } catch (Exception e) {
- UILog.Log(e.Message);
- SetCantDisplay();
- }
- }
- }
- }
-
private List services = new List();
public MainWindow() {
InitializeComponent();
- App.Current.MainWindow.WindowState = WindowState.Normal;
+ #if DEBUG
+ System.Environment.SetEnvironmentVariable("ZITI_EXTENDED_DEBUG", "true");
+ #endif
+
+ App.Current.MainWindow.WindowState = WindowState.Normal;
App.Current.MainWindow.Closing += MainWindow_Closing;
App.Current.MainWindow.Deactivated += MainWindow_Deactivated;
App.Current.MainWindow.Activated += MainWindow_Activated;
@@ -69,8 +60,6 @@ public MainWindow() {
IdentityMenu.OnDetach += OnDetach;
MainMenu.OnDetach += OnDetach;
- LaunchOrInstall();
-
SetNotifyIcon("white");
}
@@ -108,7 +97,7 @@ private void MainWindow_Closing(object sender, System.ComponentModel.CancelEvent
notifyIcon.Icon.Dispose();
notifyIcon.Dispose();
}
-
+
private void SetCantDisplay(string msg, string detailMessage) {
NoServiceView.Visibility = Visibility.Visible;
ErrorMsg.Content = msg;
@@ -117,8 +106,8 @@ private void SetCantDisplay(string msg, string detailMessage) {
_isServiceInError = true;
UpdateServiceView();
}
- private void SetCantDisplay() {
- SetCantDisplay("Service Not Started", "Start the Ziti Tunnel Service to get started");
+ private void SetCantDisplay(string msg) {
+ SetCantDisplay("Service Not Started", msg);
}
private void TargetNotifyIcon_Click(object sender, EventArgs e) {
@@ -158,6 +147,10 @@ private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
serviceClient.OnServiceEvent += ServiceClient_OnServiceEvent;
serviceClient.OnTunnelStatusEvent += ServiceClient_OnTunnelStatusEvent;
+ monitorClient = new MonitorClient();
+ monitorClient.OnClientConnected += MonitorClient_OnClientConnected;
+ monitorClient.OnTunnelStatusEvent += MonitorClient_OnTunnelStatusEvent;
+
Application.Current.Properties.Add("ServiceClient", serviceClient);
Application.Current.Properties.Add("Identities", new List());
MainMenu.OnAttachmentChange += AttachmentChanged;
@@ -166,16 +159,31 @@ private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
try {
serviceClient.Connect();
- //var s = serviceClient.GetStatus();
- //LoadStatusFromService(s.Status);
+ serviceClient.WaitForConnectionAsync().Wait();
} catch /*ignored for now (Exception ex) */{
- SetCantDisplay();
+ SetCantDisplay("Start the Ziti Tunnel Service to continue");
serviceClient.Reconnect();
}
+
+ try {
+ monitorClient.Connect();
+ monitorClient.WaitForConnectionAsync().Wait();
+ } catch /*ignored for now (Exception ex) */{
+ monitorClient.Reconnect();
+ }
+
IdentityMenu.OnForgot += IdentityForgotten;
Placement();
}
+ private void MonitorClient_OnTunnelStatusEvent(object sender, TunnelStatusEvent e) {
+ Debug.WriteLine("MonitorClient_OnTunnelStatusEvent");
+ }
+
+ private void MonitorClient_OnClientConnected(object sender, object e) {
+ Debug.WriteLine("MonitorClient_OnClientConnected");
+ }
+
private void LogLevelChanged(string level) {
serviceClient.SetLogLevel(level);
}
@@ -198,7 +206,7 @@ private void ServiceClient_OnClientConnected(object sender, object e) {
private void ServiceClient_OnClientDisconnected(object sender, object e) {
this.Dispatcher.Invoke(() => {
IdList.Children.Clear();
- SetCantDisplay();
+ SetCantDisplay("Start the Ziti Tunnel Service to continue");
});
}
@@ -256,7 +264,7 @@ public void SetSpeed(decimal bytes, Label speed, Label speedLabel) {
private void ServiceClient_OnServiceEvent(object sender, ServiceEvent e) {
if (e == null) return;
-
+
Debug.WriteLine($"==== ServiceEvent : action:{e.Action} fingerprint:{e.Fingerprint} name:{e.Service.Name} ");
this.Dispatcher.Invoke(() => {
var found = identities.Find(id => id.Fingerprint == e.Fingerprint);
@@ -289,10 +297,10 @@ private void ServiceClient_OnTunnelStatusEvent(object sender, TunnelStatusEvent
Application.Current.Properties.Add("CurrentTunnelStatus", e.Status);
e.Status.Dump(Console.Out);
this.Dispatcher.Invoke(() => {
- if(e.ApiVersion != DataClient.EXPECTED_API_VERSION) {
+ if (e.ApiVersion != DataClient.EXPECTED_API_VERSION) {
SetCantDisplay("Version mismatch!", "The version of the Service is not compatible");
return;
- }
+ }
this.MainMenu.LogLevel = e.Status.LogLevel;
InitializeTimer((int)e.Status.Duration);
LoadStatusFromService(e.Status);
@@ -362,7 +370,7 @@ private void LoadStatusFromService(TunnelStatus status) {
}
LoadIdentities(true);
} else {
- SetCantDisplay();
+ SetCantDisplay("Start the Ziti Tunnel Service to continue");
}
}
@@ -387,14 +395,14 @@ private void SetNotifyIcon(string iconPrefix) {
private void LoadIdentities(Boolean repaint) {
IdList.Children.Clear();
IdList.Height = 0;
- IdList.MaxHeight = _maxHeight-520;
+ IdList.MaxHeight = _maxHeight - 520;
ZitiIdentity[] ids = identities.ToArray();
double height = 490 + (ids.Length * 60);
if (height > _maxHeight) height = _maxHeight;
this.Height = height;
- IdentityMenu.SetHeight(this.Height-160);
+ IdentityMenu.SetHeight(this.Height - 160);
bool isActive = false;
- for (int i=0; i9)?hours.ToString():"0"+hours;
- var minutesString = (minutes>9)? minutes.ToString():"0"+minutes;
- var secondsString = (seconds>9) ? seconds.ToString() : "0"+seconds;
- ConnectedTime.Content = hoursString+":"+minutesString+":"+secondsString;
+ var hoursString = (hours > 9) ? hours.ToString() : "0" + hours;
+ var minutesString = (minutes > 9) ? minutes.ToString() : "0" + minutes;
+ var secondsString = (seconds > 9) ? seconds.ToString() : "0" + seconds;
+ ConnectedTime.Content = hoursString + ":" + minutesString + ":" + secondsString;
}
private void InitializeTimer(int millisAgoStarted) {
- _startDate = DateTime.Now.Subtract(new TimeSpan(0,0,0,0, millisAgoStarted));
- _timer = new System.Windows.Forms.Timer();
- _timer.Interval = 100;
- _timer.Tick += OnTimedEvent;
- _timer.Enabled = true;
- _timer.Start();
+ _startDate = DateTime.Now.Subtract(new TimeSpan(0, 0, 0, 0, millisAgoStarted));
+ _tunnelUptimeTimer = new System.Windows.Forms.Timer();
+ _tunnelUptimeTimer.Interval = 100;
+ _tunnelUptimeTimer.Tick += OnTimedEvent;
+ _tunnelUptimeTimer.Enabled = true;
+ _tunnelUptimeTimer.Start();
}
private void Connect(object sender, RoutedEventArgs e) {
if (!_isServiceInError) {
@@ -582,7 +589,7 @@ private void DoConnect() {
item.RefreshUI();
}
} catch (ServiceException se) {
- ShowError("Error Occurred", se.Message+" "+se.AdditionalInfo);
+ ShowError("Error Occurred", se.Message + " " + se.AdditionalInfo);
} catch (Exception ex) {
ShowError("Unexpected Error", "Code 3:" + ex.Message);
}
@@ -592,7 +599,7 @@ private void Disconnect(object sender, RoutedEventArgs e) {
ShowLoad();
try {
ConnectedTime.Content = "00:00:00";
- _timer.Stop();
+ _tunnelUptimeTimer.Stop();
serviceClient.SetTunnelState(false);
SetNotifyIcon("white");
ConnectButton.Visibility = Visibility.Visible;
@@ -666,18 +673,15 @@ private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
Placement();
}
- private void Button_Click(object sender, RoutedEventArgs e)
- {
+ private void Button_Click(object sender, RoutedEventArgs e) {
serviceClient.SetLogLevel(NextLevel());
}
int cur = 0;
LogLevelEnum[] levels = new LogLevelEnum[] { LogLevelEnum.FATAL, LogLevelEnum.ERROR, LogLevelEnum.WARN, LogLevelEnum.INFO, LogLevelEnum.DEBUG, LogLevelEnum.TRACE, LogLevelEnum.VERBOSE };
- public LogLevelEnum NextLevel()
- {
+ public LogLevelEnum NextLevel() {
cur++;
- if (cur > 6)
- {
+ if (cur > 6) {
cur = 0;
}
return levels[cur];
@@ -686,5 +690,21 @@ public LogLevelEnum NextLevel()
private void IdList_LayoutUpdated(object sender, EventArgs e) {
Placement();
}
- }
+
+ string action = "stop";
+ async private void Button_Click_1(object sender, RoutedEventArgs e) {
+ if (action == "stop") {
+ action = "start";
+ await monitorClient.StartServicAsync();
+ } else {
+ action = "stop";
+ await monitorClient.StopServicAsync();
+ }
+ Debug.WriteLine("button 1 1 1 1!");
+ }
+ async private void Button_Click_2(object sender, RoutedEventArgs e) {
+ Debug.WriteLine("button 2!");
+ await Task.Delay(10);
+ }
+ }
}
diff --git a/ZitiDesktopEdge.Client/Server/IPCServer.cs b/ZitiDesktopEdge.Client/Server/IPCServer.cs
index c91319965..555eee0eb 100644
--- a/ZitiDesktopEdge.Client/Server/IPCServer.cs
+++ b/ZitiDesktopEdge.Client/Server/IPCServer.cs
@@ -12,54 +12,114 @@
namespace ZitiDesktopEdge.Server {
public class IPCServer {
- public static string PipeName = @"OpenZiti\tunneler\monitoripc";
+ public const string PipeName = @"OpenZiti\ziti-monitor\ipc";
+ public const string EventPipeName = @"OpenZiti\ziti-monitor\events";
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static int BUFFER_SIZE = 16 * 1024;
private JsonSerializer serializer = new JsonSerializer() { Formatting = Formatting.None };
-
- /*
- InteractivelyLoggedInUser = "(A;;GRGW;;;IU)" //generic read/write. We will want to tune this to a specific group but that is not working with Windows 10 home at the moment
- System = "(A;;FA;;;SY)"
- BuiltinAdmins = "(A;;FA;;;BA)"
- LocalService = "(A;;FA;;;LS)"
- */
- private string pipeName;
+ private string ipcPipeName;
+ private string eventPipeName;
public IPCServer() {
- this.pipeName = IPCServer.PipeName;
+ this.ipcPipeName = IPCServer.PipeName;
+ this.eventPipeName = IPCServer.EventPipeName;
}
- async public Task acceptAsync() {
+ async public Task startIpcServer() {
int idx = 0;
+ // Allow AuthenticatedUserSid read and write access to the pipe.
PipeSecurity pipeSecurity = new PipeSecurity();
var id = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
+ pipeSecurity.SetAccessRule(new PipeAccessRule(id, PipeAccessRights.CreateNewInstance | PipeAccessRights.ReadWrite, AccessControlType.Allow));
+
+ while (true) {
+ try {
+ var ipcPipeServer = new NamedPipeServerStream(
+ ipcPipeName,
+ PipeDirection.InOut,
+ NamedPipeServerStream.MaxAllowedServerInstances,
+ PipeTransmissionMode.Byte,
+ PipeOptions.Asynchronous | PipeOptions.WriteThrough,
+ BUFFER_SIZE,
+ BUFFER_SIZE,
+ pipeSecurity);
+
+ await ipcPipeServer.WaitForConnectionAsync();
+ Logger.Debug("Total ipc clients now at: {0}", ++idx);
+ _ = Task.Run(async () => {
+ try {
+ await handleIpcClientAsync(ipcPipeServer);
+ } catch(Exception icpe) {
+ Logger.Error(icpe, "Unexpected erorr in handleIpcClientAsync");
+ }
+ idx--;
+ Logger.Debug("Total ipc clients now at: {0}", idx);
+ });
+ } catch (Exception pe) {
+ Logger.Error(pe, "Unexpected erorr when connecting a client pipe.");
+ }
+ }
+ }
+ async public Task startEventsServer() {
+ int idx = 0;
// Allow AuthenticatedUserSid read and write access to the pipe.
- pipeSecurity.SetAccessRule(new PipeAccessRule(id, PipeAccessRights.ReadWrite, AccessControlType.Allow));
+ PipeSecurity pipeSecurity = new PipeSecurity();
+ var id = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
+ pipeSecurity.SetAccessRule(new PipeAccessRule(id, PipeAccessRights.CreateNewInstance | PipeAccessRights.ReadWrite, AccessControlType.Allow));
while (true) {
- var namedPipeServer = new NamedPipeServerStream(
- pipeName,
- PipeDirection.InOut,
- NamedPipeServerStream.MaxAllowedServerInstances,
- PipeTransmissionMode.Byte,
- PipeOptions.Asynchronous,
- BUFFER_SIZE,
- BUFFER_SIZE,
- pipeSecurity );
-
- await namedPipeServer.WaitForConnectionAsync();
- _ = Task.Run(async ()=>{
- await handleClientAsync(namedPipeServer);
- idx--;
- Logger.Info("Total clients now at: {0}", idx);
- });
+ try {
+ var eventPipeServer = new NamedPipeServerStream(
+ eventPipeName,
+ PipeDirection.InOut,
+ NamedPipeServerStream.MaxAllowedServerInstances,
+ PipeTransmissionMode.Byte,
+ PipeOptions.Asynchronous | PipeOptions.WriteThrough,
+ BUFFER_SIZE,
+ BUFFER_SIZE,
+ pipeSecurity);
+
+ await eventPipeServer.WaitForConnectionAsync();
+ Logger.Debug("Total event clients now at: {0}", ++idx);
+ _ = Task.Run(async () => {
+ try {
+ await handleEventClientAsync(eventPipeServer);
+ } catch (Exception icpe) {
+ Logger.Error(icpe, "Unexpected erorr in handleEventClientAsync");
+ }
+ idx--;
+ Logger.Debug("Total event clients now at: {0}", idx);
+ });
+ } catch (Exception pe) {
+ Logger.Error(pe, "Unexpected erorr when connecting a client pipe.");
+ }
+ }
+ }
+
+ async public Task handleIpcClientAsync(NamedPipeServerStream ss) {
+ using (ss) {
+ try {
+ StreamReader reader = new StreamReader(ss);
+ StreamWriter writer = new StreamWriter(ss);
+
+ string line = await reader.ReadLineAsync();
+
+ while (line != null) {
+ await processMessage(line, writer);
+ line = await reader.ReadLineAsync();
+ }
+
+ Logger.Debug("handleIpcClientAsync is complete");
+ } catch (Exception e) {
+ Logger.Error(e, "Unexpected erorr when reading from or writing to a client pipe.");
+ }
}
}
- async public Task handleClientAsync(NamedPipeServerStream ss) {
+ async public Task handleEventClientAsync(NamedPipeServerStream ss) {
using (ss) {
try {
StreamReader reader = new StreamReader(ss);
@@ -72,8 +132,8 @@ async public Task handleClientAsync(NamedPipeServerStream ss) {
line = await reader.ReadLineAsync();
}
- Logger.Info("reading from pipe is complete");
- } catch(Exception e) {
+ Logger.Debug("handleEventClientAsync is complete");
+ } catch (Exception e) {
Logger.Error(e, "Unexpected erorr when reading from or writing to a client pipe.");
}
}
@@ -81,27 +141,34 @@ async public Task handleClientAsync(NamedPipeServerStream ss) {
async public Task processMessage(string msg, StreamWriter writer) {
Logger.Debug("message received: {0}", msg);
+ SvcResponse r = new SvcResponse();
try {
ServiceFunction func = serializer.Deserialize(new JsonTextReader(new StringReader(msg)));
Logger.Info("function: {0}", func.Function);
switch (func.Function) {
case "stop":
- ServiceActions.StopService();
+ r.Message = ServiceActions.StopService();
break;
case "start":
- ServiceActions.StartService();
+ r.Message = ServiceActions.StartService();
break;
case "status":
- msg = ServiceActions.ServiceStatus();
+ r.Message = ServiceActions.ServiceStatus();
break;
default:
- Logger.Error("UNKNOWN ACTION received: {0}", func.Function);
+ msg = string.Format("UNKNOWN ACTION received: {0}", func.Function);
+ Logger.Error(msg);
+ r.Code = -3;
+ r.Error = msg;
break;
}
} catch (Exception e) {
Logger.Error(e, "Unexpected erorr in processMessage!");
+ r.Code = -2;
+ r.Error = e.Message + ":" + e?.InnerException?.Message;
}
- await writer.WriteLineAsync(msg);
+ Logger.Info("Returning status: {0}", r.Message);
+ await writer.WriteLineAsync(JsonConvert.SerializeObject(r));
await writer.FlushAsync();
}
}
diff --git a/ZitiDesktopEdge.Client/Server/ServiceActions.cs b/ZitiDesktopEdge.Client/Server/ServiceActions.cs
index b995467c7..ae02b5731 100644
--- a/ZitiDesktopEdge.Client/Server/ServiceActions.cs
+++ b/ZitiDesktopEdge.Client/Server/ServiceActions.cs
@@ -5,7 +5,6 @@
namespace ZitiDesktopEdge.Server {
internal static class ServiceActions {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
-
private static ServiceController sc = new ServiceController("ziti");
public static string ServiceStatus() {
@@ -16,13 +15,15 @@ public static string ServiceStatus() {
public static string StartService() {
Logger.Info("request to start ziti service received... processing...");
sc.Start();
+ sc.WaitForStatus(ServiceControllerStatus.Running, new System.TimeSpan(0,0,30));
Logger.Info("request to start ziti service received... complete...");
return ServiceStatus();
}
public static string StopService() {
Logger.Info("request to stop ziti service received... processing...");
- sc.Start();
+ sc.Stop();
+ sc.WaitForStatus(ServiceControllerStatus.Stopped, new System.TimeSpan(0, 0, 30));
Logger.Info("request to stop ziti service received... complete...");
return ServiceStatus();
}
diff --git a/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs b/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
index 3e1fc7bc8..fa0750b9a 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
@@ -1,10 +1,257 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.IO;
+using System.IO.Pipes;
+using System.Security.Principal;
+using System.Security.AccessControl;
+using System.Threading;
using System.Threading.Tasks;
-namespace ZitiDesktopEdge.Server {
- class AbstractClient {
+using Newtonsoft.Json;
+using NLog;
+
+
+using ZitiDesktopEdge.DataStructures;
+
+namespace ZitiDesktopEdge.ServiceClient {
+ public abstract class AbstractClient {
+ private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+
+ private bool _extendedDebug = false; //set ZITI_EXTENDED_DEBUG env var to true if you want to diagnose issues with the service comms
+
+ protected NamedPipeClientStream pipeClient = null;
+ protected NamedPipeClientStream eventClient = null;
+ protected StreamWriter ipcWriter = null;
+ protected StreamReader ipcReader = null;
+ protected abstract void ConnectPipes();
+ protected abstract void ProcessLine(string line);
+
+ protected const string localPipeServer = ".";
+ protected const int ServiceConnectTimeout = 500;
+
+ protected object namedPipeSyncLock = new object();
+
+ protected JsonSerializer serializer = new JsonSerializer() { Formatting = Formatting.None };
+
+ protected virtual void ClientConnected(object e) {
+ Connected = true;
+ Reconnecting = false;
+ CleanShutdown = false;
+ Logger.Debug("CleanShutdown set to false");
+
+ ipcWriter = new StreamWriter(pipeClient);
+ ipcReader = new StreamReader(pipeClient);
+ Task.Run(() => { //hack for now until it's async...
+ try {
+ StreamReader eventReader = new StreamReader(eventClient);
+ while (true) {
+ if (eventReader.EndOfStream) {
+ break;
+ }
+
+ waitForLine(eventReader);
+ }
+ } catch (Exception ex) {
+ Logger.Debug("unepxected error: " + ex.ToString());
+ }
+
+ // since this thread is always sitting waiting to read
+ // it should be the only one triggering this event
+ ClientDisconnected(null);
+ });
+ OnClientConnected?.Invoke(this, e);
+ }
+
+ protected virtual void ClientDisconnected(object e) {
+ Reconnect();
+ Connected = false;
+ OnClientDisconnected?.Invoke(this, e);
+ }
+
+ protected virtual void ShutdownEvent(StatusEvent e) {
+ Logger.Debug("Clean shutdown detected from ziti");
+ CleanShutdown = true;
+ OnShutdownEvent?.Invoke(this, e);
+ }
+
+ async protected Task sendAsync(object objToSend) {
+ bool retried = false;
+ while (true) {
+ try {
+ string toSend = JsonConvert.SerializeObject(objToSend, Formatting.None);
+
+ if (toSend?.Trim() != null) {
+ debugServiceCommunication("=============== sending message =============== ");
+ debugServiceCommunication(toSend);
+ await ipcWriter.WriteAsync(toSend);
+ await ipcWriter.WriteAsync('\n');
+ debugServiceCommunication("=============== flushing message =============== ");
+ await ipcWriter.FlushAsync();
+ debugServiceCommunication("=============== sent message =============== ");
+ debugServiceCommunication("");
+ debugServiceCommunication("");
+ } else {
+ Logger.Debug("NOT sending empty object??? " + objToSend?.ToString());
+ }
+ break;
+ } catch (IOException ioe) {
+ //almost certainly a problem with the pipe - recreate the pipe... try one more time.
+ //setupPipe();
+ if (retried) {
+ //we tried - throw the error...
+ throw ioe;
+ } else {
+ retried = true; //fall back through to the while and try again
+ }
+ } catch (Exception ex) {
+ //if this fails it's usually because the writer is null/invalid. throwing IOException
+ //will trigger the pipe to rebuild
+ throw new IOException("Unexpected error when sending data to service. " + ex.Message);
+ }
+ }
+ }
+ protected void waitForLine(StreamReader reader) {
+ try {
+ string respAsString = readMessageAsync(reader).Result;
+ ProcessLine(respAsString);
+
+ } catch (Exception e) {
+ Logger.Debug(e.Message);
+ }
+ }
+
+ public event EventHandler OnClientConnected = null;
+ public event EventHandler OnClientDisconnected;
+ public event EventHandler OnShutdownEvent;
+
+ public bool Reconnecting { get; set; }
+ public bool Connected { get; set; }
+ public bool CleanShutdown { get; set; }
+
+ public AbstractClient() {
+ try {
+ string extDebugEnv = Environment.GetEnvironmentVariable("ZITI_EXTENDED_DEBUG");
+ if (extDebugEnv != null) {
+ if (bool.Parse(extDebugEnv)) {
+ _extendedDebug = true;
+ }
+ }
+ } catch (Exception ex) {
+ Logger.Debug("EXCEPTION IN CLIENT CONNECT: " + ex.Message);
+ //if this happens - enter retry mode...
+ Reconnect();
+ }
+ }
+
+ public void Connect() {
+ //establish the named pipe to the service
+ ConnectPipes();
+ }
+
+ public void Reconnect() {
+ if (Reconnecting) {
+ Logger.Debug("Already in reconnect mode.");
+ return;
+ } else {
+ Reconnecting = true;
+ }
+
+ Task.Run(() => {
+ Logger.Info("service is down. attempting to connect to service...");
+
+ DateTime reconnectStart = DateTime.Now;
+ DateTime logAgainAfter = reconnectStart + TimeSpan.FromSeconds(1);
+
+ while (true) {
+ try {
+ Thread.Sleep(2500);
+ ConnectPipes();
+
+ if (Connected) {
+ Logger.Debug("Connected to the service - exiting reconect loop");
+ Connected = true;
+ Reconnecting = false;
+ return;
+ } else {
+ //ClientDisconnected(null);
+ }
+ } catch {
+ var now = DateTime.Now;
+ if (now > logAgainAfter) {
+ Logger.Debug("Reconnect failed. Trying again...");
+ var duration = now - reconnectStart;
+ if (duration > TimeSpan.FromHours(1)) {
+ Logger.Info("reconnect has not completed and has been running for {0} hours", duration.TotalHours);
+ logAgainAfter += TimeSpan.FromHours(1);
+ } else if (duration > TimeSpan.FromMinutes(1)) {
+ Logger.Info("reconnect has not completed and has been running for {0} minutes", duration.TotalMinutes);
+ logAgainAfter += TimeSpan.FromMinutes(1);
+ } else {
+ logAgainAfter += TimeSpan.FromSeconds(1);
+ }
+ }
+ }
+ }
+ });
+ }
+
+ private void debugServiceCommunication(string msg) {
+ if (_extendedDebug) {
+ Logger.Debug(msg);
+ System.Diagnostics.Debug.WriteLine(msg);
+ }
+ }
+
+
+ async public Task readMessageAsync(StreamReader reader) {
+ try {
+ if (reader.EndOfStream) {
+ throw new ServiceException("the pipe has closed", 0, "end of stream reached");
+ }
+ int emptyCount = 1; //just a stop gap in case something crazy happens in the communication
+
+ debugServiceCommunication("=============== reading message =============== " + emptyCount);
+ string respAsString = await reader.ReadLineAsync();
+ debugServiceCommunication(respAsString);
+ debugServiceCommunication("=============== read message =============== " + emptyCount);
+ while (string.IsNullOrEmpty(respAsString?.Trim())) {
+ if (reader.EndOfStream) {
+ throw new Exception("the pipe has closed");
+ }
+ debugServiceCommunication("Received empty payload - continuing to read until a payload is received");
+ //now how'd that happen...
+ debugServiceCommunication("=============== reading message =============== " + emptyCount);
+ respAsString = await reader.ReadLineAsync();
+ debugServiceCommunication(respAsString);
+ debugServiceCommunication("=============== read message =============== " + emptyCount);
+ emptyCount++;
+ if (emptyCount > 5) {
+ Logger.Debug("are we there yet? " + reader.EndOfStream);
+ //that's just too many...
+ //setupPipe();
+ return null;
+ }
+ }
+ debugServiceCommunication("");
+ debugServiceCommunication("");
+ return respAsString;
+ } catch (IOException ioe) {
+ //almost certainly a problem with the pipe
+ Logger.Debug("io error in read: " + ioe.Message);
+ ClientDisconnected(null);
+ throw ioe;
+ } catch (Exception ee) {
+ //almost certainly a problem with the pipe
+ Logger.Debug("unexpected error in read: " + ee.Message);
+ ClientDisconnected(null);
+ throw ee;
+ }
+ }
+
+ async public Task WaitForConnectionAsync() {
+ while (Reconnecting || !Connected) {
+ await Task.Delay(100);
+ }
+ }
}
}
diff --git a/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
index 883df63d1..dc044fe51 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
@@ -21,9 +21,8 @@
/// one or more messages returned.
///
///
-namespace ZitiDesktopEdge.ServiceClient
-{
- public class DataClient {
+namespace ZitiDesktopEdge.ServiceClient {
+ public class DataClient : AbstractClient {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public const int EXPECTED_API_VERSION = 1;
@@ -32,166 +31,62 @@ public class DataClient {
public event EventHandler> OnMetricsEvent;
public event EventHandler OnIdentityEvent;
public event EventHandler OnServiceEvent;
- public event EventHandler OnClientConnected;
- public event EventHandler OnClientDisconnected;
- public event EventHandler OnShutdownEvent;
- private JsonSerializer serializer = new JsonSerializer() { Formatting=Formatting.None};
-
- public bool CleanShutdown { get; set; }
-
- protected virtual void ShutdownEvent(StatusEvent e) {
+ protected override void ShutdownEvent(StatusEvent e) {
Logger.Debug("Clean shutdown detected from ziti");
CleanShutdown = true;
- OnShutdownEvent?.Invoke(this, e);
+ base.ShutdownEvent(e);
}
- protected virtual void TunnelStatusEvent(TunnelStatusEvent e)
- {
+ protected virtual void TunnelStatusEvent(TunnelStatusEvent e) {
OnTunnelStatusEvent?.Invoke(this, e);
}
- protected virtual void MetricsEvent(List e)
- {
+ protected virtual void MetricsEvent(List e) {
OnMetricsEvent?.Invoke(this, e);
}
- protected virtual void IdentityEvent(IdentityEvent e)
- {
+ protected virtual void IdentityEvent(IdentityEvent e) {
OnIdentityEvent?.Invoke(this, e);
}
- protected virtual void ServiceEvent(ServiceEvent e)
- {
+ protected virtual void ServiceEvent(ServiceEvent e) {
OnServiceEvent?.Invoke(this, e);
}
- protected virtual void ClientConnected(object e)
- {
- Connected = true;
- Reconnecting = false;
- CleanShutdown = false;
- Logger.Debug("CleanShutdown set to false");
- OnClientConnected?.Invoke(this, e);
+ protected override void ClientConnected(object e) {
+ base.ClientConnected(e);
}
- protected virtual void ClientDisconnected(object e)
- {
+ protected override void ClientDisconnected(object e) {
Reconnect();
Connected = false;
- OnClientDisconnected?.Invoke(this, e);
+ base.ClientDisconnected(e);
}
- private object namedPipeSyncLock = new object();
const string ipcPipe = @"OpenZiti\ziti\ipc";
const string logPipe = @"OpenZiti\ziti\logs";
const string eventPipe = @"OpenZiti\ziti\events";
- const string localPipeServer = ".";
const PipeDirection inOut = PipeDirection.InOut;
- const int ServiceConnectTimeout = 500;
- NamedPipeClientStream pipeClient = null;
- StreamWriter ipcWriter = null;
- StreamReader ipcReader = null;
-
- NamedPipeClientStream eventClient = null;
-#if DEBUG
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
- public DataClient()
- {
- try
- {
+ public DataClient() {
+ try {
string extDebugEnv = Environment.GetEnvironmentVariable("ZITI_EXTENDED_DEBUG");
- if (extDebugEnv != null)
- {
- if (bool.Parse(extDebugEnv))
- {
+ if (extDebugEnv != null) {
+ if (bool.Parse(extDebugEnv)) {
_extendedDebug = true;
}
}
- }
- catch(Exception ex)
- {
+ } catch (Exception ex) {
Logger.Debug("EXCEPTION IN CLIENT CONNECT: " + ex.Message);
//if this happens - enter retry mode...
Reconnect();
}
}
- public bool Reconnecting { get; set; }
- public bool Connected { get; set; }
-
- public void Connect()
- {
- //establish the named pipe to the service
- setupPipe();
- }
-
- public void WaitForConnection() {
- while(Reconnecting || !Connected) {
- Task.Delay(100).Wait();
- }
- }
-
- public void Reconnect()
- {
- if (Reconnecting)
- {
- Logger.Debug("Already in reconnect mode.");
- return;
- }
- else
- {
- Reconnecting = true;
- }
-
- Task.Run(() => {
- Logger.Info("service is down. attempting to connect to service...");
-
- DateTime reconnectStart = DateTime.Now;
- DateTime logAgainAfter = reconnectStart + TimeSpan.FromSeconds(1);
-
- while (true) {
- try {
- Thread.Sleep(2500);
- pipeClient?.Close();
- eventClient?.Close();
- setupPipe();
-
- if (Connected) {
- Logger.Debug("Connected to the service - exiting reconect loop");
- Connected = true;
- Reconnecting = false;
- return;
- } else {
- //ClientDisconnected(null);
- }
- } catch {
- var now = DateTime.Now;
- if (now > logAgainAfter) {
- Logger.Debug("Reconnect failed. Trying again...");
- var duration = now - reconnectStart;
- if (duration > TimeSpan.FromHours(1)) {
- Logger.Info("reconnect has not completed and has been running for {0} hours", duration.TotalHours);
- logAgainAfter += TimeSpan.FromHours(1);
- } else if (duration > TimeSpan.FromMinutes(1)) {
- Logger.Info("reconnect has not completed and has been running for {0} minutes", duration.TotalMinutes);
- logAgainAfter += TimeSpan.FromMinutes(1);
- } else {
- logAgainAfter += TimeSpan.FromSeconds(1);
- }
- }
- }
- }
- });
- }
-
- PipeSecurity CreateSystemIOPipeSecurity()
- {
+ PipeSecurity CreateSystemIOPipeSecurity() {
PipeSecurity pipeSecurity = new PipeSecurity();
var id = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
@@ -202,62 +97,27 @@ PipeSecurity CreateSystemIOPipeSecurity()
return pipeSecurity;
}
- private void setupPipe()
- {
- lock (namedPipeSyncLock)
- {
+ protected override void ConnectPipes() {//private void setupPipe()
+ lock (namedPipeSyncLock) {
pipeClient = new NamedPipeClientStream(localPipeServer, ipcPipe, inOut);
eventClient = new NamedPipeClientStream(localPipeServer, eventPipe, PipeDirection.In);
- try
- {
+ try {
eventClient.Connect(ServiceConnectTimeout);
pipeClient.Connect(ServiceConnectTimeout);
- ipcWriter = new StreamWriter(pipeClient);
- ipcReader = new StreamReader(pipeClient);
ClientConnected(null);
- }
- catch(Exception ex)
- {
+ } catch (Exception ex) {
throw new ServiceException("Could not connect to the service.", 1, ex.Message);
}
-
- Task.Run(() => { //hack for now until it's async...
- try
- {
- StreamReader eventReader = new StreamReader(eventClient);
- while (true)
- {
- if (eventReader.EndOfStream)
- {
- break;
- }
-
- processEvent(eventReader);
- }
- }
- catch(Exception ex)
- {
- Logger.Debug("unepxected error: " + ex.ToString());
- }
-
- // since this thread is always sitting waiting to read
- // it should be the only one triggering this event
- ClientDisconnected(null);
- });
}
}
- public ZitiTunnelStatus GetStatus()
- {
- try
- {
+ public ZitiTunnelStatus GetStatus() {
+ try {
send(new ServiceFunction() { Function = "Status" });
var rtn = read(ipcReader);
return rtn;
- }
- catch (IOException ioe)
- {
+ } catch (IOException ioe) {
//almost certainly a problem with the pipe - recreate the pipe...
//setupPipe();
throw ioe;
@@ -266,21 +126,16 @@ public ZitiTunnelStatus GetStatus()
ServiceFunction AddIdentityFunction = new ServiceFunction() { Function = "AddIdentity" };
- public Identity AddIdentity(string identityName, bool activate, string jwt)
- {
- try
- {
- Identity id = new Identity
- {
+ public Identity AddIdentity(string identityName, bool activate, string jwt) {
+ try {
+ Identity id = new Identity {
Active = activate,
Name = identityName
};
- NewIdentity newId = new NewIdentity()
- {
+ NewIdentity newId = new NewIdentity() {
Id = id,
- Flags = new EnrollmentFlags()
- {
+ Flags = new EnrollmentFlags() {
JwtString = jwt
}
};
@@ -289,14 +144,11 @@ public Identity AddIdentity(string identityName, bool activate, string jwt)
send(newId);
var resp = read(ipcReader);
Logger.Debug(resp.ToString());
- if(resp.Code != 0)
- {
+ if (resp.Code != 0) {
throw new ServiceException(resp.Message, resp.Code, resp.Error);
}
return resp.Payload;
- }
- catch (IOException)
- {
+ } catch (IOException) {
//almost certainly a problem with the pipe - recreate the pipe...
//setupPipe();
throw;
@@ -304,46 +156,36 @@ public Identity AddIdentity(string identityName, bool activate, string jwt)
}
- public void RemoveIdentity(string fingerPrint)
- {
- if (string.IsNullOrEmpty(fingerPrint))
- {
+ public void RemoveIdentity(string fingerPrint) {
+ if (string.IsNullOrEmpty(fingerPrint)) {
//nothing to do...
return;
}
- try
- {
- FingerprintFunction removeFunction = new FingerprintFunction()
- {
+ try {
+ FingerprintFunction removeFunction = new FingerprintFunction() {
Function = "RemoveIdentity",
Payload = new FingerprintPayload() { Fingerprint = fingerPrint }
};
send(removeFunction);
var r = read(ipcReader);
- }
- catch (IOException ioe)
- {
+ } catch (IOException ioe) {
//almost certainly a problem with the pipe - recreate the pipe...
//setupPipe();
throw ioe;
}
}
- private void checkConnected()
- {
- if (Reconnecting)
- {
+ private void checkConnected() {
+ if (Reconnecting) {
throw new ServiceException("Client is not connected", 2, "Cannot use the client at this time, it is reconnecting");
}
- if (!Connected)
- {
+ if (!Connected) {
throw new ServiceException("Client is not connected", 2, "Cannot use the client at this time, it is not connected");
}
}
- public void SetTunnelState(bool onOff)
- {
+ public void SetTunnelState(bool onOff) {
/*
checkConnected();
try
@@ -360,10 +202,8 @@ public void SetTunnelState(bool onOff)
*/
}
- public string GetLogs()
- {
- try
- {
+ public string GetLogs() {
+ try {
NamedPipeClientStream logClient = new NamedPipeClientStream(localPipeServer, logPipe, PipeDirection.In);
StreamReader logReader = new StreamReader(logClient);
logClient.Connect(ServiceConnectTimeout);
@@ -374,9 +214,7 @@ public string GetLogs()
//todo: fix this :point_up:
content = new System.Text.RegularExpressions.Regex(@"\x1B\[[^@-~]*[@-~]").Replace(content, "");
return content;
- }
- catch
- {
+ } catch {
//almost certainly a problem with the pipe - probably means the service is NOT running
return "Error fetching logs from service. Is it running?";
}
@@ -394,49 +232,37 @@ public void SetLogLevel(string level) {
}
}
- public void SetLogLevel(LogLevelEnum level)
- {
- try
- {
+ public void SetLogLevel(LogLevelEnum level) {
+ try {
send(new SetLogLevelFunction(Enum.GetName(level.GetType(), level)));
SvcResponse resp = read(ipcReader);
return;
- }
- catch (IOException ioe)
- {
+ } catch (IOException ioe) {
//almost certainly a problem with the pipe - recreate the pipe...
//setupPipe();
throw ioe;
}
}
- public Identity IdentityOnOff(string fingerprint, bool onOff)
- {
- try
- {
+ public Identity IdentityOnOff(string fingerprint, bool onOff) {
+ try {
send(new IdentityToggleFunction(fingerprint, onOff));
IdentityResponse idr = read(ipcReader);
return idr.Payload;
- }
- catch (IOException ioe)
- {
+ } catch (IOException ioe) {
//almost certainly a problem with the pipe - recreate the pipe...
//setupPipe();
throw ioe;
}
}
- private void send(object objToSend)
- {
+ private void send(object objToSend) {
bool retried = false;
- while (true)
- {
- try
- {
+ while (true) {
+ try {
string toSend = JsonConvert.SerializeObject(objToSend, Formatting.None);
- if (toSend?.Trim() != null)
- {
+ if (toSend?.Trim() != null) {
debugServiceCommunication("=============== sending message =============== ");
debugServiceCommunication(toSend);
ipcWriter.Write(toSend);
@@ -446,29 +272,20 @@ private void send(object objToSend)
debugServiceCommunication("=============== sent message =============== ");
debugServiceCommunication("");
debugServiceCommunication("");
- }
- else
- {
+ } else {
Logger.Debug("NOT sending empty object??? " + objToSend?.ToString());
}
break;
- }
- catch (IOException ioe)
- {
+ } catch (IOException ioe) {
//almost certainly a problem with the pipe - recreate the pipe... try one more time.
//setupPipe();
- if (retried)
- {
+ if (retried) {
//we tried - throw the error...
throw ioe;
- }
- else
- {
+ } else {
retried = true; //fall back through to the while and try again
}
- }
- catch (Exception ex)
- {
+ } catch (Exception ex) {
//if this fails it's usually because the writer is null/invalid. throwing IOException
//will trigger the pipe to rebuild
throw new IOException("Unexpected error when sending data to service. " + ex.Message);
@@ -476,53 +293,46 @@ private void send(object objToSend)
}
}
- private T read(StreamReader reader) where T : SvcResponse
- {
- string respAsString = readMessage(reader);
-// T resp = JsonSerializer.Deserialize(new JsonStr(respAsString));
+ private T read(StreamReader reader) where T : SvcResponse {
+ string respAsString = readMessageAsync(reader).Result;
+ // T resp = JsonSerializer.Deserialize(new JsonStr(respAsString));
T resp = (T)serializer.Deserialize(new StringReader(respAsString), typeof(T));
return resp;
}
- private void processEvent(StreamReader reader)
- {
- try
- {
- string respAsString = readMessage(reader);
- var jsonReader = new JsonTextReader(new StringReader(respAsString));
- StatusEvent evt = serializer.Deserialize(jsonReader);
+ protected override void ProcessLine(string line) {//private void processEvent(StreamReader reader)
+ try {
+ string respAsString = line;
+ var jsonReaderEvt = new JsonTextReader(new StringReader(respAsString));
+ StatusEvent evt = serializer.Deserialize(jsonReaderEvt);
+ var jsonReader = new JsonTextReader(new StringReader(respAsString));
- switch (evt.Op)
- {
+ switch (evt.Op) {
case "metrics":
MetricsEvent m = serializer.Deserialize(jsonReader);
- if (m != null)
- {
+ if (m != null) {
MetricsEvent(m.Identities);
}
break;
case "status":
TunnelStatusEvent se = serializer.Deserialize(jsonReader);
- if (se != null)
- {
+ if (se != null) {
TunnelStatusEvent(se);
}
break;
case "identity":
IdentityEvent id = serializer.Deserialize(jsonReader);
- if (id != null)
- {
+ if (id != null) {
IdentityEvent(id);
}
break;
case "service":
ServiceEvent svc = serializer.Deserialize(jsonReader);
- if (svc != null)
- {
+ if (svc != null) {
ServiceEvent(svc);
}
break;
@@ -533,30 +343,24 @@ private void processEvent(StreamReader reader)
Logger.Debug("unexpected operation! " + evt.Op);
break;
}
- } catch (Exception e)
- {
+ } catch (Exception e) {
Logger.Debug(e.Message);
}
}
- public string readMessage(StreamReader reader)
- {
- try
- {
- if (reader.EndOfStream)
- {
+ public string readMessage(StreamReader reader) {
+ try {
+ if (reader.EndOfStream) {
throw new ServiceException("the pipe has closed", 0, "end of stream reached");
}
int emptyCount = 1; //just a stop gap in case something crazy happens in the communication
- debugServiceCommunication( "=============== reading message =============== " + emptyCount);
+ debugServiceCommunication("=============== reading message =============== " + emptyCount);
string respAsString = reader.ReadLine();
debugServiceCommunication(respAsString);
debugServiceCommunication("=============== read message =============== " + emptyCount);
- while (string.IsNullOrEmpty(respAsString?.Trim()))
- {
- if (reader.EndOfStream)
- {
+ while (string.IsNullOrEmpty(respAsString?.Trim())) {
+ if (reader.EndOfStream) {
throw new Exception("the pipe has closed");
}
debugServiceCommunication("Received empty payload - continuing to read until a payload is received");
@@ -566,8 +370,7 @@ public string readMessage(StreamReader reader)
debugServiceCommunication(respAsString);
debugServiceCommunication("=============== read message =============== " + emptyCount);
emptyCount++;
- if (emptyCount > 5)
- {
+ if (emptyCount > 5) {
Logger.Debug("are we there yet? " + reader.EndOfStream);
//that's just too many...
//setupPipe();
@@ -577,16 +380,12 @@ public string readMessage(StreamReader reader)
debugServiceCommunication("");
debugServiceCommunication("");
return respAsString;
- }
- catch (IOException ioe)
- {
+ } catch (IOException ioe) {
//almost certainly a problem with the pipe
Logger.Debug("io error in read: " + ioe.Message);
ClientDisconnected(null);
throw ioe;
- }
- catch (Exception ee)
- {
+ } catch (Exception ee) {
//almost certainly a problem with the pipe
Logger.Debug("unexpected error in read: " + ee.Message);
ClientDisconnected(null);
@@ -594,23 +393,17 @@ public string readMessage(StreamReader reader)
}
}
- private void debugServiceCommunication(string msg)
- {
- if (_extendedDebug)
- {
+ private void debugServiceCommunication(string msg) {
+ if (_extendedDebug) {
Logger.Debug(msg);
}
}
- public ZitiTunnelStatus debug()
- {
- try
- {
+ public ZitiTunnelStatus debug() {
+ try {
send(new ServiceFunction() { Function = "Debug" });
var rtn = read(ipcReader);
return rtn;
- }
- catch (IOException ioe)
- {
+ } catch (IOException ioe) {
//almost certainly a problem with the pipe - recreate the pipe...
//setupPipe();
throw ioe;
diff --git a/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs b/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
index e0b78e059..6ffcdc807 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
@@ -11,10 +11,11 @@
using NLog;
using ZitiDesktopEdge.DataStructures;
+using ZitiDesktopEdge.Server;
///
/// The implementation will abstract away the setup of the communication to
-/// the service. This implementation will communicate to the service over a
+/// the monitor service. This implementation will communicate to the service over a
/// a NamedPipe.
///
/// All communication is effectively serial - one or more messages sent and
@@ -22,470 +23,69 @@
///
///
namespace ZitiDesktopEdge.ServiceClient {
- public class MonitorClient {
+ public class MonitorClient : AbstractClient {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public const int EXPECTED_API_VERSION = 1;
public event EventHandler OnTunnelStatusEvent;
- public event EventHandler> OnMetricsEvent;
- public event EventHandler OnIdentityEvent;
- public event EventHandler OnServiceEvent;
- public event EventHandler OnClientConnected;
- public event EventHandler OnClientDisconnected;
- public event EventHandler OnShutdownEvent;
-
- private JsonSerializer serializer = new JsonSerializer() { Formatting = Formatting.None };
-
- public bool CleanShutdown { get; set; }
-
- protected virtual void ShutdownEvent(StatusEvent e) {
- Logger.Debug("Clean shutdown detected from ziti");
- CleanShutdown = true;
- OnShutdownEvent?.Invoke(this, e);
- }
protected virtual void TunnelStatusEvent(TunnelStatusEvent e) {
OnTunnelStatusEvent?.Invoke(this, e);
}
- protected virtual void MetricsEvent(List e) {
- OnMetricsEvent?.Invoke(this, e);
- }
-
- protected virtual void IdentityEvent(IdentityEvent e) {
- OnIdentityEvent?.Invoke(this, e);
- }
-
- protected virtual void ServiceEvent(ServiceEvent e) {
- OnServiceEvent?.Invoke(this, e);
- }
-
- protected virtual void ClientConnected(object e) {
- Connected = true;
- Reconnecting = false;
- CleanShutdown = false;
- Logger.Debug("CleanShutdown set to false");
- OnClientConnected?.Invoke(this, e);
- }
-
- protected virtual void ClientDisconnected(object e) {
- Reconnect();
- Connected = false;
- OnClientDisconnected?.Invoke(this, e);
- }
-
- private object namedPipeSyncLock = new object();
- const string ipcPipe = @"OpenZiti\ziti-monitor\ipc";
- const string logPipe = @"OpenZiti\ziti-monitor\logs";
- const string eventPipe = @"OpenZiti\ziti-monitor\events";
- const string localPipeServer = ".";
const PipeDirection inOut = PipeDirection.InOut;
- const int ServiceConnectTimeout = 500;
-
- NamedPipeClientStream pipeClient = null;
- StreamWriter writer = null;
- StreamReader ipcReader = null;
-
- NamedPipeClientStream eventClient = null;
-#if DEBUG
- 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
public MonitorClient() {
- try {
- string extDebugEnv = Environment.GetEnvironmentVariable("ZITI_EXTENDED_DEBUG");
- if (extDebugEnv != null) {
- if (bool.Parse(extDebugEnv)) {
- _extendedDebug = true;
- }
- }
- } catch (Exception ex) {
- Logger.Debug("EXCEPTION IN CLIENT CONNECT: " + ex.Message);
- //if this happens - enter retry mode...
- Reconnect();
- }
- }
-
- public bool Reconnecting { get; set; }
- public bool Connected { get; set; }
-
- public void Connect() {
- //establish the named pipe to the service
- setupPipe();
- }
-
- public void WaitForConnection() {
- while (Reconnecting || !Connected) {
- Task.Delay(100).Wait();
- }
}
- public void Reconnect() {
- if (Reconnecting) {
- Logger.Debug("Already in reconnect mode.");
- return;
- } else {
- Reconnecting = true;
- }
-
- Task.Run(() => {
- Logger.Info("service is down. attempting to connect to service...");
-
- DateTime reconnectStart = DateTime.Now;
- DateTime logAgainAfter = reconnectStart + TimeSpan.FromSeconds(1);
-
- while (true) {
- try {
- Thread.Sleep(2500);
- pipeClient?.Close();
- eventClient?.Close();
- setupPipe();
-
- if (Connected) {
- Logger.Debug("Connected to the service - exiting reconect loop");
- Connected = true;
- Reconnecting = false;
- return;
- } else {
- //ClientDisconnected(null);
- }
- } catch {
- var now = DateTime.Now;
- if (now > logAgainAfter) {
- Logger.Debug("Reconnect failed. Trying again...");
- var duration = now - reconnectStart;
- if (duration > TimeSpan.FromHours(1)) {
- Logger.Info("reconnect has not completed and has been running for {0} hours", duration.TotalHours);
- logAgainAfter += TimeSpan.FromHours(1);
- } else if (duration > TimeSpan.FromMinutes(1)) {
- Logger.Info("reconnect has not completed and has been running for {0} minutes", duration.TotalMinutes);
- logAgainAfter += TimeSpan.FromMinutes(1);
- } else {
- logAgainAfter += TimeSpan.FromSeconds(1);
- }
- }
- }
- }
- });
- }
-
- private void setupPipe() {
+ protected override void ConnectPipes() {
lock (namedPipeSyncLock) {
- pipeClient = new NamedPipeClientStream(localPipeServer, ipcPipe, inOut);
- eventClient = new NamedPipeClientStream(localPipeServer, eventPipe, PipeDirection.In);
+ pipeClient = new NamedPipeClientStream(localPipeServer, IPCServer.PipeName, inOut);
+ eventClient = new NamedPipeClientStream(localPipeServer, IPCServer.EventPipeName, PipeDirection.In);
try {
eventClient.Connect(ServiceConnectTimeout);
pipeClient.Connect(ServiceConnectTimeout);
- writer = new StreamWriter(pipeClient);
- ipcReader = new StreamReader(pipeClient);
ClientConnected(null);
} catch (Exception ex) {
throw new ServiceException("Could not connect to the service.", 1, ex.Message);
}
-
- Task.Run(() => { //hack for now until it's async...
- try {
- StreamReader eventReader = new StreamReader(eventClient);
- while (true) {
- if (eventReader.EndOfStream) {
- break;
- }
-
- processEvent(eventReader);
- }
- } catch (Exception ex) {
- Logger.Debug("unepxected error: " + ex.ToString());
- }
-
- // since this thread is always sitting waiting to read
- // it should be the only one triggering this event
- ClientDisconnected(null);
- });
- }
- }
-
- public ZitiTunnelStatus GetStatus() {
- try {
- send(new ServiceFunction() { Function = "Status" });
- var rtn = read(ipcReader);
- return rtn;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe - recreate the pipe...
- //setupPipe();
- throw ioe;
- }
- }
-
- ServiceFunction AddIdentityFunction = new ServiceFunction() { Function = "AddIdentity" };
-
- public Identity AddIdentity(string identityName, bool activate, string jwt) {
- try {
- Identity id = new Identity {
- Active = activate,
- Name = identityName
- };
-
- NewIdentity newId = new NewIdentity() {
- Id = id,
- Flags = new EnrollmentFlags() {
- JwtString = jwt
- }
- };
-
- send(AddIdentityFunction);
- send(newId);
- var resp = read(ipcReader);
- Logger.Debug(resp.ToString());
- if (resp.Code != 0) {
- throw new ServiceException(resp.Message, resp.Code, resp.Error);
- }
- return resp.Payload;
- } catch (IOException) {
- //almost certainly a problem with the pipe - recreate the pipe...
- //setupPipe();
- throw;
}
}
+ protected override void ProcessLine(string line) {
+ var jsonReader = new JsonTextReader(new StringReader(line));
+ StatusEvent evt = serializer.Deserialize(jsonReader);
+ switch (evt.Op) {
+ case "status":
+ TunnelStatusEvent se = serializer.Deserialize(jsonReader);
- public void RemoveIdentity(string fingerPrint) {
- if (string.IsNullOrEmpty(fingerPrint)) {
- //nothing to do...
- return;
- }
-
- try {
- FingerprintFunction removeFunction = new FingerprintFunction() {
- Function = "RemoveIdentity",
- Payload = new FingerprintPayload() { Fingerprint = fingerPrint }
- };
- send(removeFunction);
- var r = read(ipcReader);
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe - recreate the pipe...
- //setupPipe();
- throw ioe;
- }
- }
-
- private void checkConnected() {
- if (Reconnecting) {
- throw new ServiceException("Client is not connected", 2, "Cannot use the client at this time, it is reconnecting");
- }
- if (!Connected) {
- throw new ServiceException("Client is not connected", 2, "Cannot use the client at this time, it is not connected");
- }
- }
-
- public string GetLogs() {
- try {
- NamedPipeClientStream logClient = new NamedPipeClientStream(localPipeServer, logPipe, PipeDirection.In);
- StreamReader logReader = new StreamReader(logClient);
- logClient.Connect(ServiceConnectTimeout);
-
- string content = logReader.ReadToEnd();
-
- //ugly hack to turn ansi escaping to not... _bleck_
- //todo: fix this :point_up:
- content = new System.Text.RegularExpressions.Regex(@"\x1B\[[^@-~]*[@-~]").Replace(content, "");
- return content;
- } catch {
- //almost certainly a problem with the pipe - probably means the service is NOT running
- return "Error fetching logs from service. Is it running?";
- }
- }
-
- public void SetLogLevel(string level) {
- try {
- send(new SetLogLevelFunction(level));
- SvcResponse resp = read(ipcReader);
- return;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe - recreate the pipe...
- //setupPipe();
- throw ioe;
- }
- }
-
- public void SetLogLevel(LogLevelEnum level) {
- try {
- send(new SetLogLevelFunction(Enum.GetName(level.GetType(), level)));
- SvcResponse resp = read(ipcReader);
- return;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe - recreate the pipe...
- //setupPipe();
- throw ioe;
- }
- }
-
- public Identity IdentityOnOff(string fingerprint, bool onOff) {
- try {
- send(new IdentityToggleFunction(fingerprint, onOff));
- IdentityResponse idr = read(ipcReader);
- return idr.Payload;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe - recreate the pipe...
- //setupPipe();
- throw ioe;
- }
- }
-
- private void send(object objToSend) {
- bool retried = false;
- while (true) {
- try {
- string toSend = JsonConvert.SerializeObject(objToSend, Formatting.None);
-
- if (toSend?.Trim() != null) {
- debugServiceCommunication("=============== sending message =============== ");
- debugServiceCommunication(toSend);
- writer.Write(toSend);
- writer.Write('\n');
- debugServiceCommunication("=============== flushing message =============== ");
- writer.Flush();
- debugServiceCommunication("=============== sent message =============== ");
- debugServiceCommunication("");
- debugServiceCommunication("");
- } else {
- Logger.Debug("NOT sending empty object??? " + objToSend?.ToString());
+ if (se != null) {
+ TunnelStatusEvent(se);
}
break;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe - recreate the pipe... try one more time.
- //setupPipe();
- if (retried) {
- //we tried - throw the error...
- throw ioe;
- } else {
- retried = true; //fall back through to the while and try again
- }
- } catch (Exception ex) {
- //if this fails it's usually because the writer is null/invalid. throwing IOException
- //will trigger the pipe to rebuild
- throw new IOException("Unexpected error when sending data to service. " + ex.Message);
- }
- }
- }
-
- private T read(StreamReader reader) where T : SvcResponse {
- string respAsString = readMessage(reader);
- // T resp = JsonSerializer.Deserialize(new JsonStr(respAsString));
- T resp = (T)serializer.Deserialize(new StringReader(respAsString), typeof(T));
- return resp;
- }
-
- private void processEvent(StreamReader reader) {
- try {
- string respAsString = readMessage(reader);
- var jsonReader = new JsonTextReader(new StringReader(respAsString));
- StatusEvent evt = serializer.Deserialize(jsonReader);
-
- switch (evt.Op) {
- case "metrics":
- MetricsEvent m = serializer.Deserialize(jsonReader);
-
- if (m != null) {
- MetricsEvent(m.Identities);
- }
- break;
- case "status":
- TunnelStatusEvent se = serializer.Deserialize(jsonReader);
-
- if (se != null) {
- TunnelStatusEvent(se);
- }
- break;
- case "identity":
- IdentityEvent id = serializer.Deserialize(jsonReader);
-
- if (id != null) {
- IdentityEvent(id);
- }
- break;
- case "service":
- ServiceEvent svc = serializer.Deserialize(jsonReader);
+ case "shutdown":
- if (svc != null) {
- ServiceEvent(svc);
- }
- break;
- case "shutdown":
-
- break;
- default:
- Logger.Debug("unexpected operation! " + evt.Op);
- break;
- }
- } catch (Exception e) {
- Logger.Debug(e.Message);
+ break;
+ default:
+ Logger.Debug("unexpected operation! " + evt.Op);
+ break;
}
}
- public string readMessage(StreamReader reader) {
- try {
- if (reader.EndOfStream) {
- throw new ServiceException("the pipe has closed", 0, "end of stream reached");
- }
- int emptyCount = 1; //just a stop gap in case something crazy happens in the communication
-
- debugServiceCommunication("=============== reading message =============== " + emptyCount);
- string respAsString = reader.ReadLine();
- debugServiceCommunication(respAsString);
- debugServiceCommunication("=============== read message =============== " + emptyCount);
- while (string.IsNullOrEmpty(respAsString?.Trim())) {
- if (reader.EndOfStream) {
- throw new Exception("the pipe has closed");
- }
- debugServiceCommunication("Received empty payload - continuing to read until a payload is received");
- //now how'd that happen...
- debugServiceCommunication("=============== reading message =============== " + emptyCount);
- respAsString = reader.ReadLine();
- debugServiceCommunication(respAsString);
- debugServiceCommunication("=============== read message =============== " + emptyCount);
- emptyCount++;
- if (emptyCount > 5) {
- Logger.Debug("are we there yet? " + reader.EndOfStream);
- //that's just too many...
- //setupPipe();
- return null;
- }
- }
- debugServiceCommunication("");
- debugServiceCommunication("");
- return respAsString;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe
- Logger.Debug("io error in read: " + ioe.Message);
- ClientDisconnected(null);
- throw ioe;
- } catch (Exception ee) {
- //almost certainly a problem with the pipe
- Logger.Debug("unexpected error in read: " + ee.Message);
- ClientDisconnected(null);
- throw ee;
- }
+ async public Task SendServiceFunctionAsync(ServiceFunction f) {
+ await sendAsync(f);
+
+ var resp = await readMessageAsync(ipcReader);
+ Logger.Info("RESPONSE: {0}", resp);
}
- private void debugServiceCommunication(string msg) {
- if (_extendedDebug) {
- Logger.Debug(msg);
- }
+ async public Task StopServicAsync() {
+ await SendServiceFunctionAsync(new ServiceFunction() { Function = "stop" });
}
- public ZitiTunnelStatus debug() {
- try {
- send(new ServiceFunction() { Function = "Debug" });
- var rtn = read(ipcReader);
- return rtn;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe - recreate the pipe...
- //setupPipe();
- throw ioe;
- }
+ async public Task StartServicAsync() {
+ await SendServiceFunctionAsync(new ServiceFunction() { Function = "start" });
}
}
}
\ No newline at end of file
diff --git a/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj b/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj
index 983e90eae..a26c7afb3 100644
--- a/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj
+++ b/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj
@@ -33,7 +33,6 @@
..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll
- True
..\packages\NLog.4.7.5\lib\net45\NLog.dll
@@ -55,6 +54,7 @@
+
diff --git a/ZitiUpdateService/Program.cs b/ZitiUpdateService/Program.cs
index da4f2c952..8d996dfc4 100644
--- a/ZitiUpdateService/Program.cs
+++ b/ZitiUpdateService/Program.cs
@@ -2,6 +2,7 @@
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
+using System.Threading.Tasks;
using NLog;
using NLog.Config;
@@ -18,7 +19,7 @@ static class Program {
/// The main entry point for the application.
///
static void Main() {
- //Environment.SetEnvironmentVariable("ZITI_EXTENDED_DEBUG", "true");
+ System.Environment.SetEnvironmentVariable("ZITI_EXTENDED_DEBUG", "true");
var curdir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string nlogFile = Path.Combine(curdir, "ziti-monitor-log.config");
@@ -48,11 +49,14 @@ static void Main() {
Logger.Info("service started - logger initialized");
IPCServer svr = new IPCServer();
- svr.acceptAsync().Wait();
+ Task ipcServer = svr.startIpcServer();
+ Task eventServer = svr.startEventsServer();
+ Task.WaitAll(ipcServer, eventServer);
UpdateService updateSvc = new UpdateService();
updateSvc.AutoLog = true;
#if DEBUG
+ Logger.Error("================================");
updateSvc.Debug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
diff --git a/ZitiUpdateService/UpdateService.cs b/ZitiUpdateService/UpdateService.cs
index df9478d59..91f86ece4 100644
--- a/ZitiUpdateService/UpdateService.cs
+++ b/ZitiUpdateService/UpdateService.cs
@@ -90,7 +90,7 @@ private void SetupServiceWatchers() {
svc.Reconnect();
}
- svc.WaitForConnection();
+ svc.WaitForConnectionAsync().Wait();
}
private void CheckUpdate(object sender, ElapsedEventArgs e) {
From 1f6c9d9749f58707022b581382859aba717b8f9e Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Thu, 19 Nov 2020 17:32:26 -0500
Subject: [PATCH 08/25] wip - debugging communication/restarts/etc
---
DesktopEdge/IdentityDetails.xaml.cs | 330 +++++++++---------
DesktopEdge/MainMenu.xaml.cs | 6 +
DesktopEdge/MainWindow.xaml.cs | 76 ++--
.../Views/ItemRenderers/IdentityItem.xaml.cs | 176 +++++-----
DesktopEdge/ZitiDesktopEdge.csproj | 7 +
DesktopEdge/packages.config | 1 +
ZitiDesktopEdge.Client/Server/IPCServer.cs | 1 +
.../ServiceClient/AbstractClient.cs | 26 +-
.../ServiceClient/DataClient.cs | 138 ++------
.../ServiceClient/MonitorClient.cs | 23 +-
ZitiUpdateService/UpdateService.cs | 2 +-
11 files changed, 376 insertions(+), 410 deletions(-)
diff --git a/DesktopEdge/IdentityDetails.xaml.cs b/DesktopEdge/IdentityDetails.xaml.cs
index 41819a801..292c74827 100644
--- a/DesktopEdge/IdentityDetails.xaml.cs
+++ b/DesktopEdge/IdentityDetails.xaml.cs
@@ -1,167 +1,167 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using System.Windows.Shapes;
-using ZitiDesktopEdge.Models;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using ZitiDesktopEdge.Models;
using ZitiDesktopEdge.ServiceClient;
-namespace ZitiDesktopEdge {
- ///
- /// Interaction logic for IdentityDetails.xaml
- ///
- public partial class IdentityDetails:UserControl {
-
- private bool _isAttached = true;
- public delegate void Forgot(ZitiIdentity forgotten);
- public event Forgot OnForgot;
- public delegate void ErrorOccurred(string message);
- public event ErrorOccurred OnError;
- public delegate void Detched(MouseButtonEventArgs e);
- public event Detched OnDetach;
- public double MainHeight = 500;
-
- private List identities {
- get {
- return (List)Application.Current.Properties["Identities"];
- }
- }
-
- private ZitiIdentity _identity;
-
- public ZitiIdentity Identity {
- get {
- return _identity;
- }
- set {
- _identity = value;
- this.IdDetailToggle.Enabled = _identity.IsEnabled;
- UpdateView();
- IdentityArea.Opacity = 1.0;
- IdentityArea.Visibility = Visibility.Visible;
- this.Visibility = Visibility.Visible;
- }
- }
-
- public IdentityItem SelectedIdentity { get; set; }
-
- private void Window_MouseDown(object sender, MouseButtonEventArgs e) {
- if (e.ChangedButton == MouseButton.Left) {
- _isAttached = false;
- OnDetach(e);
- }
- }
-
-
- public bool IsAttached {
- get {
- return _isAttached;
- }
- set {
- _isAttached = value;
- if (_isAttached) {
- Arrow.Visibility = Visibility.Visible;
- ConfirmArrow.Visibility = Visibility.Visible;
- } else {
- Arrow.Visibility = Visibility.Collapsed;
- ConfirmArrow.Visibility = Visibility.Collapsed;
- }
- }
- }
-
- public void UpdateView() {
- IdDetailName.Text = _identity.Name;
- IdDetailName.ToolTip = _identity.Name;
- IdDetailToggle.Enabled = _identity.IsEnabled;
- IdentityName.Value = _identity.Name;
- IdentityNetwork.Value = _identity.ControllerUrl;
- IdentityEnrollment.Value = _identity.Status;
- IdentityStatus.Value = _identity.IsEnabled ? "active" : "disabled";
- ServiceList.Children.Clear();
- if (_identity.Services.Count>0) {
- for (int i = 0; i < _identity.Services.Count; i++) {
- ServiceInfo editor = new ServiceInfo();
- editor.Label = _identity.Services[i].Name;
- editor.Value = _identity.Services[i].Url;
- editor.Warning = _identity.Services[i].Warning;
- editor.IsLocked = true;
- ServiceList.Children.Add(editor);
- }
- double newHeight = MainHeight - 300;
- ServiceRow.Height = new GridLength((double)newHeight);
- MainDetailScroll.MaxHeight = newHeight;
- MainDetailScroll.Height = newHeight;
- MainDetailScroll.Visibility = Visibility.Visible;
- ServiceTitle.Content = _identity.Services.Count + " SERVICES";
- } else {
- ServiceRow.Height = new GridLength((double)0.0);
- MainDetailScroll.Visibility = Visibility.Collapsed;
- ServiceTitle.Content = "NO SERVICES AVAILABLE";
- }
- }
-
- private void IdToggle(bool on) {
- DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
- client.IdentityOnOff(_identity.Fingerprint, on);
- SelectedIdentity.ToggleSwitch.Enabled = on;
- _identity.IsEnabled = on;
- IdentityStatus.Value = _identity.IsEnabled ? "active" : "disabled";
- }
-
- public IdentityDetails() {
- InitializeComponent();
- }
- private void HideMenu(object sender, MouseButtonEventArgs e) {
- this.Visibility = Visibility.Collapsed;
- }
-
- public void SetHeight(double height) {
- MainDetailScroll.Height = height;
- }
-
- private void ForgetIdentity(object sender, MouseButtonEventArgs e) {
- if (this.Visibility==Visibility.Visible) {
- ConfirmView.Visibility = Visibility.Visible;
- }
- }
-
- private void CancelConfirmButton_Click(object sender, RoutedEventArgs e) {
- ConfirmView.Visibility = Visibility.Collapsed;
- }
-
- private void ConfirmButton_Click(object sender, RoutedEventArgs e) {
- this.Visibility = Visibility.Collapsed;
- DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
- try {
- client.RemoveIdentity(_identity.Fingerprint);
-
- ZitiIdentity forgotten = new ZitiIdentity();
- foreach (var id in identities) {
- if (id.Fingerprint == _identity.Fingerprint) {
- forgotten = id;
- identities.Remove(id);
- break;
- }
- }
-
- if (OnForgot != null) {
- OnForgot(forgotten);
- }
- } catch (DataStructures.ServiceException se) {
- OnError(se.Message);
- } catch (Exception ex) {
- OnError(ex.Message);
- }
- }
- }
-}
+namespace ZitiDesktopEdge {
+ ///
+ /// Interaction logic for IdentityDetails.xaml
+ ///
+ public partial class IdentityDetails:UserControl {
+
+ private bool _isAttached = true;
+ public delegate void Forgot(ZitiIdentity forgotten);
+ public event Forgot OnForgot;
+ public delegate void ErrorOccurred(string message);
+ public event ErrorOccurred OnError;
+ public delegate void Detched(MouseButtonEventArgs e);
+ public event Detched OnDetach;
+ public double MainHeight = 500;
+
+ private List identities {
+ get {
+ return (List)Application.Current.Properties["Identities"];
+ }
+ }
+
+ private ZitiIdentity _identity;
+
+ public ZitiIdentity Identity {
+ get {
+ return _identity;
+ }
+ set {
+ _identity = value;
+ this.IdDetailToggle.Enabled = _identity.IsEnabled;
+ UpdateView();
+ IdentityArea.Opacity = 1.0;
+ IdentityArea.Visibility = Visibility.Visible;
+ this.Visibility = Visibility.Visible;
+ }
+ }
+
+ public IdentityItem SelectedIdentity { get; set; }
+
+ private void Window_MouseDown(object sender, MouseButtonEventArgs e) {
+ if (e.ChangedButton == MouseButton.Left) {
+ _isAttached = false;
+ OnDetach(e);
+ }
+ }
+
+
+ public bool IsAttached {
+ get {
+ return _isAttached;
+ }
+ set {
+ _isAttached = value;
+ if (_isAttached) {
+ Arrow.Visibility = Visibility.Visible;
+ ConfirmArrow.Visibility = Visibility.Visible;
+ } else {
+ Arrow.Visibility = Visibility.Collapsed;
+ ConfirmArrow.Visibility = Visibility.Collapsed;
+ }
+ }
+ }
+
+ public void UpdateView() {
+ IdDetailName.Text = _identity.Name;
+ IdDetailName.ToolTip = _identity.Name;
+ IdDetailToggle.Enabled = _identity.IsEnabled;
+ IdentityName.Value = _identity.Name;
+ IdentityNetwork.Value = _identity.ControllerUrl;
+ IdentityEnrollment.Value = _identity.Status;
+ IdentityStatus.Value = _identity.IsEnabled ? "active" : "disabled";
+ ServiceList.Children.Clear();
+ if (_identity.Services.Count>0) {
+ for (int i = 0; i < _identity.Services.Count; i++) {
+ ServiceInfo editor = new ServiceInfo();
+ editor.Label = _identity.Services[i].Name;
+ editor.Value = _identity.Services[i].Url;
+ editor.Warning = _identity.Services[i].Warning;
+ editor.IsLocked = true;
+ ServiceList.Children.Add(editor);
+ }
+ double newHeight = MainHeight - 300;
+ ServiceRow.Height = new GridLength((double)newHeight);
+ MainDetailScroll.MaxHeight = newHeight;
+ MainDetailScroll.Height = newHeight;
+ MainDetailScroll.Visibility = Visibility.Visible;
+ ServiceTitle.Content = _identity.Services.Count + " SERVICES";
+ } else {
+ ServiceRow.Height = new GridLength((double)0.0);
+ MainDetailScroll.Visibility = Visibility.Collapsed;
+ ServiceTitle.Content = "NO SERVICES AVAILABLE";
+ }
+ }
+
+ async private void IdToggle(bool on) {
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
+ await client.IdentityOnOffAsync(_identity.Fingerprint, on);
+ SelectedIdentity.ToggleSwitch.Enabled = on;
+ _identity.IsEnabled = on;
+ IdentityStatus.Value = _identity.IsEnabled ? "active" : "disabled";
+ }
+
+ public IdentityDetails() {
+ InitializeComponent();
+ }
+ private void HideMenu(object sender, MouseButtonEventArgs e) {
+ this.Visibility = Visibility.Collapsed;
+ }
+
+ public void SetHeight(double height) {
+ MainDetailScroll.Height = height;
+ }
+
+ private void ForgetIdentity(object sender, MouseButtonEventArgs e) {
+ if (this.Visibility==Visibility.Visible) {
+ ConfirmView.Visibility = Visibility.Visible;
+ }
+ }
+
+ private void CancelConfirmButton_Click(object sender, RoutedEventArgs e) {
+ ConfirmView.Visibility = Visibility.Collapsed;
+ }
+
+ async private void ConfirmButton_Click(object sender, RoutedEventArgs e) {
+ this.Visibility = Visibility.Collapsed;
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
+ try {
+ await client.RemoveIdentityAsync(_identity.Fingerprint);
+
+ ZitiIdentity forgotten = new ZitiIdentity();
+ foreach (var id in identities) {
+ if (id.Fingerprint == _identity.Fingerprint) {
+ forgotten = id;
+ identities.Remove(id);
+ break;
+ }
+ }
+
+ if (OnForgot != null) {
+ OnForgot(forgotten);
+ }
+ } catch (DataStructures.ServiceException se) {
+ OnError(se.Message);
+ } catch (Exception ex) {
+ OnError(ex.Message);
+ }
+ }
+ }
+}
diff --git a/DesktopEdge/MainMenu.xaml.cs b/DesktopEdge/MainMenu.xaml.cs
index 7520dc8bf..5bb822627 100644
--- a/DesktopEdge/MainMenu.xaml.cs
+++ b/DesktopEdge/MainMenu.xaml.cs
@@ -13,6 +13,12 @@
using Newtonsoft.Json.Linq;
using ZitiDesktopEdge.ServiceClient;
+using NLog;
+using NLog.Config;
+using NLog.Targets;
+
+using ZitiDesktopEdge.Server;
+
namespace ZitiDesktopEdge
{
///
diff --git a/DesktopEdge/MainWindow.xaml.cs b/DesktopEdge/MainWindow.xaml.cs
index 70bdb1b40..e2ea1263f 100644
--- a/DesktopEdge/MainWindow.xaml.cs
+++ b/DesktopEdge/MainWindow.xaml.cs
@@ -14,12 +14,17 @@
using ZitiDesktopEdge.DataStructures;
using ZitiDesktopEdge.ServiceClient;
+using NLog;
+using NLog.Config;
+using NLog.Targets;
+
namespace ZitiDesktopEdge {
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window {
+ private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public System.Windows.Forms.NotifyIcon notifyIcon;
public string Position = "Bottom";
@@ -41,15 +46,42 @@ private List identities {
}
}
- private List services = new List();
public MainWindow() {
InitializeComponent();
#if DEBUG
System.Environment.SetEnvironmentVariable("ZITI_EXTENDED_DEBUG", "true");
- #endif
+#endif
+ var asm = System.Reflection.Assembly.GetExecutingAssembly();
+ var curdir = Path.GetDirectoryName(asm.Location);
+ string nlogFile = Path.Combine(curdir, asm.ManifestModule.Name + ".log.config");
+
+ if (File.Exists(nlogFile)) {
+ LogManager.Configuration = new XmlLoggingConfiguration(nlogFile);
+ } else {
+ 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,
+ Layout = "${longdate}|${level:uppercase=true:padding=5}|${logger}|${message}",
+ //ArchiveAboveSize = 10000,
+ };
+ var logconsole = new ConsoleTarget("logconsole");
+
+ // Rules for mapping loggers to targets
+ config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
+ config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
+
+ // Apply config
+ LogManager.Configuration = config;
+ }
+ Logger.Info("service started - logger initialized");
- App.Current.MainWindow.WindowState = WindowState.Normal;
+ App.Current.MainWindow.WindowState = WindowState.Normal;
App.Current.MainWindow.Closing += MainWindow_Closing;
App.Current.MainWindow.Deactivated += MainWindow_Deactivated;
App.Current.MainWindow.Activated += MainWindow_Activated;
@@ -137,7 +169,7 @@ private void UpdateServiceView() {
}
}
- private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
+ async private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
// add a new service client
serviceClient = new DataClient();
serviceClient.OnClientConnected += ServiceClient_OnClientConnected;
@@ -158,16 +190,16 @@ private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
IdentityMenu.OnError += IdentityMenu_OnError;
try {
- serviceClient.Connect();
- serviceClient.WaitForConnectionAsync().Wait();
+ await serviceClient.ConnectAsync();
+ await serviceClient.WaitForConnectionAsync();
} catch /*ignored for now (Exception ex) */{
SetCantDisplay("Start the Ziti Tunnel Service to continue");
serviceClient.Reconnect();
}
try {
- monitorClient.Connect();
- monitorClient.WaitForConnectionAsync().Wait();
+ await monitorClient.ConnectAsync();
+ await monitorClient.WaitForConnectionAsync();
} catch /*ignored for now (Exception ex) */{
monitorClient.Reconnect();
}
@@ -185,7 +217,7 @@ private void MonitorClient_OnClientConnected(object sender, object e) {
}
private void LogLevelChanged(string level) {
- serviceClient.SetLogLevel(level);
+ serviceClient.SetLogLevelAsync(level).Wait();
}
private void IdentityMenu_OnError(string message) {
@@ -514,7 +546,7 @@ private void ShowMenu(object sender, MouseButtonEventArgs e) {
MainMenu.Visibility = Visibility.Visible;
}
- private void AddIdentity(object sender, MouseButtonEventArgs e) {
+ async private void AddIdentity(object sender, MouseButtonEventArgs e) {
UIModel.HideOnLostFocus = false;
Microsoft.Win32.OpenFileDialog jwtDialog = new Microsoft.Win32.OpenFileDialog();
UIModel.HideOnLostFocus = true;
@@ -525,9 +557,9 @@ private void AddIdentity(object sender, MouseButtonEventArgs e) {
string fileContent = File.ReadAllText(jwtDialog.FileName);
try {
- Identity createdId = serviceClient.AddIdentity(System.IO.Path.GetFileName(jwtDialog.FileName), false, fileContent);
+ Identity createdId = await serviceClient.AddIdentityAsync(System.IO.Path.GetFileName(jwtDialog.FileName), false, fileContent);
- serviceClient.IdentityOnOff(createdId.FingerPrint, true);
+ await serviceClient.IdentityOnOffAsync(createdId.FingerPrint, true);
if (createdId != null) {
identities.Add(ZitiIdentity.FromClient(createdId));
LoadIdentities(true);
@@ -565,15 +597,15 @@ private void InitializeTimer(int millisAgoStarted) {
private void Connect(object sender, RoutedEventArgs e) {
if (!_isServiceInError) {
ShowLoad();
- this.Dispatcher.Invoke(() => {
+ this.Dispatcher.Invoke(async () => {
//Dispatcher.Invoke(new Action(() => { }), System.Windows.Threading.DispatcherPriority.ContextIdle);
- DoConnect();
+ await DoConnectAsync();
HideLoad();
});
}
}
- private void DoConnect() {
+ async private Task DoConnectAsync() {
try {
serviceClient.SetTunnelState(true);
SetNotifyIcon("green");
@@ -581,7 +613,7 @@ private void DoConnect() {
DisconnectButton.Visibility = Visibility.Visible;
for (int i = 0; i < identities.Count; i++) {
- serviceClient.IdentityOnOff(identities[i].Fingerprint, true);
+ await serviceClient.IdentityOnOffAsync(identities[i].Fingerprint, true);
}
for (int i = 0; i < IdList.Children.Count; i++) {
IdentityItem item = IdList.Children[i] as IdentityItem;
@@ -594,7 +626,7 @@ private void DoConnect() {
ShowError("Unexpected Error", "Code 3:" + ex.Message);
}
}
- private void Disconnect(object sender, RoutedEventArgs e) {
+ async private void Disconnect(object sender, RoutedEventArgs e) {
if (!_isServiceInError) {
ShowLoad();
try {
@@ -605,7 +637,7 @@ private void Disconnect(object sender, RoutedEventArgs e) {
ConnectButton.Visibility = Visibility.Visible;
DisconnectButton.Visibility = Visibility.Collapsed;
for (int i = 0; i < identities.Count; i++) {
- serviceClient.IdentityOnOff(identities[i].Fingerprint, false);
+ await serviceClient.IdentityOnOffAsync(identities[i].Fingerprint, false);
}
for (int i = 0; i < IdList.Children.Count; i++) {
IdentityItem item = IdList.Children[i] as IdentityItem;
@@ -673,8 +705,8 @@ private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
Placement();
}
- private void Button_Click(object sender, RoutedEventArgs e) {
- serviceClient.SetLogLevel(NextLevel());
+ async private void Button_Click(object sender, RoutedEventArgs e) {
+ await serviceClient.SetLogLevelAsync(NextLevel());
}
int cur = 0;
@@ -700,10 +732,10 @@ async private void Button_Click_1(object sender, RoutedEventArgs e) {
action = "stop";
await monitorClient.StopServicAsync();
}
- Debug.WriteLine("button 1 1 1 1!");
+ Logger.Info("button 1 1 1 1!");
}
async private void Button_Click_2(object sender, RoutedEventArgs e) {
- Debug.WriteLine("button 2!");
+ Logger.Info("button 2!");
await Task.Delay(10);
}
}
diff --git a/DesktopEdge/Views/ItemRenderers/IdentityItem.xaml.cs b/DesktopEdge/Views/ItemRenderers/IdentityItem.xaml.cs
index ab55ea10b..1f8e76db6 100644
--- a/DesktopEdge/Views/ItemRenderers/IdentityItem.xaml.cs
+++ b/DesktopEdge/Views/ItemRenderers/IdentityItem.xaml.cs
@@ -1,90 +1,90 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using System.Windows.Shapes;
-using ZitiDesktopEdge.Models;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using ZitiDesktopEdge.Models;
using ZitiDesktopEdge.ServiceClient;
-namespace ZitiDesktopEdge {
- ///
- /// User Control to list Identities and give status
- ///
- public partial class IdentityItem:UserControl {
-
- public delegate void StatusChanged(bool attached);
- public event StatusChanged OnStatusChanged;
-
- public ZitiIdentity _identity;
- public ZitiIdentity Identity {
- get {
- return _identity;
- }
- set {
- _identity = value;
- this.RefreshUI();
- }
- }
-
- public void RefreshUI () {
- ToggleSwitch.Enabled = _identity.IsEnabled;
- IdName.Content = _identity.Name;
- IdUrl.Content = _identity.ControllerUrl;
- ServiceCount.Content = _identity.Services.Count.ToString();
- if (ToggleSwitch.Enabled) {
- ToggleStatus.Content = "ENABLED";
- } else {
- ToggleStatus.Content = "DISABLED";
- }
- }
-
- public IdentityItem() {
- InitializeComponent();
- ToggleSwitch.OnToggled += ToggleIdentity;
- }
-
- private void ToggleIdentity(bool on) {
- try {
- if (OnStatusChanged != null) {
- OnStatusChanged(on);
- }
- DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
- DataStructures.Identity id = client.IdentityOnOff(_identity.Fingerprint, on);
- this.Identity.IsEnabled = on;
- if (on) {
- ToggleStatus.Content = "ENABLED";
- } else {
- ToggleStatus.Content = "DISABLED";
- }
- } catch (DataStructures.ServiceException se) {
- MessageBox.Show(se.AdditionalInfo, se.Message);
- } catch (Exception ex) {
- MessageBox.Show("Error", ex.Message);
- }
- }
-
- private void Canvas_MouseEnter(object sender, MouseEventArgs e) {
- OverState.Opacity = 0.2;
- }
-
- private void Canvas_MouseLeave(object sender, MouseEventArgs e) {
- OverState.Opacity = 0;
- }
-
- private void OpenDetails(object sender, MouseButtonEventArgs e) {
- IdentityDetails deets = ((MainWindow)Application.Current.MainWindow).IdentityMenu;
- deets.SelectedIdentity = this;
- deets.IdDetailToggle.Enabled = this.Identity.IsEnabled;
- deets.Identity = this.Identity;
- }
- }
-}
+namespace ZitiDesktopEdge {
+ ///
+ /// User Control to list Identities and give status
+ ///
+ public partial class IdentityItem:UserControl {
+
+ public delegate void StatusChanged(bool attached);
+ public event StatusChanged OnStatusChanged;
+
+ public ZitiIdentity _identity;
+ public ZitiIdentity Identity {
+ get {
+ return _identity;
+ }
+ set {
+ _identity = value;
+ this.RefreshUI();
+ }
+ }
+
+ public void RefreshUI () {
+ ToggleSwitch.Enabled = _identity.IsEnabled;
+ IdName.Content = _identity.Name;
+ IdUrl.Content = _identity.ControllerUrl;
+ ServiceCount.Content = _identity.Services.Count.ToString();
+ if (ToggleSwitch.Enabled) {
+ ToggleStatus.Content = "ENABLED";
+ } else {
+ ToggleStatus.Content = "DISABLED";
+ }
+ }
+
+ public IdentityItem() {
+ InitializeComponent();
+ ToggleSwitch.OnToggled += ToggleIdentity;
+ }
+
+ private void ToggleIdentity(bool on) {
+ try {
+ if (OnStatusChanged != null) {
+ OnStatusChanged(on);
+ }
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
+ DataStructures.Identity id = client.IdentityOnOffAsync(_identity.Fingerprint, on).Result;
+ this.Identity.IsEnabled = on;
+ if (on) {
+ ToggleStatus.Content = "ENABLED";
+ } else {
+ ToggleStatus.Content = "DISABLED";
+ }
+ } catch (DataStructures.ServiceException se) {
+ MessageBox.Show(se.AdditionalInfo, se.Message);
+ } catch (Exception ex) {
+ MessageBox.Show("Error", ex.Message);
+ }
+ }
+
+ private void Canvas_MouseEnter(object sender, MouseEventArgs e) {
+ OverState.Opacity = 0.2;
+ }
+
+ private void Canvas_MouseLeave(object sender, MouseEventArgs e) {
+ OverState.Opacity = 0;
+ }
+
+ private void OpenDetails(object sender, MouseButtonEventArgs e) {
+ IdentityDetails deets = ((MainWindow)Application.Current.MainWindow).IdentityMenu;
+ deets.SelectedIdentity = this;
+ deets.IdDetailToggle.Enabled = this.Identity.IsEnabled;
+ deets.Identity = this.Identity;
+ }
+ }
+}
diff --git a/DesktopEdge/ZitiDesktopEdge.csproj b/DesktopEdge/ZitiDesktopEdge.csproj
index 88fec2a3d..d0c29b3cd 100644
--- a/DesktopEdge/ZitiDesktopEdge.csproj
+++ b/DesktopEdge/ZitiDesktopEdge.csproj
@@ -88,7 +88,11 @@
..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll
+
+ ..\packages\NLog.4.7.5\lib\net45\NLog.dll
+
+
@@ -104,7 +108,10 @@
True
True
+
+
+
diff --git a/DesktopEdge/packages.config b/DesktopEdge/packages.config
index b38f3c783..9001a3120 100644
--- a/DesktopEdge/packages.config
+++ b/DesktopEdge/packages.config
@@ -1,4 +1,5 @@
+
\ No newline at end of file
diff --git a/ZitiDesktopEdge.Client/Server/IPCServer.cs b/ZitiDesktopEdge.Client/Server/IPCServer.cs
index 555eee0eb..eadd353d8 100644
--- a/ZitiDesktopEdge.Client/Server/IPCServer.cs
+++ b/ZitiDesktopEdge.Client/Server/IPCServer.cs
@@ -21,6 +21,7 @@ public class IPCServer {
private JsonSerializer serializer = new JsonSerializer() { Formatting = Formatting.None };
private string ipcPipeName;
private string eventPipeName;
+
public IPCServer() {
this.ipcPipeName = IPCServer.PipeName;
this.eventPipeName = IPCServer.EventPipeName;
diff --git a/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs b/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
index fa0750b9a..d763936ef 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
@@ -15,7 +15,6 @@
namespace ZitiDesktopEdge.ServiceClient {
public abstract class AbstractClient {
- private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private bool _extendedDebug = false; //set ZITI_EXTENDED_DEBUG env var to true if you want to diagnose issues with the service comms
@@ -23,13 +22,15 @@ public abstract class AbstractClient {
protected NamedPipeClientStream eventClient = null;
protected StreamWriter ipcWriter = null;
protected StreamReader ipcReader = null;
- protected abstract void ConnectPipes();
+ protected abstract Task ConnectPipesAsync();
protected abstract void ProcessLine(string line);
+ protected abstract Logger Logger { get; }
protected const string localPipeServer = ".";
protected const int ServiceConnectTimeout = 500;
- protected object namedPipeSyncLock = new object();
+ //protected object namedPipeSyncLock = new object();
+ protected static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
protected JsonSerializer serializer = new JsonSerializer() { Formatting = Formatting.None };
@@ -143,9 +144,9 @@ public AbstractClient() {
}
}
- public void Connect() {
+ async public Task ConnectAsync() {
//establish the named pipe to the service
- ConnectPipes();
+ await ConnectPipesAsync();
}
public void Reconnect() {
@@ -156,7 +157,7 @@ public void Reconnect() {
Reconnecting = true;
}
- Task.Run(() => {
+ Task.Run(async () => {
Logger.Info("service is down. attempting to connect to service...");
DateTime reconnectStart = DateTime.Now;
@@ -164,8 +165,8 @@ public void Reconnect() {
while (true) {
try {
- Thread.Sleep(2500);
- ConnectPipes();
+ await Task.Delay(2500);
+ await ConnectPipesAsync();
if (Connected) {
Logger.Debug("Connected to the service - exiting reconect loop");
@@ -198,16 +199,15 @@ public void Reconnect() {
private void debugServiceCommunication(string msg) {
if (_extendedDebug) {
Logger.Debug(msg);
- System.Diagnostics.Debug.WriteLine(msg);
}
}
async public Task readMessageAsync(StreamReader reader) {
- try {
+ try {/*
if (reader.EndOfStream) {
throw new ServiceException("the pipe has closed", 0, "end of stream reached");
- }
+ }*/
int emptyCount = 1; //just a stop gap in case something crazy happens in the communication
debugServiceCommunication("=============== reading message =============== " + emptyCount);
@@ -215,9 +215,9 @@ async public Task readMessageAsync(StreamReader reader) {
debugServiceCommunication(respAsString);
debugServiceCommunication("=============== read message =============== " + emptyCount);
while (string.IsNullOrEmpty(respAsString?.Trim())) {
- if (reader.EndOfStream) {
+ /*if (reader.EndOfStream) {
throw new Exception("the pipe has closed");
- }
+ }*/
debugServiceCommunication("Received empty payload - continuing to read until a payload is received");
//now how'd that happen...
debugServiceCommunication("=============== reading message =============== " + emptyCount);
diff --git a/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
index dc044fe51..f926a997d 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
@@ -23,7 +23,8 @@
///
namespace ZitiDesktopEdge.ServiceClient {
public class DataClient : AbstractClient {
- private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+ private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
+ protected override Logger Logger { get { return _logger; } }
public const int EXPECTED_API_VERSION = 1;
@@ -97,24 +98,24 @@ PipeSecurity CreateSystemIOPipeSecurity() {
return pipeSecurity;
}
- protected override void ConnectPipes() {//private void setupPipe()
- lock (namedPipeSyncLock) {
+ async protected override Task ConnectPipesAsync() {
+ await semaphoreSlim.WaitAsync();
+ try {
pipeClient = new NamedPipeClientStream(localPipeServer, ipcPipe, inOut);
eventClient = new NamedPipeClientStream(localPipeServer, eventPipe, PipeDirection.In);
-
- try {
- eventClient.Connect(ServiceConnectTimeout);
- pipeClient.Connect(ServiceConnectTimeout);
- ClientConnected(null);
- } catch (Exception ex) {
- throw new ServiceException("Could not connect to the service.", 1, ex.Message);
- }
+ await eventClient.ConnectAsync(ServiceConnectTimeout);
+ await pipeClient.ConnectAsync(ServiceConnectTimeout);
+ ClientConnected(null);
+ } catch (Exception ex) {
+ semaphoreSlim.Release();
+ throw new ServiceException("Could not connect to the service.", 1, ex.Message);
}
+ semaphoreSlim.Release();
}
- public ZitiTunnelStatus GetStatus() {
+ async public Task GetStatusAsync() {
try {
- send(new ServiceFunction() { Function = "Status" });
+ await sendAsync(new ServiceFunction() { Function = "Status" });
var rtn = read(ipcReader);
return rtn;
} catch (IOException ioe) {
@@ -126,7 +127,7 @@ public ZitiTunnelStatus GetStatus() {
ServiceFunction AddIdentityFunction = new ServiceFunction() { Function = "AddIdentity" };
- public Identity AddIdentity(string identityName, bool activate, string jwt) {
+ async public Task AddIdentityAsync(string identityName, bool activate, string jwt) {
try {
Identity id = new Identity {
Active = activate,
@@ -140,8 +141,8 @@ public Identity AddIdentity(string identityName, bool activate, string jwt) {
}
};
- send(AddIdentityFunction);
- send(newId);
+ await sendAsync(AddIdentityFunction);
+ await sendAsync(newId);
var resp = read(ipcReader);
Logger.Debug(resp.ToString());
if (resp.Code != 0) {
@@ -156,7 +157,7 @@ public Identity AddIdentity(string identityName, bool activate, string jwt) {
}
- public void RemoveIdentity(string fingerPrint) {
+ async public Task RemoveIdentityAsync(string fingerPrint) {
if (string.IsNullOrEmpty(fingerPrint)) {
//nothing to do...
return;
@@ -167,7 +168,7 @@ public void RemoveIdentity(string fingerPrint) {
Function = "RemoveIdentity",
Payload = new FingerprintPayload() { Fingerprint = fingerPrint }
};
- send(removeFunction);
+ await sendAsync(removeFunction);
var r = read(ipcReader);
} catch (IOException ioe) {
//almost certainly a problem with the pipe - recreate the pipe...
@@ -220,9 +221,9 @@ public string GetLogs() {
}
}
- public void SetLogLevel(string level) {
+ async public Task SetLogLevelAsync(string level) {
try {
- send(new SetLogLevelFunction(level));
+ await sendAsync(new SetLogLevelFunction(level));
SvcResponse resp = read(ipcReader);
return;
} catch (IOException ioe) {
@@ -232,9 +233,9 @@ public void SetLogLevel(string level) {
}
}
- public void SetLogLevel(LogLevelEnum level) {
+ async public Task SetLogLevelAsync(LogLevelEnum level) {
try {
- send(new SetLogLevelFunction(Enum.GetName(level.GetType(), level)));
+ await sendAsync(new SetLogLevelFunction(Enum.GetName(level.GetType(), level)));
SvcResponse resp = read(ipcReader);
return;
} catch (IOException ioe) {
@@ -244,9 +245,9 @@ public void SetLogLevel(LogLevelEnum level) {
}
}
- public Identity IdentityOnOff(string fingerprint, bool onOff) {
+ async public Task IdentityOnOffAsync(string fingerprint, bool onOff) {
try {
- send(new IdentityToggleFunction(fingerprint, onOff));
+ await sendAsync(new IdentityToggleFunction(fingerprint, onOff));
IdentityResponse idr = read(ipcReader);
return idr.Payload;
} catch (IOException ioe) {
@@ -256,51 +257,13 @@ public Identity IdentityOnOff(string fingerprint, bool onOff) {
}
}
- private void send(object objToSend) {
- bool retried = false;
- while (true) {
- try {
- string toSend = JsonConvert.SerializeObject(objToSend, Formatting.None);
-
- if (toSend?.Trim() != null) {
- debugServiceCommunication("=============== sending message =============== ");
- debugServiceCommunication(toSend);
- ipcWriter.Write(toSend);
- ipcWriter.Write('\n');
- debugServiceCommunication("=============== flushing message =============== ");
- ipcWriter.Flush();
- debugServiceCommunication("=============== sent message =============== ");
- debugServiceCommunication("");
- debugServiceCommunication("");
- } else {
- Logger.Debug("NOT sending empty object??? " + objToSend?.ToString());
- }
- break;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe - recreate the pipe... try one more time.
- //setupPipe();
- if (retried) {
- //we tried - throw the error...
- throw ioe;
- } else {
- retried = true; //fall back through to the while and try again
- }
- } catch (Exception ex) {
- //if this fails it's usually because the writer is null/invalid. throwing IOException
- //will trigger the pipe to rebuild
- throw new IOException("Unexpected error when sending data to service. " + ex.Message);
- }
- }
- }
-
private T read(StreamReader reader) where T : SvcResponse {
string respAsString = readMessageAsync(reader).Result;
- // T resp = JsonSerializer.Deserialize(new JsonStr(respAsString));
T resp = (T)serializer.Deserialize(new StringReader(respAsString), typeof(T));
return resp;
}
- protected override void ProcessLine(string line) {//private void processEvent(StreamReader reader)
+ protected override void ProcessLine(string line) {
try {
string respAsString = line;
var jsonReaderEvt = new JsonTextReader(new StringReader(respAsString));
@@ -348,59 +311,14 @@ protected override void ProcessLine(string line) {//private void processEvent(St
}
}
- public string readMessage(StreamReader reader) {
- try {
- if (reader.EndOfStream) {
- throw new ServiceException("the pipe has closed", 0, "end of stream reached");
- }
- int emptyCount = 1; //just a stop gap in case something crazy happens in the communication
-
- debugServiceCommunication("=============== reading message =============== " + emptyCount);
- string respAsString = reader.ReadLine();
- debugServiceCommunication(respAsString);
- debugServiceCommunication("=============== read message =============== " + emptyCount);
- while (string.IsNullOrEmpty(respAsString?.Trim())) {
- if (reader.EndOfStream) {
- throw new Exception("the pipe has closed");
- }
- debugServiceCommunication("Received empty payload - continuing to read until a payload is received");
- //now how'd that happen...
- debugServiceCommunication("=============== reading message =============== " + emptyCount);
- respAsString = reader.ReadLine();
- debugServiceCommunication(respAsString);
- debugServiceCommunication("=============== read message =============== " + emptyCount);
- emptyCount++;
- if (emptyCount > 5) {
- Logger.Debug("are we there yet? " + reader.EndOfStream);
- //that's just too many...
- //setupPipe();
- return null;
- }
- }
- debugServiceCommunication("");
- debugServiceCommunication("");
- return respAsString;
- } catch (IOException ioe) {
- //almost certainly a problem with the pipe
- Logger.Debug("io error in read: " + ioe.Message);
- ClientDisconnected(null);
- throw ioe;
- } catch (Exception ee) {
- //almost certainly a problem with the pipe
- Logger.Debug("unexpected error in read: " + ee.Message);
- ClientDisconnected(null);
- throw ee;
- }
- }
-
private void debugServiceCommunication(string msg) {
if (_extendedDebug) {
Logger.Debug(msg);
}
}
- public ZitiTunnelStatus debug() {
+ async public Task debugAsync() {
try {
- send(new ServiceFunction() { Function = "Debug" });
+ await sendAsync(new ServiceFunction() { Function = "Debug" });
var rtn = read(ipcReader);
return rtn;
} catch (IOException ioe) {
diff --git a/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs b/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
index 6ffcdc807..edbdedf08 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
@@ -24,7 +24,8 @@
///
namespace ZitiDesktopEdge.ServiceClient {
public class MonitorClient : AbstractClient {
- private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+ private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
+ protected override Logger Logger { get { return _logger; } }
public const int EXPECTED_API_VERSION = 1;
@@ -39,19 +40,19 @@ protected virtual void TunnelStatusEvent(TunnelStatusEvent e) {
public MonitorClient() {
}
- protected override void ConnectPipes() {
- lock (namedPipeSyncLock) {
+ async protected override Task ConnectPipesAsync() {
+ await semaphoreSlim.WaitAsync();
+ try {
pipeClient = new NamedPipeClientStream(localPipeServer, IPCServer.PipeName, inOut);
eventClient = new NamedPipeClientStream(localPipeServer, IPCServer.EventPipeName, PipeDirection.In);
-
- try {
- eventClient.Connect(ServiceConnectTimeout);
- pipeClient.Connect(ServiceConnectTimeout);
- ClientConnected(null);
- } catch (Exception ex) {
- throw new ServiceException("Could not connect to the service.", 1, ex.Message);
- }
+ await eventClient.ConnectAsync(ServiceConnectTimeout);
+ await pipeClient.ConnectAsync(ServiceConnectTimeout);
+ ClientConnected(null);
+ } catch (Exception ex) {
+ semaphoreSlim.Release();
+ throw new ServiceException("Could not connect to the service.", 1, ex.Message);
}
+ semaphoreSlim.Release();
}
protected override void ProcessLine(string line) {
diff --git a/ZitiUpdateService/UpdateService.cs b/ZitiUpdateService/UpdateService.cs
index 91f86ece4..6add0e517 100644
--- a/ZitiUpdateService/UpdateService.cs
+++ b/ZitiUpdateService/UpdateService.cs
@@ -85,7 +85,7 @@ private void SetupServiceWatchers() {
CheckUpdate(null, null); //check immediately
try {
- svc.Connect();
+ svc.ConnectAsync().Wait();
} catch {
svc.Reconnect();
}
From 0238f71a1dc3da60cbfc80913ca376fb15a04b52 Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Thu, 19 Nov 2020 23:01:22 -0500
Subject: [PATCH 09/25] wip - logger name changed. continued
refactor/testing/UI and service work
---
DesktopEdge/MainMenu.xaml.cs | 640 +++++++++---------
DesktopEdge/MainWindow.xaml | 4 +-
DesktopEdge/MainWindow.xaml.cs | 42 +-
.../DataStructures/DataStructures.cs | 4 +
.../Server/EventRegistry.cs | 14 +
ZitiDesktopEdge.Client/Server/IPCServer.cs | 17 +-
.../Server/ServiceActions.cs | 2 +-
.../ServiceClient/AbstractClient.cs | 20 +-
.../ServiceClient/DataClient.cs | 9 +-
.../ServiceClient/MonitorClient.cs | 28 +-
.../ZitiDesktopEdge.Client.csproj | 1 +
ZitiUpdateService/Program.cs | 8 +-
ZitiUpdateService/UpdateCheckers.cs | 9 +-
ZitiUpdateService/UpdateService.cs | 48 +-
ZitiUpdateService/ziti-monitor-log.config | 2 +-
15 files changed, 446 insertions(+), 402 deletions(-)
create mode 100644 ZitiDesktopEdge.Client/Server/EventRegistry.cs
diff --git a/DesktopEdge/MainMenu.xaml.cs b/DesktopEdge/MainMenu.xaml.cs
index 5bb822627..e9ebbd83e 100644
--- a/DesktopEdge/MainMenu.xaml.cs
+++ b/DesktopEdge/MainMenu.xaml.cs
@@ -1,16 +1,16 @@
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Input;
-using System.Diagnostics;
-using System;
-using System.Threading;
-using ZitiDesktopEdge.Models;
-using System.Reflection;
-using System.Web;
-using System.Net.Mail;
-using System.IO;
-using System.Net;
-using Newtonsoft.Json.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Diagnostics;
+using System;
+using System.Threading;
+using ZitiDesktopEdge.Models;
+using System.Reflection;
+using System.Web;
+using System.Net.Mail;
+using System.IO;
+using System.Net;
+using Newtonsoft.Json.Linq;
using ZitiDesktopEdge.ServiceClient;
using NLog;
@@ -19,310 +19,310 @@
using ZitiDesktopEdge.Server;
-namespace ZitiDesktopEdge
-{
- ///
- /// Interaction logic for MainMenu.xaml
- ///
- public partial class MainMenu : UserControl {
-
-
- public delegate void AttachementChanged(bool attached);
- public event AttachementChanged OnAttachmentChange;
- public delegate void LogLevelChanged(string level);
- public event LogLevelChanged OnLogLevelChanged;
- public delegate void Detched(MouseButtonEventArgs e);
- public event Detched OnDetach;
- public string menuState = "Main";
- public string licenseData = "it's open source.";
- public string LogLevel = "";
- private string _updateUrl = "https://api.github.com/repos/openziti/desktop-edge-win/releases/latest";
- private string _downloadUrl = "";
-
- public MainMenu() {
- InitializeComponent();
- LicensesItems.Text = licenseData;
- CheckUpdates();
- }
-
- private void HideMenu(object sender, MouseButtonEventArgs e) {
- menuState = "Menu";
- UpdateState();
- MainMenuArea.Visibility = Visibility.Collapsed;
- }
- private void Window_MouseDown(object sender, MouseButtonEventArgs e) {
- if (e.ChangedButton == MouseButton.Left) {
- OnDetach(e);
- }
- }
-
- private void CloseApp(object sender, MouseButtonEventArgs e) {
- Application.Current.Shutdown();
- }
-
- private void DoUpdate(object sender, MouseButtonEventArgs e) {
- System.Diagnostics.Process.Start(_downloadUrl);
- }
-
- private void ShowAbout(object sender, MouseButtonEventArgs e) {
- menuState = "About";
- UpdateState();
- }
-
- private void ShowAdvanced(object sender, MouseButtonEventArgs e) {
- menuState = "Advanced";
- UpdateState();
- }
- private void ShowLicenses(object sender, MouseButtonEventArgs e) {
- menuState = "Licenses";
- UpdateState();
- }
- private void ShowConfig(object sender, MouseButtonEventArgs e) {
- menuState = "Config";
- UpdateState();
- }
- private void ShowLogs(object sender, MouseButtonEventArgs e) {
- menuState = "Logs";
- UpdateState();
- }
- private void ShowUILogs(object sender, MouseButtonEventArgs e) {
- menuState = "UILogs";
- UpdateState();
- }
- private void SetLogLevel(object sender, MouseButtonEventArgs e) {
- menuState = "LogLevel";
- UpdateState();
- }
-
- private void CheckUpdates() {
- try
- {
- HttpWebRequest httpWebRequest = WebRequest.CreateHttp(_updateUrl);
- httpWebRequest.Method = "GET";
- httpWebRequest.ContentType = "application/json";
- httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";
- HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
- StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream());
- string result = streamReader.ReadToEnd();
- JObject json = JObject.Parse(result);
- string currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
- string serverVersion = json.Property("tag_name").Value.ToString() + ".0";
-
- Version installed = new Version(currentVersion);
- Version published = new Version(serverVersion);
- int compare = installed.CompareTo(published);
- if (compare < 0)
- {
- UpdateAvailable.Content = "An Upgrade is available, click to download";
- UpdateAvailable.Visibility = Visibility.Visible;
- }
- else if (compare > 0)
- {
- UpdateAvailable.Content = "Your version is newer than the released version";
- UpdateAvailable.Visibility = Visibility.Visible;
- }
- JArray assets = JArray.Parse(json.Property("assets").Value.ToString());
- foreach (JObject asset in assets.Children())
- {
- _downloadUrl = asset.Property("browser_download_url").Value.ToString();
- break;
- }
- } 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;
- }
- }
-
- private void UpdateState() {
- MainItems.Visibility = Visibility.Collapsed;
- AboutItems.Visibility = Visibility.Collapsed;
- MainItemsButton.Visibility = Visibility.Collapsed;
- AboutItemsArea.Visibility = Visibility.Collapsed;
- BackArrow.Visibility = Visibility.Collapsed;
- AdvancedItems.Visibility = Visibility.Collapsed;
- LicensesItems.Visibility = Visibility.Collapsed;
- LogsItems.Visibility = Visibility.Collapsed;
- ConfigItems.Visibility = Visibility.Collapsed;
- LogLevelItems.Visibility = Visibility.Collapsed;
-
- if (menuState == "About") {
- MenuTitle.Content = "About";
- AboutItemsArea.Visibility = Visibility.Visible;
- AboutItems.Visibility = Visibility.Visible;
- BackArrow.Visibility = Visibility.Visible;
-
- string version = "";
- try {
- DataStructures.TunnelStatus s = (DataStructures.TunnelStatus)Application.Current.Properties["CurrentTunnelStatus"];
- version = $"{s.ServiceVersion.Version}@{s.ServiceVersion.Revision}";
- } catch (Exception e) {
-#if DEBUG
- Debug.WriteLine(e.ToString());
-#endif
- }
-
- // Interface Version
- VersionInfo.Content = "App: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()+" Service: "+ version;
-
- } else if (menuState=="Advanced") {
- MenuTitle.Content = "Advanced Settings";
- AdvancedItems.Visibility = Visibility.Visible;
- BackArrow.Visibility = Visibility.Visible;
- } else if (menuState=="Licenses") {
- MenuTitle.Content = "Third Party Licenses";
- LicensesItems.Visibility = Visibility.Visible;
- BackArrow.Visibility = Visibility.Visible;
- } else if (menuState=="Logs") {
- DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
- MenuTitle.Content = "Service Logs";
- LogsItems.Text = client.GetLogs();
- LogsItems.Visibility = Visibility.Visible;
- BackArrow.Visibility = Visibility.Visible;
- } else if (menuState == "UILogs") {
- MenuTitle.Content = "Application Logs";
- LogsItems.Text = UILog.GetLogs();
- LogsItems.Visibility = Visibility.Visible;
- BackArrow.Visibility = Visibility.Visible;
- } else if (menuState == "LogLevel") {
- ResetLevels();
-
- MenuTitle.Content = "Set Log Level";
- LogLevelItems.Visibility = Visibility.Visible;
- BackArrow.Visibility = Visibility.Visible;
- } else if (menuState=="Config") {
- MenuTitle.Content = "Tunnel Configuration";
- ConfigItems.Visibility = Visibility.Visible;
- BackArrow.Visibility = Visibility.Visible;
-
- ConfigIp.Value = Application.Current.Properties["ip"]?.ToString();
- ConfigSubnet.Value = Application.Current.Properties["subnet"]?.ToString();
- ConfigMtu.Value = Application.Current.Properties["mtu"]?.ToString();
- ConfigDns.Value = Application.Current.Properties["dns"]?.ToString();
- } else {
- MenuTitle.Content = "Main Menu";
- MainItems.Visibility = Visibility.Visible;
- MainItemsButton.Visibility = Visibility.Visible;
- }
- }
-
- private void GoBack(object sender, MouseButtonEventArgs e) {
- if (menuState=="Config"||menuState=="Logs"||menuState=="UILogs") {
- menuState = "Advanced";
- } else if (menuState=="Licenses") {
- menuState = "About";
- } else {
- menuState = "Menu";
- }
- UpdateState();
- }
- private void ShowPrivacy(object sender, MouseButtonEventArgs e) {
- Process.Start(new ProcessStartInfo("https://netfoundry.io/privacy") { UseShellExecute = true });
- }
- private void ShowTerms(object sender, MouseButtonEventArgs e) {
- Process.Start(new ProcessStartInfo("https://netfoundry.io/terms") { UseShellExecute = true });
- }
- private void ShowFeedback(object sender, MouseButtonEventArgs e) {
- DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
- var mailMessage = new MailMessage();
- mailMessage.From = new MailAddress("ziti-support@netfoundry.io");
- mailMessage.Subject = "Ziti Support";
- mailMessage.IsBodyHtml = true;
- mailMessage.Body = "";
-
- string timestamp = DateTime.Now.ToFileTime().ToString();
- string serviceLogTempFile = Path.Combine(Path.GetTempPath(), timestamp+"-Ziti-Service.log");
- using (StreamWriter sw = new StreamWriter(serviceLogTempFile)) {
- sw.WriteLine(client.GetLogs());
- }
-
- string uiLogTempFile = Path.Combine(Path.GetTempPath(), timestamp+"-Ziti-Application.log");
- using (StreamWriter sw = new StreamWriter(uiLogTempFile)) {
- sw.WriteLine(UILog.GetLogs());
- }
-
- mailMessage.Attachments.Add(new Attachment(serviceLogTempFile));
- mailMessage.Attachments.Add(new Attachment(uiLogTempFile));
-
- string emlFile = Path.Combine(Path.GetTempPath(), timestamp+"-ziti.eml");
-
- using (var filestream = File.Open(emlFile, FileMode.Create)) {
- var binaryWriter = new BinaryWriter(filestream);
- binaryWriter.Write(System.Text.Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
- var assembly = typeof(SmtpClient).Assembly;
- var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
- var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
- var mailWriter = mailWriterContructor.Invoke(new object[] { filestream });
- var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
- sendMethod.Invoke(mailMessage, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { mailWriter, true, true }, null);
- var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
- closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
- }
-
- Process.Start(emlFile);
-
-
-
- //string body = HttpUtility.UrlEncode("\n\nService Logs\n\n" + client.GetLogs());// + "\n\nApplication Logs\n\n" + UILog.GetLogs());
- //Process.Start(new ProcessStartInfo("mailto:ziti-support@netfoundry.io?subject=Ziti%20Support&body="+body) { UseShellExecute = true });
- }
- private void ShowSupport(object sender, MouseButtonEventArgs e) {
- Process.Start(new ProcessStartInfo("https://openziti.discourse.group/") { UseShellExecute = true });
- }
-
- private void DetachWindow(object sender, MouseButtonEventArgs e) {
- Application.Current.MainWindow.ShowInTaskbar = true;
- DetachButton.Visibility = Visibility.Collapsed;
- AttachButton.Visibility = Visibility.Visible;
- Arrow.Visibility = Visibility.Collapsed;
- if (OnAttachmentChange != null) {
- OnAttachmentChange(false);
- }
- MainMenuArea.Visibility = Visibility.Collapsed;
- }
-
- public void Detach() {
- Application.Current.MainWindow.ShowInTaskbar = true;
- DetachButton.Visibility = Visibility.Collapsed;
- AttachButton.Visibility = Visibility.Visible;
- Arrow.Visibility = Visibility.Collapsed;
- }
- private void RetachWindow(object sender, MouseButtonEventArgs e) {
- Application.Current.MainWindow.ShowInTaskbar = false;
- DetachButton.Visibility = Visibility.Visible;
- AttachButton.Visibility = Visibility.Collapsed;
- Arrow.Visibility = Visibility.Visible;
- if (OnAttachmentChange != null) {
- OnAttachmentChange(true);
- }
- }
-
- private void ResetLevels() {
- if (this.LogLevel == "") this.LogLevel = "error";
- LogVerbose.IsSelected = false;
- LogDebug.IsSelected = false;
- LogInfo.IsSelected = false;
- LogError.IsSelected = false;
- LogFatal.IsSelected = false;
- LogWarn.IsSelected = false;
- LogTrace.IsSelected = false;
- if (this.LogLevel == "verbose") LogVerbose.IsSelected = true;
- else if (this.LogLevel == "debug") LogDebug.IsSelected = true;
- else if (this.LogLevel == "info") LogInfo.IsSelected = true;
- else if (this.LogLevel == "error") LogError.IsSelected = true;
- else if (this.LogLevel == "fatal") LogFatal.IsSelected = true;
- else if (this.LogLevel == "warn") LogWarn.IsSelected = true;
- else if (this.LogLevel == "trace") LogTrace.IsSelected = true;
- }
-
- private void SetLevel(object sender, MouseButtonEventArgs e) {
- SubOptionItem item = (SubOptionItem)sender;
- this.LogLevel = item.Label.ToLower();
- if (OnLogLevelChanged != null) {
- OnLogLevelChanged(this.LogLevel);
- }
- ResetLevels();
- }
- }
-}
+namespace ZitiDesktopEdge
+{
+ ///
+ /// Interaction logic for MainMenu.xaml
+ ///
+ public partial class MainMenu : UserControl {
+
+
+ public delegate void AttachementChanged(bool attached);
+ public event AttachementChanged OnAttachmentChange;
+ public delegate void LogLevelChanged(string level);
+ public event LogLevelChanged OnLogLevelChanged;
+ public delegate void Detched(MouseButtonEventArgs e);
+ public event Detched OnDetach;
+ public string menuState = "Main";
+ public string licenseData = "it's open source.";
+ public string LogLevel = "";
+ private string _updateUrl = "https://api.github.com/repos/openziti/desktop-edge-win/releases/latest";
+ private string _downloadUrl = "";
+
+ public MainMenu() {
+ InitializeComponent();
+ LicensesItems.Text = licenseData;
+ CheckUpdates();
+ }
+
+ private void HideMenu(object sender, MouseButtonEventArgs e) {
+ menuState = "Menu";
+ UpdateState();
+ MainMenuArea.Visibility = Visibility.Collapsed;
+ }
+ private void Window_MouseDown(object sender, MouseButtonEventArgs e) {
+ if (e.ChangedButton == MouseButton.Left) {
+ OnDetach(e);
+ }
+ }
+
+ private void CloseApp(object sender, MouseButtonEventArgs e) {
+ Application.Current.Shutdown();
+ }
+
+ private void DoUpdate(object sender, MouseButtonEventArgs e) {
+ System.Diagnostics.Process.Start(_downloadUrl);
+ }
+
+ private void ShowAbout(object sender, MouseButtonEventArgs e) {
+ menuState = "About";
+ UpdateState();
+ }
+
+ private void ShowAdvanced(object sender, MouseButtonEventArgs e) {
+ menuState = "Advanced";
+ UpdateState();
+ }
+ private void ShowLicenses(object sender, MouseButtonEventArgs e) {
+ menuState = "Licenses";
+ UpdateState();
+ }
+ private void ShowConfig(object sender, MouseButtonEventArgs e) {
+ menuState = "Config";
+ UpdateState();
+ }
+ private void ShowLogs(object sender, MouseButtonEventArgs e) {
+ menuState = "Logs";
+ UpdateState();
+ }
+ private void ShowUILogs(object sender, MouseButtonEventArgs e) {
+ menuState = "UILogs";
+ UpdateState();
+ }
+ private void SetLogLevel(object sender, MouseButtonEventArgs e) {
+ menuState = "LogLevel";
+ UpdateState();
+ }
+
+ private void CheckUpdates() {
+ try
+ {
+ HttpWebRequest httpWebRequest = WebRequest.CreateHttp(_updateUrl);
+ httpWebRequest.Method = "GET";
+ httpWebRequest.ContentType = "application/json";
+ httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";
+ HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
+ StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream());
+ string result = streamReader.ReadToEnd();
+ JObject json = JObject.Parse(result);
+ string currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
+ string serverVersion = json.Property("tag_name").Value.ToString() + ".0";
+
+ Version installed = new Version(currentVersion);
+ Version published = new Version(serverVersion);
+ int compare = installed.CompareTo(published);
+ if (compare < 0)
+ {
+ UpdateAvailable.Content = "An Upgrade is available, click to download";
+ UpdateAvailable.Visibility = Visibility.Visible;
+ }
+ else if (compare > 0)
+ {
+ UpdateAvailable.Content = "Your version is newer than the released version";
+ UpdateAvailable.Visibility = Visibility.Visible;
+ }
+ JArray assets = JArray.Parse(json.Property("assets").Value.ToString());
+ foreach (JObject asset in assets.Children())
+ {
+ _downloadUrl = asset.Property("browser_download_url").Value.ToString();
+ break;
+ }
+ } 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;
+ }
+ }
+
+ private void UpdateState() {
+ MainItems.Visibility = Visibility.Collapsed;
+ AboutItems.Visibility = Visibility.Collapsed;
+ MainItemsButton.Visibility = Visibility.Collapsed;
+ AboutItemsArea.Visibility = Visibility.Collapsed;
+ BackArrow.Visibility = Visibility.Collapsed;
+ AdvancedItems.Visibility = Visibility.Collapsed;
+ LicensesItems.Visibility = Visibility.Collapsed;
+ LogsItems.Visibility = Visibility.Collapsed;
+ ConfigItems.Visibility = Visibility.Collapsed;
+ LogLevelItems.Visibility = Visibility.Collapsed;
+
+ if (menuState == "About") {
+ MenuTitle.Content = "About";
+ AboutItemsArea.Visibility = Visibility.Visible;
+ AboutItems.Visibility = Visibility.Visible;
+ BackArrow.Visibility = Visibility.Visible;
+
+ string version = "";
+ try {
+ DataStructures.TunnelStatus s = (DataStructures.TunnelStatus)Application.Current.Properties["CurrentTunnelStatus"];
+ version = $"{s.ServiceVersion.Version}@{s.ServiceVersion.Revision}";
+ } catch (Exception e) {
+#if DEBUG
+ Debug.WriteLine(e.ToString());
+#endif
+ }
+
+ // Interface Version
+ VersionInfo.Content = "App: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()+" Service: "+ version;
+
+ } else if (menuState=="Advanced") {
+ MenuTitle.Content = "Advanced Settings";
+ AdvancedItems.Visibility = Visibility.Visible;
+ BackArrow.Visibility = Visibility.Visible;
+ } else if (menuState=="Licenses") {
+ MenuTitle.Content = "Third Party Licenses";
+ LicensesItems.Visibility = Visibility.Visible;
+ BackArrow.Visibility = Visibility.Visible;
+ } else if (menuState=="Logs") {
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
+ MenuTitle.Content = "Service Logs";
+ LogsItems.Text = client.GetLogs();
+ LogsItems.Visibility = Visibility.Visible;
+ BackArrow.Visibility = Visibility.Visible;
+ } else if (menuState == "UILogs") {
+ MenuTitle.Content = "Application Logs";
+ LogsItems.Text = UILog.GetLogs();
+ LogsItems.Visibility = Visibility.Visible;
+ BackArrow.Visibility = Visibility.Visible;
+ } else if (menuState == "LogLevel") {
+ ResetLevels();
+
+ MenuTitle.Content = "Set Log Level";
+ LogLevelItems.Visibility = Visibility.Visible;
+ BackArrow.Visibility = Visibility.Visible;
+ } else if (menuState=="Config") {
+ MenuTitle.Content = "Tunnel Configuration";
+ ConfigItems.Visibility = Visibility.Visible;
+ BackArrow.Visibility = Visibility.Visible;
+
+ ConfigIp.Value = Application.Current.Properties["ip"]?.ToString();
+ ConfigSubnet.Value = Application.Current.Properties["subnet"]?.ToString();
+ ConfigMtu.Value = Application.Current.Properties["mtu"]?.ToString();
+ ConfigDns.Value = Application.Current.Properties["dns"]?.ToString();
+ } else {
+ MenuTitle.Content = "Main Menu";
+ MainItems.Visibility = Visibility.Visible;
+ MainItemsButton.Visibility = Visibility.Visible;
+ }
+ }
+
+ private void GoBack(object sender, MouseButtonEventArgs e) {
+ if (menuState=="Config"||menuState=="Logs"||menuState=="UILogs") {
+ menuState = "Advanced";
+ } else if (menuState=="Licenses") {
+ menuState = "About";
+ } else {
+ menuState = "Menu";
+ }
+ UpdateState();
+ }
+ private void ShowPrivacy(object sender, MouseButtonEventArgs e) {
+ Process.Start(new ProcessStartInfo("https://netfoundry.io/privacy") { UseShellExecute = true });
+ }
+ private void ShowTerms(object sender, MouseButtonEventArgs e) {
+ Process.Start(new ProcessStartInfo("https://netfoundry.io/terms") { UseShellExecute = true });
+ }
+ private void ShowFeedback(object sender, MouseButtonEventArgs e) {
+ DataClient client = (DataClient)Application.Current.Properties["ServiceClient"];
+ var mailMessage = new MailMessage();
+ mailMessage.From = new MailAddress("ziti-support@netfoundry.io");
+ mailMessage.Subject = "Ziti Support";
+ mailMessage.IsBodyHtml = true;
+ mailMessage.Body = "";
+
+ string timestamp = DateTime.Now.ToFileTime().ToString();
+ string serviceLogTempFile = Path.Combine(Path.GetTempPath(), timestamp+"-Ziti-Service.log");
+ using (StreamWriter sw = new StreamWriter(serviceLogTempFile)) {
+ sw.WriteLine(client.GetLogs());
+ }
+
+ string uiLogTempFile = Path.Combine(Path.GetTempPath(), timestamp+"-Ziti-Application.log");
+ using (StreamWriter sw = new StreamWriter(uiLogTempFile)) {
+ sw.WriteLine(UILog.GetLogs());
+ }
+
+ mailMessage.Attachments.Add(new Attachment(serviceLogTempFile));
+ mailMessage.Attachments.Add(new Attachment(uiLogTempFile));
+
+ string emlFile = Path.Combine(Path.GetTempPath(), timestamp+"-ziti.eml");
+
+ using (var filestream = File.Open(emlFile, FileMode.Create)) {
+ var binaryWriter = new BinaryWriter(filestream);
+ binaryWriter.Write(System.Text.Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
+ var assembly = typeof(SmtpClient).Assembly;
+ var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
+ var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
+ var mailWriter = mailWriterContructor.Invoke(new object[] { filestream });
+ var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
+ sendMethod.Invoke(mailMessage, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { mailWriter, true, true }, null);
+ var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
+ closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
+ }
+
+ Process.Start(emlFile);
+
+
+
+ //string body = HttpUtility.UrlEncode("\n\nService Logs\n\n" + client.GetLogs());// + "\n\nApplication Logs\n\n" + UILog.GetLogs());
+ //Process.Start(new ProcessStartInfo("mailto:ziti-support@netfoundry.io?subject=Ziti%20Support&body="+body) { UseShellExecute = true });
+ }
+ private void ShowSupport(object sender, MouseButtonEventArgs e) {
+ Process.Start(new ProcessStartInfo("https://openziti.discourse.group/") { UseShellExecute = true });
+ }
+
+ private void DetachWindow(object sender, MouseButtonEventArgs e) {
+ Application.Current.MainWindow.ShowInTaskbar = true;
+ DetachButton.Visibility = Visibility.Collapsed;
+ AttachButton.Visibility = Visibility.Visible;
+ Arrow.Visibility = Visibility.Collapsed;
+ if (OnAttachmentChange != null) {
+ OnAttachmentChange(false);
+ }
+ MainMenuArea.Visibility = Visibility.Collapsed;
+ }
+
+ public void Detach() {
+ Application.Current.MainWindow.ShowInTaskbar = true;
+ DetachButton.Visibility = Visibility.Collapsed;
+ AttachButton.Visibility = Visibility.Visible;
+ Arrow.Visibility = Visibility.Collapsed;
+ }
+ private void RetachWindow(object sender, MouseButtonEventArgs e) {
+ Application.Current.MainWindow.ShowInTaskbar = false;
+ DetachButton.Visibility = Visibility.Visible;
+ AttachButton.Visibility = Visibility.Collapsed;
+ Arrow.Visibility = Visibility.Visible;
+ if (OnAttachmentChange != null) {
+ OnAttachmentChange(true);
+ }
+ }
+
+ private void ResetLevels() {
+ if (this.LogLevel == "") this.LogLevel = "error";
+ LogVerbose.IsSelected = false;
+ LogDebug.IsSelected = false;
+ LogInfo.IsSelected = false;
+ LogError.IsSelected = false;
+ LogFatal.IsSelected = false;
+ LogWarn.IsSelected = false;
+ LogTrace.IsSelected = false;
+ if (this.LogLevel == "verbose") LogVerbose.IsSelected = true;
+ else if (this.LogLevel == "debug") LogDebug.IsSelected = true;
+ else if (this.LogLevel == "info") LogInfo.IsSelected = true;
+ else if (this.LogLevel == "error") LogError.IsSelected = true;
+ else if (this.LogLevel == "fatal") LogFatal.IsSelected = true;
+ else if (this.LogLevel == "warn") LogWarn.IsSelected = true;
+ else if (this.LogLevel == "trace") LogTrace.IsSelected = true;
+ }
+
+ private void SetLevel(object sender, MouseButtonEventArgs e) {
+ SubOptionItem item = (SubOptionItem)sender;
+ this.LogLevel = item.Label.ToLower();
+ if (OnLogLevelChanged != null) {
+ OnLogLevelChanged(this.LogLevel);
+ }
+ ResetLevels();
+ }
+ }
+}
diff --git a/DesktopEdge/MainWindow.xaml b/DesktopEdge/MainWindow.xaml
index 6ac248011..0db7bf5ee 100644
--- a/DesktopEdge/MainWindow.xaml
+++ b/DesktopEdge/MainWindow.xaml
@@ -319,7 +319,7 @@
-
-
+
+
diff --git a/DesktopEdge/MainWindow.xaml.cs b/DesktopEdge/MainWindow.xaml.cs
index e2ea1263f..bd0d69aad 100644
--- a/DesktopEdge/MainWindow.xaml.cs
+++ b/DesktopEdge/MainWindow.xaml.cs
@@ -60,7 +60,7 @@ public MainWindow() {
LogManager.Configuration = new XmlLoggingConfiguration(nlogFile);
} else {
var config = new LoggingConfiguration();
- var logname = "ziti-montior";
+ var logname = asm.GetName().Name;
// Targets where to log to: File and Console
var logfile = new FileTarget("logfile") {
FileName = $"{logname}.log",
@@ -181,7 +181,7 @@ async private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
monitorClient = new MonitorClient();
monitorClient.OnClientConnected += MonitorClient_OnClientConnected;
- monitorClient.OnTunnelStatusEvent += MonitorClient_OnTunnelStatusEvent;
+ monitorClient.OnMonitorStatusEvent += MonitorClient_OnMonitorStatusEvent;
Application.Current.Properties.Add("ServiceClient", serviceClient);
Application.Current.Properties.Add("Identities", new List());
@@ -208,8 +208,38 @@ async private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
Placement();
}
- private void MonitorClient_OnTunnelStatusEvent(object sender, TunnelStatusEvent e) {
- Debug.WriteLine("MonitorClient_OnTunnelStatusEvent");
+ private void MonitorClient_OnMonitorStatusEvent(object sender, MonitorStatusEvent evt) {
+ Debug.WriteLine("MonitorClient_OnMonitorStatusEvent");
+ ServiceControllerStatus status = (ServiceControllerStatus)Enum.Parse(typeof(ServiceControllerStatus), evt.Status);
+ action = evt.Status;
+ switch (status) {
+ case ServiceControllerStatus.Running:
+ Logger.Info("Service is started");
+ action = "stop";
+ break;
+ case ServiceControllerStatus.Stopped:
+ Logger.Info("Service is stopped");
+ action = "start";
+ break;
+ case ServiceControllerStatus.StopPending:
+ Logger.Info("Service is stopping...");
+ break;
+ case ServiceControllerStatus.StartPending:
+ Logger.Info("Service is starting...");
+ break;
+ case ServiceControllerStatus.PausePending:
+ Logger.Warn("UNEXPECTED STATUS: PausePending");
+ break;
+ case ServiceControllerStatus.Paused:
+ Logger.Warn("UNEXPECTED STATUS: Paused");
+ break;
+ default:
+ Logger.Warn("UNEXPECTED STATUS: {0}", evt.Status);
+ break;
+ }
+ this.Dispatcher.Invoke(() => {
+ this.serviceStatus.Content = "Service is :" + evt.Status;
+ });
}
private void MonitorClient_OnClientConnected(object sender, object e) {
@@ -725,11 +755,11 @@ private void IdList_LayoutUpdated(object sender, EventArgs e) {
string action = "stop";
async private void Button_Click_1(object sender, RoutedEventArgs e) {
- if (action == "stop") {
+ if (action == "Stopped") {
action = "start";
await monitorClient.StartServicAsync();
} else {
- action = "stop";
+ action = "Running";
await monitorClient.StopServicAsync();
}
Logger.Info("button 1 1 1 1!");
diff --git a/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs b/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs
index ae02f49c8..a55e5f452 100644
--- a/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs
+++ b/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs
@@ -291,4 +291,8 @@ public class IdentityEvent : ActionEvent
{
public Identity Id { get; set; }
}
+
+ public class MonitorStatusEvent : StatusEvent {
+ public string Status { get; set; }
+ }
}
\ No newline at end of file
diff --git a/ZitiDesktopEdge.Client/Server/EventRegistry.cs b/ZitiDesktopEdge.Client/Server/EventRegistry.cs
new file mode 100644
index 000000000..e3b2ad543
--- /dev/null
+++ b/ZitiDesktopEdge.Client/Server/EventRegistry.cs
@@ -0,0 +1,14 @@
+using System;
+using System.Threading;
+
+namespace ZitiDesktopEdge.Server {
+ public class EventRegistry {
+ protected static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
+
+ public static event EventHandler MyEvent;
+
+ public static void SendEventToConsumers(object objToSend) {
+ MyEvent(objToSend, null);
+ }
+ }
+}
diff --git a/ZitiDesktopEdge.Client/Server/IPCServer.cs b/ZitiDesktopEdge.Client/Server/IPCServer.cs
index eadd353d8..2c02c0758 100644
--- a/ZitiDesktopEdge.Client/Server/IPCServer.cs
+++ b/ZitiDesktopEdge.Client/Server/IPCServer.cs
@@ -122,12 +122,22 @@ async public Task handleIpcClientAsync(NamedPipeServerStream ss) {
async public Task handleEventClientAsync(NamedPipeServerStream ss) {
using (ss) {
+
+ StreamWriter writer = new StreamWriter(ss);
+ EventHandler eh = async (object sender, EventArgs e) => {
+ await writer.WriteLineAsync(sender.ToString());
+ await writer.FlushAsync();
+ };
+
+ MonitorStatusEvent status = new MonitorStatusEvent() { Op="status", Status = ServiceActions.ServiceStatus() };
+ await writer.WriteLineAsync(JsonConvert.SerializeObject(status));
+ await writer.FlushAsync();
+
+ EventRegistry.MyEvent += eh;
try {
StreamReader reader = new StreamReader(ss);
- StreamWriter writer = new StreamWriter(ss);
-
+
string line = await reader.ReadLineAsync();
-
while (line != null) {
await processMessage(line, writer);
line = await reader.ReadLineAsync();
@@ -137,6 +147,7 @@ async public Task handleEventClientAsync(NamedPipeServerStream ss) {
} catch (Exception e) {
Logger.Error(e, "Unexpected erorr when reading from or writing to a client pipe.");
}
+ EventRegistry.MyEvent -= eh;
}
}
diff --git a/ZitiDesktopEdge.Client/Server/ServiceActions.cs b/ZitiDesktopEdge.Client/Server/ServiceActions.cs
index ae02b5731..3a6bd159d 100644
--- a/ZitiDesktopEdge.Client/Server/ServiceActions.cs
+++ b/ZitiDesktopEdge.Client/Server/ServiceActions.cs
@@ -3,7 +3,7 @@
using NLog;
namespace ZitiDesktopEdge.Server {
- internal static class ServiceActions {
+ public static class ServiceActions {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static ServiceController sc = new ServiceController("ziti");
diff --git a/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs b/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
index d763936ef..d33895fed 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/AbstractClient.cs
@@ -42,7 +42,7 @@ protected virtual void ClientConnected(object e) {
ipcWriter = new StreamWriter(pipeClient);
ipcReader = new StreamReader(pipeClient);
- Task.Run(() => { //hack for now until it's async...
+ Task.Run(async () => { //hack for now until it's async...
try {
StreamReader eventReader = new StreamReader(eventClient);
while (true) {
@@ -50,7 +50,12 @@ protected virtual void ClientConnected(object e) {
break;
}
- waitForLine(eventReader);
+ try {
+ string respAsString = await readMessageAsync(eventReader);
+ ProcessLine(respAsString);
+ } catch (Exception ex) {
+ Logger.Warn(ex, "ERROR caught");
+ }
}
} catch (Exception ex) {
Logger.Debug("unepxected error: " + ex.ToString());
@@ -111,15 +116,6 @@ async protected Task sendAsync(object objToSend) {
}
}
}
- protected void waitForLine(StreamReader reader) {
- try {
- string respAsString = readMessageAsync(reader).Result;
- ProcessLine(respAsString);
-
- } catch (Exception e) {
- Logger.Debug(e.Message);
- }
- }
public event EventHandler OnClientConnected = null;
public event EventHandler OnClientDisconnected;
@@ -196,7 +192,7 @@ public void Reconnect() {
});
}
- private void debugServiceCommunication(string msg) {
+ protected void debugServiceCommunication(string msg) {
if (_extendedDebug) {
Logger.Debug(msg);
}
diff --git a/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
index f926a997d..696594566 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs
@@ -11,6 +11,7 @@
using NLog;
using ZitiDesktopEdge.DataStructures;
+using ZitiDesktopEdge.Server;
///
/// The implementation will abstract away the setup of the communication to
@@ -68,7 +69,6 @@ protected override void ClientDisconnected(object e) {
const string ipcPipe = @"OpenZiti\ziti\ipc";
const string logPipe = @"OpenZiti\ziti\logs";
const string eventPipe = @"OpenZiti\ziti\events";
- const PipeDirection inOut = PipeDirection.InOut;
bool _extendedDebug = false; //set ZITI_EXTENDED_DEBUG env var to true if you want to diagnose issues with the service comms
@@ -101,7 +101,7 @@ PipeSecurity CreateSystemIOPipeSecurity() {
async protected override Task ConnectPipesAsync() {
await semaphoreSlim.WaitAsync();
try {
- pipeClient = new NamedPipeClientStream(localPipeServer, ipcPipe, inOut);
+ pipeClient = new NamedPipeClientStream(localPipeServer, ipcPipe, PipeDirection.InOut);
eventClient = new NamedPipeClientStream(localPipeServer, eventPipe, PipeDirection.In);
await eventClient.ConnectAsync(ServiceConnectTimeout);
await pipeClient.ConnectAsync(ServiceConnectTimeout);
@@ -311,11 +311,6 @@ protected override void ProcessLine(string line) {
}
}
- private void debugServiceCommunication(string msg) {
- if (_extendedDebug) {
- Logger.Debug(msg);
- }
- }
async public Task debugAsync() {
try {
await sendAsync(new ServiceFunction() { Function = "Debug" });
diff --git a/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs b/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
index edbdedf08..bdc0f5934 100644
--- a/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
+++ b/ZitiDesktopEdge.Client/ServiceClient/MonitorClient.cs
@@ -29,21 +29,19 @@ public class MonitorClient : AbstractClient {
public const int EXPECTED_API_VERSION = 1;
- public event EventHandler OnTunnelStatusEvent;
+ public event EventHandler OnMonitorStatusEvent;
- protected virtual void TunnelStatusEvent(TunnelStatusEvent e) {
- OnTunnelStatusEvent?.Invoke(this, e);
+ protected virtual void MonitorStatusEvent(MonitorStatusEvent e) {
+ OnMonitorStatusEvent?.Invoke(this, e);
}
- const PipeDirection inOut = PipeDirection.InOut;
-
public MonitorClient() {
}
async protected override Task ConnectPipesAsync() {
await semaphoreSlim.WaitAsync();
try {
- pipeClient = new NamedPipeClientStream(localPipeServer, IPCServer.PipeName, inOut);
+ pipeClient = new NamedPipeClientStream(localPipeServer, IPCServer.PipeName, PipeDirection.InOut);
eventClient = new NamedPipeClientStream(localPipeServer, IPCServer.EventPipeName, PipeDirection.In);
await eventClient.ConnectAsync(ServiceConnectTimeout);
await pipeClient.ConnectAsync(ServiceConnectTimeout);
@@ -57,22 +55,8 @@ async protected override Task ConnectPipesAsync() {
protected override void ProcessLine(string line) {
var jsonReader = new JsonTextReader(new StringReader(line));
- StatusEvent evt = serializer.Deserialize(jsonReader);
- switch (evt.Op) {
- case "status":
- TunnelStatusEvent se = serializer.Deserialize(jsonReader);
-
- if (se != null) {
- TunnelStatusEvent(se);
- }
- break;
- case "shutdown":
-
- break;
- default:
- Logger.Debug("unexpected operation! " + evt.Op);
- break;
- }
+ MonitorStatusEvent evt = serializer.Deserialize(jsonReader);
+ MonitorStatusEvent(evt);
}
async public Task SendServiceFunctionAsync(ServiceFunction f) {
diff --git a/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj b/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj
index a26c7afb3..56c113b39 100644
--- a/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj
+++ b/ZitiDesktopEdge.Client/ZitiDesktopEdge.Client.csproj
@@ -54,6 +54,7 @@
+
diff --git a/ZitiUpdateService/Program.cs b/ZitiUpdateService/Program.cs
index 8d996dfc4..ff488070e 100644
--- a/ZitiUpdateService/Program.cs
+++ b/ZitiUpdateService/Program.cs
@@ -48,17 +48,11 @@ static void Main() {
}
Logger.Info("service started - logger initialized");
- IPCServer svr = new IPCServer();
- Task ipcServer = svr.startIpcServer();
- Task eventServer = svr.startEventsServer();
-
- Task.WaitAll(ipcServer, eventServer);
UpdateService updateSvc = new UpdateService();
updateSvc.AutoLog = true;
#if DEBUG
- Logger.Error("================================");
updateSvc.Debug();
- System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
+ updateSvc.WaitForCompletion();
#else
ServiceBase[] ServicesToRun = new ServiceBase[]
{
diff --git a/ZitiUpdateService/UpdateCheckers.cs b/ZitiUpdateService/UpdateCheckers.cs
index 296d0c261..d53538e19 100644
--- a/ZitiUpdateService/UpdateCheckers.cs
+++ b/ZitiUpdateService/UpdateCheckers.cs
@@ -74,6 +74,13 @@ public bool IsUpdateAvailable(Version current) {
internal class FilesystemCheck : IUpdateCheck {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
string dest = null;
+
+ bool isUpdateAvailable = false;
+ public FilesystemCheck(bool updateAvailable) {
+ this.isUpdateAvailable = updateAvailable;
+
+ }
+
public bool AlreadyDownloaded(string destinationFolder, string destinationName) {
return File.Exists(Path.Combine(destinationFolder, destinationName));
}
@@ -88,7 +95,7 @@ public string FileName() {
}
public bool IsUpdateAvailable(Version current) {
- return true;
+ return isUpdateAvailable;
}
}
}
diff --git a/ZitiUpdateService/UpdateService.cs b/ZitiUpdateService/UpdateService.cs
index 6add0e517..d7cf66846 100644
--- a/ZitiUpdateService/UpdateService.cs
+++ b/ZitiUpdateService/UpdateService.cs
@@ -12,6 +12,7 @@
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using ZitiDesktopEdge.ServiceClient;
+using ZitiDesktopEdge.Server;
namespace ZitiUpdateService {
public partial class UpdateService : ServiceBase {
@@ -30,6 +31,10 @@ public partial class UpdateService : ServiceBase {
private bool running = false;
ServiceController controller;
+ ZitiDesktopEdge.Server.IPCServer svr = new ZitiDesktopEdge.Server.IPCServer();
+ Task ipcServer = null;
+ Task eventServer = null;
+
public UpdateService() {
InitializeComponent();
@@ -41,7 +46,7 @@ public UpdateService() {
}
public void Debug() {
- OnStart(null);
+ OnStart(new string[] { "FilesystemCheck" });
}
protected override void OnStart(string[] args) {
@@ -58,17 +63,25 @@ protected override void OnStart(string[] args) {
if (!running) {
running = true;
Task.Run(() => {
- SetupServiceWatchers();
+ SetupServiceWatchers(args);
});
}
+
+ ipcServer = svr.startIpcServer();
+ eventServer = svr.startEventsServer();
+
Logger.Info("ziti-monitor service is initialized and running");
}
+ public void WaitForCompletion() {
+ Task.WaitAll(ipcServer, eventServer);
+ }
+
protected override void OnStop() {
Logger.Info("ziti-monitor service is stopping");
}
- private void SetupServiceWatchers() {
+ private void SetupServiceWatchers(string[] args) {
var updateTimerInterval = ConfigurationManager.AppSettings.Get("UpdateTimer");
var upInt = TimeSpan.Zero;
@@ -82,7 +95,7 @@ private void SetupServiceWatchers() {
_updateTimer.Enabled = true;
_updateTimer.Start();
Logger.Info("Version Checker is running");
- CheckUpdate(null, null); //check immediately
+ CheckUpdate(args, null); //check immediately
try {
svc.ConnectAsync().Wait();
@@ -99,8 +112,13 @@ private void CheckUpdate(object sender, ElapsedEventArgs e) {
try {
Logger.Debug("checking for update");
string updateUrl = "https://api.github.com/repos/openziti/desktop-edge-win/releases/latest"; //hardcoded on purpose
- IUpdateCheck check = new GithubCheck(updateUrl);
- //IUpdateCheck check = new FilesystemCheck();
+ string[] senderAsArgs = (string[])sender;
+ IUpdateCheck check = null;
+ if (sender == null || senderAsArgs.Length < 1 || !senderAsArgs[0].Equals("FilesystemCheck")) {
+ check = new GithubCheck(updateUrl);
+ } else {
+ check = new FilesystemCheck(false);
+ }
string currentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); //fetch from ziti?
Version installed = new Version(currentVersion);
@@ -165,20 +183,6 @@ private void CheckUpdate(object sender, ElapsedEventArgs e) {
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");
@@ -214,6 +218,10 @@ private static void Svc_OnClientDisconnected(object sender, object e) {
Logger.Info("client disconnected due to clean service shutdown");
} else {
Logger.Error("SERVICE IS DOWN and did not exit cleanly. initiating DNS cleanup");
+
+ MonitorStatusEvent status = new MonitorStatusEvent() { Op = "status", Status = ServiceActions.ServiceStatus() };
+ EventRegistry.SendEventToConsumers(status);
+
//EnumerateDNS();
var ps = System.Management.Automation.PowerShell.Create();
string script = "Get-NetIPInterface | ForEach-Object { Set-DnsClientServerAddress -InterfaceIndex $_.ifIndex -ResetServerAddresses }";
diff --git a/ZitiUpdateService/ziti-monitor-log.config b/ZitiUpdateService/ziti-monitor-log.config
index 23485ec72..6e18186d8 100644
--- a/ZitiUpdateService/ziti-monitor-log.config
+++ b/ZitiUpdateService/ziti-monitor-log.config
@@ -10,7 +10,7 @@
archiveEvery="Day"
archiveNumbering="Date"
archiveDateFormat="yyyyMMdd"
- maxArchiveFiles="14" />
+ maxArchiveFiles="7" />
From 0c7f02a95588a69808d470be8e6f44d6e34d7e5a Mon Sep 17 00:00:00 2001
From: dovholuknf <46322585+dovholuknf@users.noreply.github.com>
Date: Fri, 20 Nov 2020 17:14:27 -0500
Subject: [PATCH 10/25] wip nov20 - big button turns service off. popup turns
it back on... UX needs work now
---
DesktopEdge/MainWindow.xaml | 4 +-
DesktopEdge/MainWindow.xaml.cs | 148 ++++++++++++++----
.../DataStructures/DataStructures.cs | 6 +-
ZitiDesktopEdge.Client/Server/IPCServer.cs | 45 +++++-
.../ServiceClient/AbstractClient.cs | 17 +-
.../ServiceClient/DataClient.cs | 36 +----
.../ServiceClient/MonitorClient.cs | 45 ++++--
ZitiUpdateService/UpdateService.cs | 7 +-
8 files changed, 215 insertions(+), 93 deletions(-)
diff --git a/DesktopEdge/MainWindow.xaml b/DesktopEdge/MainWindow.xaml
index 0db7bf5ee..fc22fbabd 100644
--- a/DesktopEdge/MainWindow.xaml
+++ b/DesktopEdge/MainWindow.xaml
@@ -143,7 +143,7 @@
-