Skip to content

Commit

Permalink
Added Support for Executing Individual commands over API
Browse files Browse the repository at this point in the history
  • Loading branch information
saucepleez committed Dec 3, 2019
1 parent 585ff14 commit 8f50d74
Show file tree
Hide file tree
Showing 5 changed files with 148 additions and 39 deletions.
1 change: 1 addition & 0 deletions taskt/Core/Automation/Commands/RemoteTaskCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public class RemoteTaskCommand : ScriptCommand
[Attributes.PropertyAttributes.PropertyUISelectionOption("Run Raw Script Data")]
[Attributes.PropertyAttributes.PropertyUISelectionOption("Run Local File")]
[Attributes.PropertyAttributes.PropertyUISelectionOption("Run Remote File")]
[Attributes.PropertyAttributes.PropertyUISelectionOption("Run Command Json")]
[Attributes.PropertyAttributes.InputSpecification("Select the necessary parameter.")]
[Attributes.PropertyAttributes.Remarks("")]
public string v_ParameterType { get; set; }
Expand Down
106 changes: 88 additions & 18 deletions taskt/Core/Server/LocalTCPListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ namespace taskt.Core.Server
public static class LocalTCPListener
{
public static Automation.Engine.AutomationEngineInstance automationInstance;
public static Automation.Engine.AutomationEngineInstance ExecuteCommandEngine;
private static Serilog.Core.Logger automationLogger;
public static TcpListener automationListener;
private static LocalListenerSettings listenerSettings;
Expand All @@ -30,6 +31,7 @@ public static class LocalTCPListener
static LocalTCPListener()
{
automationLogger = new Core.Logging().CreateLogger("Automation Client", Serilog.RollingInterval.Day);
ExecuteCommandEngine = new Automation.Engine.AutomationEngineInstance();
}

public static void Initialize(UI.Forms.frmScriptBuilder builder)
Expand Down Expand Up @@ -140,17 +142,17 @@ public static void StartAutomationListener(int port)
//get list of ip
var enabledIPs = listenerSettings.IPWhiteList.Split(',');

if (enabledIPs.Any( s => s.Trim().Contains(clientAddress)))
if (enabledIPs.Any(s => s.Trim().Contains(clientAddress)))
{
automationLogger.Information($"Client '{clientAddress}' verified from WhiteList '{listenerSettings.IPWhiteList}'");
automationLogger.Information($"Client '{clientAddress}' verified from WhiteList '{listenerSettings.IPWhiteList}'");
}
else
{
automationLogger.Information($"Closing Client Connection due to IP verification failure");
SendResponse(ResponseCode.Unauthorized, $"Unauthorized", stream);
return;
}

}
else
{
Expand Down Expand Up @@ -207,7 +209,7 @@ public static void StartAutomationListener(int port)
{
automationLogger.Information($"Error Occured Reading Stream: {ex.ToString()}");
}

// Shutdown and end connection
client.Close();
automationLogger.Information($"Client Connection Closed");
Expand Down Expand Up @@ -263,7 +265,7 @@ private static void ProcessRequest(string data, string[] messageContent, Network
return;
}


if (dataParameter.TryParseBase64(out var base64SourceString))
{
automationLogger.Information($"Client Passed Base64 String: {base64SourceString}");
Expand All @@ -274,7 +276,7 @@ private static void ProcessRequest(string data, string[] messageContent, Network
automationLogger.Information($"Client Did Not Pass Base64 String");
}


//check if data parameter references file location
if (isFileLocation)
{
Expand Down Expand Up @@ -302,7 +304,7 @@ private static void ProcessRequest(string data, string[] messageContent, Network
//log execution
automationLogger.Information($"Executing Script: {dataParameter}");


//invoke builder and pass it script data to execute
associatedBuilder.Invoke(new MethodInvoker(delegate ()
{
Expand All @@ -313,15 +315,14 @@ private static void ProcessRequest(string data, string[] messageContent, Network
newEngine.Show();
}));



if (data.StartsWith("POST /AwaitScript"))
{
//reset result value
TasktResult = "";

//add reference to script finished event
automationInstance.ScriptFinishedEvent += AutomationInstance_ScriptFinishedEvent;
automationInstance.ScriptFinishedEvent += AutomationInstance_ScriptFinishedEvent;

//wait for script to finish before returning
do
Expand All @@ -339,9 +340,69 @@ private static void ProcessRequest(string data, string[] messageContent, Network
SendResponse(ResponseCode.OK, "Script Launched Successfully", stream);
}




}
else if (data.StartsWith("POST /ExecuteCommand"))
{
automationLogger.Information($"Client Requests Command Execution");

//locate the body content
string dataParameter = "";

//find the script parameter
foreach (var item in messageContent)
{
if (item.StartsWith("CommandData: "))
{
dataParameter = item.Replace("CommandData: ", "");
break;
}
}

//check to see if nothing was provided
if (string.IsNullOrEmpty(dataParameter))
{
automationLogger.Information($"Client Command Data Not Found");
return;
}


if (dataParameter.TryParseBase64(out var base64SourceString))
{
automationLogger.Information($"Client Passed Base64 String: {base64SourceString}");
dataParameter = base64SourceString;
}
else
{
automationLogger.Information($"Client Did Not Pass Base64 String");
}

try
{
//deserialize command
var command = Newtonsoft.Json.JsonConvert.DeserializeObject(dataParameter, new Newtonsoft.Json.JsonSerializerSettings() { TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All });

//log execution
automationLogger.Information($"Executing Command: {dataParameter}");

//define script action
var scriptAction = new Script.ScriptAction() { ScriptCommand = (Core.Automation.Commands.ScriptCommand)command };

//execute command
ExecuteCommandEngine.ExecuteCommand(scriptAction);

//send back response
SendResponse(ResponseCode.OK, "Command Executed Successfully", stream);
}
catch (Exception ex)
{
SendResponse(ResponseCode.InternalServerError, $"An error occured: {ex.ToString()}", stream);
}


}

else if (data.StartsWith("POST /EngineStatus"))
{
automationLogger.Information($"Returning Engine Status: {Client.ClientStatus}");
Expand Down Expand Up @@ -424,7 +485,7 @@ public static string SendAutomationTask(string endpoint, string parameterType, s
//check type of execution needed
if (parameterType == "Run Raw Script Data")
{


//handle await preference
if (awaitPreference == "Await For Result")
Expand Down Expand Up @@ -488,6 +549,15 @@ public static string SendAutomationTask(string endpoint, string parameterType, s
//add script parameter
request.AddParameter("ScriptLocation", scriptData, RestSharp.ParameterType.HttpHeader);
}
else if (parameterType == "Run Command Json")
{

request.Resource = "/ExecuteCommand";

//add script data
request.AddParameter("CommandData", scriptData.ToBase64(), RestSharp.ParameterType.HttpHeader);

}
else if (parameterType == "Get Engine Status")
{
request.Resource = "/EngineStatus";
Expand All @@ -498,7 +568,7 @@ public static string SendAutomationTask(string endpoint, string parameterType, s
}

request.Timeout = int.Parse(timeout);


RestSharp.IRestResponse resp = client.Execute(request);

Expand All @@ -518,15 +588,15 @@ public static string SendAutomationTask(string endpoint, string parameterType, s
public static string GetListeningAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return $"{ip.ToString()}:{Port.ToString()}" ;
}
return $"{ip.ToString()}:{Port.ToString()}";
}
}

throw new Exception("No network adapters with an IPv4 address in the system!");
throw new Exception("No network adapters with an IPv4 address in the system!");
}
}
public enum ResponseCode
Expand Down
Loading

0 comments on commit 8f50d74

Please sign in to comment.