protected override void OnSetUp()
        {
            base.OnSetUp();
            SimpleHttpContext context = SimpleHttpContext.Create("http://localhost");

            sessionStorage = new AmplaSessionStorage(context.Session);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Writes fatal error response as JSON if command execution failed completely.
        /// </summary>
        protected string WriteFatalResponse(SimpleHttpContext context, Exception ex)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    writer.WriteStartObject("output");
                    writer.WritePropertyValue("success", 0);
                    writer.WritePropertyValue("code", 1);
                    writer.WritePropertyValue("message", ex.Message ?? "A fatal error occurred");
                    writer.WriteEndObject();
                    WriteErrorsObject(writer, new List <Exception>()
                    {
                        ex
                    });
                    writer.WriteEndObject();
                }
            }
            catch (Exception exx)
            {
                _errorHandler?.LogError(exx);
            }
            return(json.ToString());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Executes 'GetStats' command.
        /// </summary>
        private string GetStats(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    foreach (IStatsWriter stats in _statsWriters)
                    {
                        stats.WriteRuntimeStatistics(writer);
                    }
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Exemplo n.º 4
0
        /// <summary>
        /// Executes 'Ping' command.
        /// </summary>
        private string Ping(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                using (var writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    _statsWriters
                    .Where(sw => sw is ServiceState)
                    .FirstOrDefault()?
                    .WriteRuntimeStatistics(writer);
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Exemplo n.º 5
0
        /// <summary>
        /// Executes 'Read' command.
        /// </summary>
        private string Read(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                string input1 = _gpio.GetBank(BankType.Input1);
                string input2 = _gpio.GetBank(BankType.Input2);
                string output = _gpio.GetBank(BankType.Output);

                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    writer.WriteStartObject("output");
                    writer.WritePropertyValue("success", 1);
                    writer.WritePropertyValue("input1", input1);
                    writer.WritePropertyValue("input2", input2);
                    writer.WritePropertyValue("output", output);
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Exemplo n.º 6
0
        /// <summary>
        /// Executes 'GetLogs' command.
        /// </summary>
        private string GetLogs(SimpleHttpContext context)
        {
            StringBuilder text = new StringBuilder();

            try
            {
                Int32.TryParse(context.Query.Get("maxLines"), out int maxLines);
                if (maxLines <= 0)
                {
                    maxLines = 1000;
                }

                Double.TryParse(context.Query.Get("minutes"), out double minutes);
                if (minutes == 0)
                {
                    minutes = 1440 * 7;
                }
                if (minutes > 1000000)
                {
                    minutes = 1000000;
                }

                List <string> lines = ((Log)Log.Instance).GetLog(maxLines, minutes);
                lines.ForEach(l => text.AppendLine(l));
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(ex.Message);
            }
            return(text.ToString());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Handles HTTP request.
        /// </summary>
        protected override async Task HandleRequest(SimpleHttpContext context)
        {
            string json;

            switch (context.Command)
            {
            case "read":
                json = Read(context);
                await context.WriteJson(json);

                break;

            case "write":
                json = Write(context);
                await context.WriteJson(json);

                break;

            case "readwrite":
                json = ReadWrite(context);
                await context.WriteJson(json);

                break;

            default:
                string message = "Command not found";
                await context.WriteError(message, 404);

                throw new Exception(message);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Executes 'Write' command.
        /// </summary>
        private string Write(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                string output = context.Query.Get("output");
                if (String.IsNullOrWhiteSpace(output))
                {
                    throw new Exception("Parameter 'output' missing or invalid");
                }
                _gpio.SetBank(BankType.Output, output);

                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    writer.WriteStartObject("output");
                    writer.WritePropertyValue("success", 1);
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
Exemplo n.º 9
0
        /// <summary>
        /// Executes 'Set Device Name' command.
        /// </summary>
        private string SetDeviceName(SimpleHttpContext context)
        {
            StringBuilder json = new StringBuilder();

            try
            {
                string name = context.Query.Get("name");
                if (String.IsNullOrWhiteSpace(name))
                {
                    throw new Exception("Parameter 'name' is missing or invalid");
                }

                _config.DeviceName = name;
                using (SimpleJsonWriter writer = new SimpleJsonWriter(json))
                {
                    writer.WriteStartObject();
                    WriteServiceObject(writer, true);
                    WriteDeviceObject(writer);
                    WriteRequestObject(writer, context);
                    writer.WriteStartObject("output");
                    writer.WritePropertyValue("success", 1);
                    writer.WritePropertyValue("code", 0);
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                }
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                return(WriteFatalResponse(context, ex));
            }
            return(json.ToString());
        }
        public void AutomaticLoginFromSession()
        {
            SimpleSecurityWebServiceClient webServiceClient = new SimpleSecurityWebServiceClient("User");

            webServiceClient.AddExistingSession("User");

            string session = webServiceClient.Sessions[0].SessionId;
            string url     = "http://localhost/?amplaSession=" + session;

            context = SimpleHttpContext.Create(url);

            IAmplaUserService amplaUserService = new AmplaUserService(webServiceClient, new AmplaUserStore());

            Assert.That(SessionStorage.GetAmplaSession(), Is.Empty);

            LoginAmplaSessionUsingQueryString loginAmplaSession = new LoginAmplaSessionUsingQueryString(context.Request, context.Response, amplaUserService, FormsAuthenticationService, SessionStorage);

            loginAmplaSession.Execute();

            Assert.That(context.Request.Cookies, Is.Not.Empty);
            Assert.That(context.Request.Url, Is.EqualTo(new Uri("http://localhost/")));

            Assert.That(SessionStorage.GetAmplaSession(), Is.EqualTo(session));

            var ticket = FormsAuthenticationService.GetUserTicket();

            Assert.That(ticket, Is.Not.Null);
            Assert.That(ticket.UserData, Is.EqualTo(session));
        }
Exemplo n.º 11
0
        protected override void OnSetUp()
        {
            base.OnSetUp();
            context = SimpleHttpContext.Create("http://localhost");

            securityWebService = new SimpleSecurityWebServiceClient("User");
            amplaUserService   = new AmplaUserService(securityWebService, new AmplaUserStore());
        }
Exemplo n.º 12
0
        protected override void OnSetUp()
        {
            base.OnSetUp();
            webServiceClient = new SimpleSecurityWebServiceClient("User");
            amplaUserStore   = new AmplaUserStore();
            amplaUserService = new AmplaUserService(webServiceClient, amplaUserStore);

            context = SimpleHttpContext.Create("http://localhost");

            controller = new AccountController(amplaUserService, FormsAuthenticationService, AmplaSessionStorage);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Handles HTTP request.
        /// </summary>
        protected override async Task HandleRequest(SimpleHttpContext context)
        {
            string json, html, text;

            switch (context.Command)
            {
            case "ping":
                json = Ping(context);
                await context.WriteJson(json);

                break;

            case "getstats":
                json = GetStats(context);
                await context.WriteJson(json);

                break;

            case "getstatshtml":
                json = GetStats(context);
                html = StatsToHtml.GetStatsHtml(json);
                await context.WriteHtml(html);

                break;

            case "getlogs":
                text = GetLogs(context);
                await context.WriteText(text);

                break;

            case "pstree":
                text = PsTree(context);
                context.Response.ContentType = "text/plain";
                await context.Response.WriteAsync(text);

                break;

            case "ps":
                text = Ps(context);
                context.Response.ContentType = "text/plain";
                await context.Response.WriteAsync(text);

                break;

            default:
                string message = "Command not found";
                await context.WriteError(message, 404);

                throw new Exception(message);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Writes the 'request' object for all commands.
        /// </summary>
        public void WriteRequestObject(SimpleJsonWriter writer, SimpleHttpContext context)
        {
            IDictionary <string, string[]> qs = context.Query.GetAll();

            writer.WriteStartObject("request");
            writer.WritePropertyValue("handler", context.Handler);
            writer.WritePropertyValue("command", context.Command);
            foreach (string key in qs.Keys)
            {
                writer.WritePropertyValue(key, qs[key].Length > 0 ? qs[key][0] : null);
            }
            writer.WritePropertyValue("elapsedMS", context.Stopwatch.ElapsedMilliseconds);
            writer.WriteEndObject();
        }
Exemplo n.º 15
0
        public void DisabledSessionStorageDoesntThrow()
        {
            context = context.WithSessionsDisabled();
            Assert.That(context.Session.Enabled, Is.False);

            securityWebService.AddExistingSession("User");
            string    session = securityWebService.Sessions[0].SessionId;
            string    message;
            AmplaUser user = amplaUserService.SessionLogin(session, out message);

            Assert.That(user, Is.Not.Null);
            FormsAuthenticationService.StoreUserTicket(user, false);

            context.Response.Redirect("http://localhost/Production");

            new AlignSessionWithFormsAuthentication(context.Request, AmplaSessionStorage, FormsAuthenticationService).Execute();

            Assert.That(AmplaSessionStorage.GetAmplaSession(), Is.Empty);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Executes 'ps' command.
        /// </summary>
        private string Ps(SimpleHttpContext context)
        {
            try
            {
                if (_config.IsWindows)
                {
                    return("No Windows OS support");
                }

                string args = context.Query.Get("args") ?? "-e -o pid,uname,pcpu,pmem,comm --sort -pcpu";
                string data = $"ps {args}".Bash(2500, true);

                return(data);
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
            }
            return("");
        }
Exemplo n.º 17
0
        /// <summary>
        /// Executes 'pstree' command.
        /// </summary>
        private string PsTree(SimpleHttpContext context)
        {
            try
            {
                if (_config.IsWindows)
                {
                    return("No Windows OS support");
                }

                string args = context.Query.Get("args") ?? "-cg";
                string data = $"pstree {args}".Bash(2500, true);

                return(data);
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
            }
            return("");
        }
Exemplo n.º 18
0
        /// <summary>
        /// Handles an HTTP request, performs some helper stuff, passes execution to instance method.
        /// </summary>
        public async Task ProcessRequest(SimpleHttpContext context)
        {
            try
            {
                string log = context.Query.Get("log") ?? "1";
                if ((log == "1") || (log == "true"))
                {
                    _logger?.WriteMessage("Http", $"Handling request: {context.Url}");
                }

                await HandleRequest(context);

                _serviceStats.LogCommand(context.Path, context.Stopwatch.Elapsed, true);
            }
            catch (Exception ex)
            {
                _errorHandler?.LogError(ex);
                throw;
            }
        }
Exemplo n.º 19
0
        public void Run()
        {
            TcpListener server = new TcpListener(IPAddress.Any, _port);
            server.Start();

            try
            {
                while (true)
                {
                    TcpClient socket = server.AcceptTcpClient();

                    using (var context = new SimpleHttpContext(socket, _logger))
                    {
                        _requestHandler(context);
                    }
                }
            }
            finally
            {
                server.Stop();
            }
        }
        public void NoSession()
        {
            SimpleSecurityWebServiceClient webServiceClient = new SimpleSecurityWebServiceClient("User");

            const string session = "invalid";

            const string url = "http://localhost/?amplaSession=" + session;

            context = SimpleHttpContext.Create(url);

            IAmplaUserService amplaUserService = new AmplaUserService(webServiceClient, new AmplaUserStore());

            LoginAmplaSessionUsingQueryString loginAmplaSession = new LoginAmplaSessionUsingQueryString(context.Request, context.Response, amplaUserService, FormsAuthenticationService, SessionStorage);

            loginAmplaSession.Execute();

            Assert.That(context.Request.Cookies, Is.Empty);
            Assert.That(context.Request.Url, Is.EqualTo(new Uri(url)));

            var ticket = FormsAuthenticationService.GetUserTicket();

            Assert.That(ticket, Is.Null);
            Assert.That(SessionStorage.GetAmplaSession(), Is.Empty);
        }
Exemplo n.º 21
0
        private void HandleHttpRequest(SimpleHttpContext context)
        {
            //Beep();

            if (context.Request.Method == "POST")
            {
                if (context.Request.Url.Path.Equals("/notify"))
                {
                    var region = context.Request.Url.QueryParameters["region"].First();

                    if (_profileLoaded)
                    {
                        var command = Command.Parse("CLICK " + region);

                        if (command == null)
                        {
                            Log("No key sequence found for " + region);
                            context.Response.StatusCode = HttpStatusCode.NotFound;
                            context.Response.StatusDescription = "Not Found";
                        }
                        else
                        {
                            Log("Sending keys for region " + region);
                            command.Execute(this);
                        }
                    }
                    else
                    {
                        Log("No profile loaded!");
                        Beep();
                    }
                }
            }
            else if (context.Request.Method == "GET")
            {
                var resource = GetResourceForUrl(context.Request.Url.Path);

                if (resource == null)
                {
                    Log("Could not map resource for URL" + context.Request.Url);
                    context.Response.StatusCode = HttpStatusCode.NotFound;
                    context.Response.StatusDescription = "Not Found";
                }
                else
                {
                    using (var stream = GetResourceStream(resource))
                    {
                        if (stream == null)
                        {
                            Log("Could not load resource for " + resource);
                            context.Response.StatusCode = HttpStatusCode.NotFound;
                            context.Response.StatusDescription = "Not Found";
                            context.Write("Not found");
                        }
                        else
                        {
                            Log("Found resource " + resource);
                            context.Response.ContentType = GetContentTypeForResource(resource);
                            context.Write(stream);
                        }
                    }
                }
            }
            else
            {
                Log("No support for method " + context.Request.Method);
                context.Response.StatusCode = HttpStatusCode.MethodNotAllowed;
                context.Response.StatusDescription = "Method Not Allowed";
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// Instance method to handle specific path request.
 /// </summary>
 protected abstract Task HandleRequest(SimpleHttpContext context);
 protected override void OnSetUp()
 {
     base.OnSetUp();
     context = SimpleHttpContext.Create("http://localhost");
 }
Exemplo n.º 24
0
 public virtual void OnPageLoad(SimpleHttpContext ctx)
 {
 }