示例#1
0
        public async Task ListenerLoop()
        {
            while (!StopServer)
            {
                var context = await Listener.GetContextAsync();

                if (StopServer)
                {
                    break;
                }

                HttpListenerRequest  rawRequest  = context.Request;
                HttpListenerResponse rawResponse = context.Response;

                Console.WriteLine("request came in: " + rawRequest.HttpMethod + " " + rawRequest.RawUrl);

                PolarisRequest  request  = new PolarisRequest(rawRequest);
                PolarisResponse response = new PolarisResponse();

                string     route = rawRequest.Url.AbsolutePath.TrimEnd('/').TrimStart('/');
                PowerShell PowerShellInstance = PowerShell.Create();
                PowerShellInstance.RunspacePool = PowerShellPool;
                try
                {
                    // this script has a sleep in it to simulate a long running script
                    PowerShellInstance.AddScript(ScriptBlockRoutes[route][rawRequest.HttpMethod]);
                    PowerShellInstance.AddParameter(nameof(request), request);
                    PowerShellInstance.AddParameter(nameof(response), response);

                    var res = PowerShellInstance.BeginInvoke <PSObject>(new PSDataCollection <PSObject>(), new PSInvocationSettings(), (result) => {
                        if (PowerShellInstance.InvocationStateInfo.State == PSInvocationState.Failed)
                        {
                            Console.WriteLine(PowerShellInstance.InvocationStateInfo.Reason);
                            response.Send(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.SetStatusCode(500);
                        }
                        Send(rawResponse, response);
                        PowerShellInstance.Dispose();
                    }, null);
                }
                catch (Exception e)
                {
                    if (e is KeyNotFoundException)
                    {
                        Send(rawResponse, System.Text.Encoding.UTF8.GetBytes("Not Found"), 404, "text/plain; charset=UTF-8");
                        Console.WriteLine("404 Not Found");
                    }
                    else
                    {
                        Console.WriteLine(e.Message);
                        throw e;
                    }
                }
            }

            Listener.Close();
            PowerShellPool.Dispose();
        }
示例#2
0
        public async Task ListenerLoop()
        {
            while (!StopServer)
            {
                HttpListenerContext context = null;
                try
                {
                    context = await Listener.GetContextAsync();
                }
                catch (Exception e)
                {
                    if (!(e is ObjectDisposedException))
                    {
                        throw;
                    }
                }

                if (StopServer || context == null)
                {
                    if (Listener != null)
                    {
                        Listener.Close();
                    }
                    break;
                }

                HttpListenerRequest  rawRequest  = context.Request;
                HttpListenerResponse rawResponse = context.Response;

                Log("request came in: " + rawRequest.HttpMethod + " " + rawRequest.RawUrl);

                PolarisRequest  request  = new PolarisRequest(rawRequest);
                PolarisResponse response = new PolarisResponse();

                string     route = rawRequest.Url.AbsolutePath.TrimEnd('/').TrimStart('/');
                PowerShell PowerShellInstance = PowerShell.Create();
                PowerShellInstance.RunspacePool = PowerShellPool;
                try
                {
                    // Set up PowerShell instance by making request and response global
                    PowerShellInstance.AddScript(PolarisHelperScripts.InitializeRequestAndResponseScript);
                    PowerShellInstance.AddParameter("req", request);
                    PowerShellInstance.AddParameter("res", response);

                    // Run middleware in the order in which it was added
                    foreach (PolarisMiddleware middleware in RouteMiddleware)
                    {
                        PowerShellInstance.AddScript(middleware.ScriptBlock);
                    }

                    PowerShellInstance.AddScript(ScriptBlockRoutes[route][rawRequest.HttpMethod]);

                    var res = PowerShellInstance.BeginInvoke <PSObject>(new PSDataCollection <PSObject>(), new PSInvocationSettings(), (result) => {
                        // Handle errors
                        if (PowerShellInstance.InvocationStateInfo.State == PSInvocationState.Failed)
                        {
                            Log(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.Send(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.SetStatusCode(500);
                        }
                        else if (PowerShellInstance.HadErrors)
                        {
                            var errorsBody = "\n";
                            for (int i = 0; i < PowerShellInstance.Streams.Error.Count; i++)
                            {
                                errorsBody += "[" + i + "]:\n";
                                errorsBody += PowerShellInstance.Streams.Error[i].Exception.ToString();
                                errorsBody += PowerShellInstance.Streams.Error[i].InvocationInfo.PositionMessage + "\n\n";
                            }
                            response.Send(errorsBody);
                            response.SetStatusCode(500);
                        }

                        // Handle logs
                        if (request.Query[GetLogsString] != null)
                        {
                            var informationBody = "\n";
                            for (int i = 0; i < PowerShellInstance.Streams.Information.Count; i++)
                            {
                                foreach (var tag in PowerShellInstance.Streams.Information[i].Tags)
                                {
                                    informationBody += "[" + tag + "]";
                                }

                                informationBody += PowerShellInstance.Streams.Information[i].MessageData.ToString() + "\n";
                            }
                            informationBody += "\n";

                            // Set response to the logs and the actual response (could be errors)
                            var logBytes = System.Text.Encoding.UTF8.GetBytes(informationBody);
                            var bytes    = new byte[logBytes.Length + response.ByteResponse.Length];
                            logBytes.CopyTo(bytes, 0);
                            response.ByteResponse.CopyTo(bytes, logBytes.Length);
                            response.ByteResponse = bytes;
                        }

                        Send(rawResponse, response);
                        PowerShellInstance.Dispose();
                    }, null);
                }
                catch (Exception e)
                {
                    if (e is KeyNotFoundException)
                    {
                        Send(rawResponse, System.Text.Encoding.UTF8.GetBytes("Not Found"), 404, "text/plain; charset=UTF-8");
                        Log("404 Not Found");
                    }
                    else
                    {
                        Log(e.Message);
                        throw e;
                    }
                }
            }
        }
示例#3
0
        public async Task ListenerLoop()
        {
            while (!StopServer)
            {
                HttpListenerContext context = null;
                try
                {
                    context = await Listener.GetContextAsync();
                }
                catch (Exception e)
                {
                    if (!(e is ObjectDisposedException))
                    {
                        throw;
                    }
                }

                if (StopServer || context == null)
                {
                    if (Listener != null)
                    {
                        Listener.Close();
                    }
                    break;
                }

                HttpListenerRequest  rawRequest  = context.Request;
                HttpListenerResponse rawResponse = context.Response;

                Log("request came in: " + rawRequest.HttpMethod + " " + rawRequest.RawUrl);

                PolarisRequest  request  = new PolarisRequest(rawRequest);
                PolarisResponse response = new PolarisResponse();

                string     route = rawRequest.Url.AbsolutePath.TrimEnd('/').TrimStart('/');
                PowerShell PowerShellInstance = PowerShell.Create();
                PowerShellInstance.RunspacePool = PowerShellPool;
                try
                {
                    // Set up PowerShell instance by making request and response global
                    PowerShellInstance.AddScript(PolarisHelperScripts.InitializeRequestAndResponseScript);
                    PowerShellInstance.AddParameter("req", request);
                    PowerShellInstance.AddParameter("res", response);

                    // Run middleware in the order in which it was added
                    foreach (PolarisMiddleware middleware in RouteMiddleware)
                    {
                        PowerShellInstance.AddScript(middleware.ScriptBlock);
                    }

                    PowerShellInstance.AddScript(ScriptBlockRoutes[route][rawRequest.HttpMethod]);

                    var res = PowerShellInstance.BeginInvoke <PSObject>(new PSDataCollection <PSObject>(), new PSInvocationSettings(), (result) => {
                        if (PowerShellInstance.InvocationStateInfo.State == PSInvocationState.Failed)
                        {
                            Log(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.Send(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.SetStatusCode(500);
                        }
                        Send(rawResponse, response);
                        PowerShellInstance.Dispose();
                    }, null);
                }
                catch (Exception e)
                {
                    if (e is KeyNotFoundException)
                    {
                        Send(rawResponse, System.Text.Encoding.UTF8.GetBytes("Not Found"), 404, "text/plain; charset=UTF-8");
                        Log("404 Not Found");
                    }
                    else
                    {
                        Log(e.Message);
                        throw e;
                    }
                }
            }
        }