Beispiel #1
0
 public void GetImagePresentationURL(HttpServerRequest Request, string ReqEncoding, string ReqCompression, string ReqResolution, out string RetImagePresentationURL)
 {
     RetImagePresentationURL = HttpUtilities.CreateFullUrl(Request.Url,
                                                           "/html?Encoding=" + ReqEncoding +
                                                           "&Compression=" + ReqCompression +
                                                           "&Resolution=" + ReqResolution);
 }
        protected override void HandleHttpRequest(Connection connection, HttpServerRequest request, HttpServerResponse response)
        {
            base.HandleHttpRequest(connection, request, response);

            if (response.ContentSource != ContentSource.ContentNone)
            {
                return;
            }

            if (request.Header.RequestType != "GET")
            {
                response.SendError(HttpStatusCode.BadRequest, String.Format("Request Type '{0}' not supported.", request.Header.RequestType));
                return;
            }

            String lPath = RootPath + request.Header.RequestPath.Replace('/', Path.DirectorySeparatorChar);

            if (lPath.IndexOf("..") > -1)
            {
                response.SendError(HttpStatusCode.Forbidden, String.Format("Bad Request: Path '{0}' contains '..' which is invalid.", lPath));
                return;
            }

            if (!File.Exists(lPath))
            {
                response.SendError(HttpStatusCode.NotFound, String.Format("File '{0}' not found.", lPath));
                return;
            }

            response.Header.ContentType = "text/html";
            response.ContentStream      = new FileStream(lPath, FileOpenMode.ReadOnly);
            response.CloseStream        = true;      /* Response will close stream once it's been sent */
        }
 public HttpRequestEventArgs(Connection connection, HttpServerRequest request, HttpServerResponse response)
     : base(connection)
 {
     this.fRequest  = request;
     this.fResponse = response;
     this.Handled   = false;
 }
Beispiel #4
0
        private void OnHttpServerRequest(HttpServerRequest httpRequest, HttpServerResponse httpResponse)
        {
            UrlData     urlData = Url.Parse(httpRequest.Url, /* parseQueryString */ true);
            ServerRoute route   = _router.Match(urlData.PathName);

            Action <Exception> errorHandler = delegate(Exception e) {
                httpResponse.WriteHead(HttpStatusCode.InternalServerError, e.Message);
                httpResponse.End();

                Runtime.TraceInfo("500 : %s %s", httpRequest.Method, httpRequest.Url);
                return;
            };

            ServerRequest         request      = new ServerRequest(httpRequest, urlData, route);
            Task <ServerResponse> responseTask = null;

            try {
                responseTask = _modules[0].ProcessRequest(request);
            }
            catch (Exception e) {
                errorHandler(e);
                return;
            }

            responseTask.Done(delegate(ServerResponse response) {
                response.Write(httpResponse);

                Runtime.TraceInfo("%d : %s %s", response.StatusCode, httpRequest.Method, httpRequest.Url);
            })
            .Fail(errorHandler);
        }
Beispiel #5
0
        // define custom virtual page
        public override async Task <bool> rewrite(System.IO.Stream resp, HttpServerRequest req)
        {
            String tempPath = req.path;

            if (req.path.IndexOf("?") != -1)
            {
                tempPath = tempPath.Substring(0, req.path.IndexOf("?"));
            }
            switch (tempPath)
            {
            // generate virtual page for url /hello.png
            case "/hello.png":
                //Download image from internet and return as local page
                byte[] imageByte = await DownloadImageFromWebsiteAsync("https://assets.windowsphone.com/db658987-b7ca-43aa-885c-fd4426fb6962/Downloads-VS_InvariantCulture_Default.png");

                String contentType = Util.getContentType("/hello.png");
                //Write header
                string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                              "Content-Length: {0}\r\n" + contentType +
                                              "Cache-Control: no-cache, no-store, must-revalidate\r\nPragma: no-cache\r\nExpires: 0\r\n" +
                                              "Connection: close\r\n\r\n",
                                              imageByte.Length);

                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                //Write response
                await resp.WriteAsync(headerArray, 0, headerArray.Length);

                await resp.WriteAsync(imageByte, 0, imageByte.Length);

                return(true);

                break;
            }
            return(false);
        }
Beispiel #6
0
        internal ServerRequest(HttpServerRequest httpRequest, UrlData urlData, ServerRoute route)
        {
            _httpRequest = httpRequest;

            _urlData = urlData;
            _route   = route;
        }
        // define custom virtual page
        public override async Task<bool> rewrite(System.IO.Stream resp, HttpServerRequest req)
        {
            String tempPath = req.path;
            if (req.path.IndexOf("?") != -1)
                tempPath = tempPath.Substring(0, req.path.IndexOf("?"));
            switch (tempPath)
            {
                // generate virtual page for url /hello.png
                case "/hello.png":
                    //Download image from internet and return as local page
                    byte[] imageByte = await DownloadImageFromWebsiteAsync("https://assets.windowsphone.com/db658987-b7ca-43aa-885c-fd4426fb6962/Downloads-VS_InvariantCulture_Default.png");

                        String contentType = Util.getContentType("/hello.png");
                    //Write header
                    string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                    "Content-Length: {0}\r\n" + contentType +
                                    "Cache-Control: no-cache, no-store, must-revalidate\r\nPragma: no-cache\r\nExpires: 0\r\n" +
                                    "Connection: close\r\n\r\n",
                                    imageByte.Length);

                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    //Write response
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                    await resp.WriteAsync(imageByte, 0, imageByte.Length);

                    return true;
                    break;

            }
            return false;
        }
 public async override Task<string> render(HttpServerRequest req)
 {
     //html = html.Replace("<%text_type_password%>", Util.loader.GetString("TypePassword"));
     if (req.getParameters.ContainsKey("p"))
     {
     
         switch (req.getParameters["p"])
         {
             /*case "i":
                 return Convert.ToInt32(App.IsTrial) + ";" + Convert.ToInt32(this.httpServer.removeLogin);*/
             case "l":
                 bool logged = false;
                 {
                     if (req.getParameters.ContainsKey("password"))
                     {
                         String password = "";
                         if (Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey("password"))
                             password = (string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["password"];
                         else
                             password = "******";
                         if (req.getParameters["password"].Equals(password))
                         {
                             logged = true;
                             Util.authorizedIp.Add(httpServer.lastIpAddress);
                         }
                     }
                 }
                 return Convert.ToInt32(logged)+"";
             default:
                 return "";
         }
     }else
         return req.html;
 }
        public async Task Invoke(HttpContext context, IEnumerable <IHttpServerEventCallback> callbacks)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (callbacks == null)
            {
                throw new ArgumentNullException(nameof(callbacks));
            }

            var stopwatch = Stopwatch.StartNew();

            callbacks.Invoke(() => HttpServerRequest.Create(context));

            try
            {
                await _next(context);
            }
            catch (HttpException e)
            {
                await WriteResponse(context, e.StatusCode, e.Message);
            }
            catch (Exception e)
            {
                await WriteResponse(context, HttpStatusCode.InternalServerError, "FAIL!");

                callbacks.Invoke(() => HttpServerException.Create(context, stopwatch.ElapsedMilliseconds, e));
            }

            callbacks.Invoke(() => HttpServerResponse.Create(context, stopwatch.ElapsedMilliseconds));
        }
Beispiel #10
0
        /// <summary>
        /// Class handling export of sensor data to RDF.
        /// </summary>
        /// <param name="Output">RDF will be output here.</param>
        /// <param name="Request">HTTP Request resulting in the generation of the RDF document.</param>
        public SensorDataRdfExport(StringBuilder Output, HttpServerRequest Request)
            : base()
        {
            this.turtle = new StringBuilder();
            this.Init(this.turtle, Request);

            this.xml = XmlWriter.Create(Output, XmlUtilities.GetXmlWriterSettings(false, false, true));
        }
        public void logs_one_item()
        {
            var httpServerRequest = HttpServerRequest.Create(_httpContext);

            _testSubject.Invoke(httpServerRequest);

            _logger.Logs.Count.ShouldBe(1);
        }
		/// <summary>
		/// Class handling export of sensor data to RDF.
		/// </summary>
		/// <param name="Output">RDF will be output here.</param>
		/// <param name="Request">HTTP Request resulting in the generation of the RDF document.</param>
		public SensorDataRdfExport (StringBuilder Output, HttpServerRequest Request)
			: base ()
		{
			this.turtle = new StringBuilder ();
			this.Init (this.turtle, Request);

			this.xml = XmlWriter.Create (Output, XmlUtilities.GetXmlWriterSettings (false, false, true));
		}
        public void serialise_server_request()
        {
            var httpServerRequest = HttpServerRequest.Create(_httpContext);

            httpServerRequest.Timestamp = new DateTimeOffset(2016, 11, 18, 19, 52, 6, TimeSpan.Zero).AddTicks(4425454);

            _testSubject.Invoke(httpServerRequest);

            _logger.Logs[0].ShouldBe("{\"eventType\":\"HttpServerRequest\",\"timestamp\":\"2016-11-18T19:52:06.4425454+00:00\",\"uri\":\"/ping?v=1\",\"method\":\"GET\",\"userAgent\":\"my-user-agent\"}");
        }
 // get info on uploaded file
  public override async Task<string> render(HttpServerRequest req)
  {
      PostParameter file= req.postParameters.Where(x => x.name == "upload").FirstOrDefault();
      if (file != null)
      {
         BasicProperties prop= await file.contentFile.GetBasicPropertiesAsync();
          req.html=req.html.Replace("<%FILEINFO%>", "File info:<br/>Name: "+Path.GetFileName(file.value)+"<br/>Size: "+(prop.Size/1000)+"KB");
      }else
          req.html=req.html.Replace("<%FILEINFO%>", "");
      return req.html;
  }
        private async Task HandleIncomingRequests6(CancellationToken ct)
        {
            while (!ct.IsCancellationRequested)
            {
                var tcpClient = await _tcpListener6.AcceptTcpClientAsync();

                var request = new HttpServerRequest(_scheduler, tcpClient, _localPort);
                request.Init(() => _requests.Remove(request), ct2 => HandleRequest(ct2, request));
                _requests.Add(request);
            }
        }
        public override void HandleRequestPart(byte[] stream, HttpServerRequest resultThisFar)
        {
            var word = stream.ReadNextWord();

            if (word.WordFound)
            {
                resultThisFar.HttpVersion = word.Word;
                UnparsedData = word.RemainingBytes;
                IsFinished = true;
                IsSucceeded = true;
            }
        }
        public override void HandleRequestPart(byte[] stream, HttpServerRequest resultThisFar)
        {
            var word = stream.ReadNextWord();

            if (word.WordFound)
            {
                resultThisFar.Uri = new Uri(word.Word, UriKind.RelativeOrAbsolute);
                UnparsedData = word.RemainingBytes;
                IsFinished = true;
                IsSucceeded = true;
            }
        }
        private static void HttpGetEvent(HttpServerResponse resp, HttpServerRequest req, string ContentType, ISensorDataExport ExportModule)
        {
            networkLed.High();
            try
            {
                double?Temperature = null;
                double?TemperatureDiff = null;
                double?Light = null;
                double?LightDiff = null;
                bool?  Motion = null;
                double d, d2;
                string s;
                bool   b;
                int    Timeout;

                if (!req.Query.TryGetValue("Timeout", out s) || !int.TryParse(s, out Timeout) || Timeout <= 0)
                {
                    throw new HttpException(HttpStatusCode.ClientError_BadRequest);
                }

                if (req.Query.TryGetValue("Temperature", out s) && XmlUtilities.TryParseDouble(s, out d) &&
                    req.Query.TryGetValue("TemperatureDiff", out s) && XmlUtilities.TryParseDouble(s, out d2) && d2 > 0)
                {
                    Temperature     = d;
                    TemperatureDiff = d2;
                }

                if (req.Query.TryGetValue("Light", out s) && XmlUtilities.TryParseDouble(s, out d) &&
                    req.Query.TryGetValue("LightDiff", out s) && XmlUtilities.TryParseDouble(s, out d2) && d2 > 0)
                {
                    Light     = d;
                    LightDiff = d2;
                }

                if (req.Query.TryGetValue("Motion", out s) && XmlUtilities.TryParseBoolean(s, out b))
                {
                    Motion = b;
                }

                if (!(Temperature.HasValue || Light.HasValue || Motion.HasValue))
                {
                    throw new HttpException(HttpStatusCode.ClientError_BadRequest);
                }

                lock (synchObject)
                {
                    pendingEvents.Add(new PendingEvent(Temperature, TemperatureDiff, Light, LightDiff, Motion, Timeout, resp, ContentType, ExportModule));
                }
            } finally
            {
                networkLed.Low();
            }
        }
        internal async Task<HttpServerRequest> ParseRequestStream(IInputStream requestStream)
        {
            var httpStream = new HttpRequestStream(requestStream);
            var request = new HttpServerRequest();

            try
            {
                var stream = await httpStream.ReadAsync(BUFFER_SIZE, InputStreamOptions.Partial);
                byte[] streamData = stream.Data;

                var requestPipeline = GetPipeline();
                using (var pipeLineEnumerator = requestPipeline.GetEnumerator())
                {
                    pipeLineEnumerator.MoveNext();
                    bool requestComplete = false;

                    while (!requestComplete)
                    {
                        pipeLineEnumerator.Current.HandleRequestPart(streamData, request);
                        streamData = pipeLineEnumerator.Current.UnparsedData;

                        if (pipeLineEnumerator.Current.IsFinished)
                        {
                            if (!pipeLineEnumerator.Current.IsSucceeded ||
                                !pipeLineEnumerator.MoveNext())
                            {
                                break;
                            }
                        }
                        else
                        {
                            var newStreamdata = await httpStream.ReadAsync(BUFFER_SIZE, InputStreamOptions.Partial);

                            if (!newStreamdata.ReadSuccessful)
                            {
                                break;
                            }

                            streamData = streamData.ConcatArray(newStreamdata.Data);
                        }
                    }
                }

                request.IsComplete = requestPipeline.All(p => p.IsSucceeded);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return request;
        }
        private static void HttpGetRoot(HttpServerResponse resp, HttpServerRequest req, bool Protected)
        {
            networkLed.High();
            try
            {
                string SessionId = req.Header.GetCookie("SessionId");
                string Host;

                resp.ContentType = "text/html";
                resp.Encoding    = System.Text.Encoding.UTF8;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                if ((!Protected) || CheckSession(SessionId))
                {
                    resp.Write("<html><head><title>Camera</title></head><body><h1>Welcome to Camera</h1><p>Below, choose what you want to do.</p><ul>");
                    resp.Write("<li><a href='/html'>View camera.</a></li>");

                    if (Protected)
                    {
                        resp.Write("<li><a href='/credentials'>Update login credentials.</a></li>");
                    }
                    else
                    {
                        int i;

                        Host = req.Header.Host;
                        if ((i = Host.IndexOf(':')) > 0)
                        {
                            Host = Host.Substring(0, i);
                        }

                        resp.Write("<li><a href='http://");
                        resp.Write(Host);
                        resp.Write(':');
                        resp.Write(upnpServer.Port.ToString());
                        resp.Write("/StillImage'>Still Image Web service.</a></li>");
                    }

                    resp.Write("</body></html>");
                }
                else
                {
                    OutputLoginForm(resp, string.Empty);
                }
            } finally
            {
                networkLed.Low();
            }
        }
        private static object CoapGetTurtle(CoapRequest Request, object Payload)
        {
            try
            {
                StringBuilder     sb               = new StringBuilder();
                HttpServerRequest HttpRequest      = Request.ToHttpRequest();
                ISensorDataExport SensorDataExport = new SensorDataTurtleExport(sb, HttpRequest);
                ExportSensorData(SensorDataExport, new ReadoutRequest(HttpRequest));

                return(sb.ToString());
            } catch (Exception ex)
            {
                Log.Exception(ex);
                return(ex.Message);
            }
        }
        // get info on uploaded file
        public override async Task <string> render(HttpServerRequest req)
        {
            PostParameter file = req.postParameters.Where(x => x.name == "upload").FirstOrDefault();

            if (file != null)
            {
                BasicProperties prop = await file.contentFile.GetBasicPropertiesAsync();

                req.html = req.html.Replace("<%FILEINFO%>", "File info:<br/>Name: " + Path.GetFileName(file.value) + "<br/>Size: " + (prop.Size / 1000) + "KB");
            }
            else
            {
                req.html = req.html.Replace("<%FILEINFO%>", "");
            }
            return(req.html);
        }
        private static object CoapGetRdf(CoapRequest Request, object Payload)
        {
            try
            {
                StringBuilder     sb               = new StringBuilder();
                HttpServerRequest HttpRequest      = Request.ToHttpRequest();
                ISensorDataExport SensorDataExport = new SensorDataRdfExport(sb, HttpRequest);
                ExportSensorData(SensorDataExport, new ReadoutRequest(HttpRequest));

                XmlDocument Xml = new XmlDocument();
                Xml.LoadXml(sb.ToString());
                return(Xml);
            } catch (Exception ex)
            {
                Log.Exception(ex);
                return(ex.Message);
            }
        }
        private static void HttpPostRoot(HttpServerResponse resp, HttpServerRequest req)
        {
            networkLed.High();
            try
            {
                FormParameters Parameters = req.Data as FormParameters;
                if (Parameters == null)
                {
                    throw new HttpException(HttpStatusCode.ClientError_BadRequest);
                }

                string UserName = Parameters ["UserName"];
                string Password = Parameters ["Password"];
                string Hash;
                object AuthorizationObject;

                GetDigestUserPasswordHash(UserName, out Hash, out AuthorizationObject);

                if (AuthorizationObject == null || Hash != CalcHash(UserName, Password))
                {
                    resp.ContentType = "text/html";
                    resp.Encoding    = System.Text.Encoding.UTF8;
                    resp.ReturnCode  = HttpStatusCode.Successful_OK;

                    Log.Warning("Invalid login attempt.", EventLevel.Minor, UserName, req.ClientAddress);
                    OutputLoginForm(resp, "<p>The login was incorrect. Either the user name or the password was incorrect. Please try again.</p>");
                }
                else
                {
                    Log.Information("User logged in.", EventLevel.Minor, UserName, req.ClientAddress);

                    string SessionId = CreateSessionId(UserName);
                    resp.SetCookie("SessionId", SessionId, "/");
                    resp.ReturnCode = HttpStatusCode.Redirection_SeeOther;
                    resp.AddHeader("Location", "/");
                    resp.SendResponse();
                    // PRG pattern, to avoid problems with post back warnings in the browser: http://en.wikipedia.org/wiki/Post/Redirect/Get
                }
            } finally
            {
                networkLed.Low();
            }
        }
Beispiel #25
0
 public override void HandleRequestPart(byte[] stream, HttpServerRequest resultThisFar)
 {
     if (resultThisFar.ContentLength == 0)
     {
         IsFinished = true;
         IsSucceeded = stream.Length == 0;
     }
     else
     {
         _content.AddRange(stream);
         if (_content.Count == resultThisFar.ContentLength)
         {
             resultThisFar.Content = _content.ToArray();
             IsFinished = true;
             IsSucceeded = true;
         }
         // else if content is bigger, finished will never be set, badrequest will happen
     }
 }
        private static void HttpGetCameraDevice(HttpServerResponse resp, HttpServerRequest req)
        {
            networkLed.High();
            try
            {
                string Xml;
                byte[] Data;
                int    c;

                using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Camera.UPnP.CameraDevice.xml"))
                {
                    c               = (int)stream.Length;
                    Data            = new byte[c];
                    stream.Position = 0;
                    stream.Read(Data, 0, c);
                    Xml = TextDecoder.DecodeString(Data, System.Text.Encoding.UTF8);
                }

                string HostName = System.Net.Dns.GetHostName();
                System.Net.IPHostEntry HostEntry = System.Net.Dns.GetHostEntry(HostName);

                foreach (System.Net.IPAddress Address in HostEntry.AddressList)
                {
                    if (Address.AddressFamily == req.ClientEndPoint.AddressFamily)
                    {
                        Xml = Xml.Replace("{IP}", Address.ToString());
                        break;
                    }
                }

                Xml = Xml.Replace("{PORT}", upnpServer.Port.ToString());
                Xml = Xml.Replace("{UDN}", defaultSettings.UDN);

                resp.ContentType = "text/xml";
                resp.Encoding    = System.Text.Encoding.UTF8;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                resp.Write(Xml);
            } finally
            {
                networkLed.Low();
            }
        }
Beispiel #27
0
        public async override Task <string> render(HttpServerRequest req)
        {
            //html = html.Replace("<%text_type_password%>", Util.loader.GetString("TypePassword"));
            if (req.getParameters.ContainsKey("p"))
            {
                switch (req.getParameters["p"])
                {
                /*case "i":
                 *  return Convert.ToInt32(App.IsTrial) + ";" + Convert.ToInt32(this.httpServer.removeLogin);*/
                case "l":
                    bool logged = false;
                    {
                        if (req.getParameters.ContainsKey("password"))
                        {
                            String password = "";
                            if (Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey("password"))
                            {
                                password = (string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["password"];
                            }
                            else
                            {
                                password = "******";
                            }
                            if (req.getParameters["password"].Equals(password))
                            {
                                logged = true;
                                Util.authorizedIp.Add(httpServer.lastIpAddress);
                            }
                        }
                    }
                    return(Convert.ToInt32(logged) + "");

                default:
                    return("");
                }
            }
            else
            {
                return(req.html);
            }
        }
        private static void GetImageProperties(HttpServerRequest req, out string Encoding, out byte Compression, out LinkSpriteJpegColorCamera.ImageSize Resolution)
        {
            string s;

            if (req.Query.TryGetValue("Encoding", out Encoding))
            {
                if (Encoding != "image/jpeg" && Encoding != "image/png" && Encoding != "image/bmp")
                {
                    throw new HttpException(HttpStatusCode.ClientError_BadRequest);
                }
            }
            else
            {
                Encoding = defaultSettings.ImageEncoding;
            }

            if (req.Query.TryGetValue("Compression", out s))
            {
                if (!byte.TryParse(s, out Compression))
                {
                    throw new HttpException(HttpStatusCode.ClientError_BadRequest);
                }
            }
            else
            {
                Compression = defaultSettings.CompressionLevel;
            }

            if (req.Query.TryGetValue("Resolution", out s))
            {
                if (!Enum.TryParse <LinkSpriteJpegColorCamera.ImageSize> ("_" + s, out Resolution))
                {
                    throw new HttpException(HttpStatusCode.ClientError_BadRequest);
                }
            }
            else
            {
                Resolution = defaultSettings.Resolution;
            }
        }
        private static void HttpGetHtml(HttpServerResponse resp, HttpServerRequest req, bool Protected)
        {
            networkLed.High();
            try
            {
                LinkSpriteJpegColorCamera.ImageSize Resolution;
                string Encoding;
                byte   Compression;

                if (Protected)
                {
                    string SessionId = req.Header.GetCookie("SessionId");
                    if (!CheckSession(SessionId))
                    {
                        throw new HttpTemporaryRedirectException("/");
                    }
                }

                GetImageProperties(req, out Encoding, out Compression, out Resolution);

                resp.ContentType = "text/html";
                resp.Encoding    = System.Text.Encoding.UTF8;
                resp.Expires     = DateTime.Now;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                resp.Write("<html><head/><body><h1>Camera, ");
                resp.Write(DateTime.Now.ToString());
                resp.Write("</h1><img src='camera?Encoding=");
                resp.Write(Encoding);
                resp.Write("&Compression=");
                resp.Write(Compression.ToString());
                resp.Write("&Resolution=");
                resp.Write(Resolution.ToString().Substring(1));
                resp.Write("' width='640' height='480'/>");
                resp.Write("</body><html>");
            } finally
            {
                networkLed.Low();
            }
        }
Beispiel #30
0
        private async static Task <byte[]> UsernamePasswordEchoHandler(HttpServerRequest request)
        {
            var response = await Handlers.LoadResponse(request.Path);

            var authHeader = request.Headers["Authorization"];

            byte[] base64 = Convert.FromBase64String(authHeader.Substring("Basic ".Length));
            var    parts  = Encoding.UTF8.GetString(base64, 0, base64.Length).Split(':');

            byte[] bodyArray = Encoding.UTF8.GetBytes(string.Join("|", parts));

            string intro = String.Format("HTTP/1.1 {0} OK\r\n", response.StatusCode);

            string headers = Handlers.BuildHeaders(response.Headers);

            headers = headers + string.Format("Content-Length: {0}\r\n\r\n", bodyArray.Length);

            byte[] headerArray = Encoding.UTF8.GetBytes(intro + headers);

            byte[] result = headerArray.Concat(bodyArray).ToArray();
            return(result);
        }
Beispiel #31
0
        private static void HttpGetRoot(HttpServerResponse resp, HttpServerRequest req)
        {
            networkLed.High();
            try
            {
                resp.ContentType = "text/html";
                resp.Encoding    = System.Text.Encoding.UTF8;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                resp.Write("<html><head><title>Sensor</title></head><body><h1>Welcome to Sensor</h1><p>Below, choose what you want to do.</p><ul>");
                resp.Write("<li>View Data</li><ul>");
                resp.Write("<li><a href='/xml?Momentary=1'>View data as XML using REST</a></li>");
                resp.Write("<li><a href='/json?Momentary=1'>View data as JSON using REST</a></li>");
                resp.Write("<li><a href='/turtle?Momentary=1'>View data as TURTLE using REST</a></li>");
                resp.Write("<li><a href='/rdf?Momentary=1'>View data as RDF using REST</a></li>");
                resp.Write("<li><a href='/html'>Data in a HTML page with graphs</a></li></ul>");
                resp.Write("</body></html>");
            } finally
            {
                networkLed.Low();
            }
        }
        private async Task HandleRequest(CancellationToken ct, HttpServerRequest request)
        {
            foreach (var handler in _handlers)
            {
                try
                {
                    await handler.HandleRequest(ct, request, request.Path);
                }
                catch (Exception ex)
                {
                    this.Log().LogError(EVENT_HANDLER_ERROR, ex, "Error in event Handler.");
                }

                if (request.IsResponseSet)
                {
                    break;
                }
            }

            if (!request.IsResponseSet)
            {
                request.SetResponse("text/plain", ct2 => GetErrorContent(request, ct2), 404, "NOT FOUND");
            }
        }
Beispiel #33
0
		private static void HttpPostSet (HttpServerResponse resp, HttpServerRequest req)
		{
			FormParameters Parameters = req.Data as FormParameters;
			if (Parameters == null)
				throw new HttpException (HttpStatusCode.ClientError_BadRequest);

			int i;
			bool b;

			for (i = 0; i < 8; i++)
			{
				if (XmlUtilities.TryParseBoolean (Parameters ["do" + (i + 1).ToString ()], out b) && b)
				{
					digitalOutputs [i].High ();
					state.SetDO (i + 1, true);
				} else
				{
					digitalOutputs [i].Low ();	// Unchecked checkboxes are not reported back to the server.
					state.SetDO (i + 1, false);
				}
			}

			if (XmlUtilities.TryParseBoolean (Parameters ["alarm"], out b) && b)
			{
				AlarmOn ();
				state.Alarm = true;
			} else
			{
				AlarmOff ();
				state.Alarm = false;
			}

			state.UpdateIfModified ();

			resp.ReturnCode = HttpStatusCode.Redirection_SeeOther;
			resp.AddHeader ("Location", "/set");
			resp.SendResponse ();
			// PRG pattern, to avoid problems with post back warnings in the browser: http://en.wikipedia.org/wiki/Post/Redirect/Get
		}
Beispiel #34
0
		private static void HttpGetSet (HttpServerResponse resp, HttpServerRequest req)
		{
			string s;
			int i;
			bool b;

			foreach (KeyValuePair<string,string> Query in req.Query)
			{
				if (!XmlUtilities.TryParseBoolean (Query.Value, out b))
					continue;

				s = Query.Key.ToLower ();
				if (s == "alarm")
				{
					if (b)
					{
						AlarmOn ();
						state.Alarm = true;
					} else
					{
						AlarmOff ();
						state.Alarm = false;
					}
				} else if (s.StartsWith ("do") && int.TryParse (s.Substring (2), out i) && i >= 1 && i <= 8)
				{
					digitalOutputs [i - 1].Value = b;
					state.SetDO (i, b);
				}
			}

			state.UpdateIfModified ();

			resp.ContentType = "text/html";
			resp.Encoding = System.Text.Encoding.UTF8;
			resp.ReturnCode = HttpStatusCode.Successful_OK;

			resp.Write ("<html><head><title>Actuator</title></head><body><h1>Control Actuator Outputs</h1>");
			resp.Write ("<form method='POST' action='/set' target='_self'><p>");

			for (i = 0; i < 8; i++)
			{
				resp.Write ("<input type='checkbox' name='do");
				resp.Write ((i + 1).ToString ());
				resp.Write ("'");
				if (digitalOutputs [i].Value)
					resp.Write (" checked='checked'");
				resp.Write ("/> Digital Output ");
				resp.Write ((i + 1).ToString ());
				resp.Write ("<br/>");
			}

			resp.Write ("<input type='checkbox' name='alarm'");
			if (alarmThread != null)
				resp.Write (" checked='checked'");
			resp.Write ("/> Alarm</p>");
			resp.Write ("<p><input type='submit' value='Set'/></p></form></body></html>");
		}
Beispiel #35
0
		private static void HttpPostCredentials (HttpServerResponse resp, HttpServerRequest req)
		{
			string SessionId = req.Header.GetCookie ("SessionId");
			if (!CheckSession (SessionId))
				throw new HttpTemporaryRedirectException ("/");

			FormParameters Parameters = req.Data as FormParameters;
			if (Parameters == null)
				throw new HttpException (HttpStatusCode.ClientError_BadRequest);

			resp.ContentType = "text/html";
			resp.Encoding = System.Text.Encoding.UTF8;
			resp.ReturnCode = HttpStatusCode.Successful_OK;

			string UserName = Parameters ["UserName"];
			string Password = Parameters ["Password"];
			string NewUserName = Parameters ["NewUserName"];
			string NewPassword1 = Parameters ["NewPassword1"];
			string NewPassword2 = Parameters ["NewPassword2"];

			string Hash;
			object AuthorizationObject;

			GetDigestUserPasswordHash (UserName, out Hash, out  AuthorizationObject);

			if (AuthorizationObject == null || Hash != CalcHash (UserName, Password))
			{
				Log.Warning ("Invalid attempt to change login credentials.", EventLevel.Minor, UserName, req.ClientAddress);
				OutputCredentialsForm (resp, "<p>Login credentials provided were not correct. Please try again.</p>");
			} else if (NewPassword1 != NewPassword2)
			{
				OutputCredentialsForm (resp, "<p>The new password was not entered correctly. Please provide the same new password twice.</p>");
			} else if (string.IsNullOrEmpty (UserName) || string.IsNullOrEmpty (NewPassword1))
			{
				OutputCredentialsForm (resp, "<p>Please provide a non-empty user name and password.</p>");
			} else if (UserName.Length > DB.ShortStringClipLength)
			{
				OutputCredentialsForm (resp, "<p>The new user name was too long.</p>");
			} else
			{
				Log.Information ("Login credentials changed.", EventLevel.Minor, UserName, req.ClientAddress);

				credentials.UserName = NewUserName;
				credentials.PasswordHash = CalcHash (NewUserName, NewPassword1);
				credentials.UpdateIfModified ();

				resp.ReturnCode = HttpStatusCode.Redirection_SeeOther;
				resp.AddHeader ("Location", "/");
				resp.SendResponse ();
				// PRG pattern, to avoid problems with post back warnings in the browser: http://en.wikipedia.org/wiki/Post/Redirect/Get
			}
		}
Beispiel #36
0
		private static void HttpGetEvent (HttpServerResponse resp, HttpServerRequest req, string ContentType, ISensorDataExport ExportModule)
		{
			networkLed.High ();
			try
			{
				double? Temperature = null;
				double? TemperatureDiff = null;
				double? Light = null;
				double? LightDiff = null;
				bool? Motion = null;
				double d, d2;
				string s;
				bool b;
				int Timeout;

				if (!req.Query.TryGetValue ("Timeout", out s) || !int.TryParse (s, out Timeout) || Timeout <= 0)
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				if (req.Query.TryGetValue ("Temperature", out s) && XmlUtilities.TryParseDouble (s, out d) &&
				    req.Query.TryGetValue ("TemperatureDiff", out s) && XmlUtilities.TryParseDouble (s, out d2) && d2 > 0)
				{
					Temperature = d;
					TemperatureDiff = d2;
				}

				if (req.Query.TryGetValue ("Light", out s) && XmlUtilities.TryParseDouble (s, out d) &&
				    req.Query.TryGetValue ("LightDiff", out s) && XmlUtilities.TryParseDouble (s, out d2) && d2 > 0)
				{
					Light = d;
					LightDiff = d2;
				}

				if (req.Query.TryGetValue ("Motion", out s) && XmlUtilities.TryParseBoolean (s, out b))
					Motion = b;

				if (!(Temperature.HasValue || Light.HasValue || Motion.HasValue))
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				lock (synchObject)
				{
					pendingEvents.Add (new PendingEvent (Temperature, TemperatureDiff, Light, LightDiff, Motion, Timeout, resp, ContentType, ExportModule));
				}

			} finally
			{
				networkLed.Low ();
			}
		}
		/// <summary>
		/// Represents a request for sensor data.
		/// </summary>
		/// <param name="Request">HTTP Request</param>
		public ReadoutRequest (HttpServerRequest Request)
		{
			string NodeId = string.Empty;
			string CacheType = string.Empty;
			string SourceId = string.Empty;
			bool b;

			foreach (KeyValuePair<string,string> Parameter in Request.Query)
			{
				switch (Parameter.Key.ToLower ())
				{
					case "nodeid":
						NodeId = Parameter.Value;
						break;

					case "cachetype":
						CacheType = Parameter.Value;
						break;

					case "sourceid":
						SourceId = Parameter.Value;
						break;

					case "all":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types = ReadoutType.All;
						else
							this.types = (ReadoutType)0;
						break;

					case "historical":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValues;
						else
							this.types &= ~ReadoutType.HistoricalValues;

						break;

					case "from":
						if (!XmlUtilities.TryParseDateTimeXml (Parameter.Value, out this.from))
							this.from = DateTime.MinValue;
						break;

					case "to":
						if (!XmlUtilities.TryParseDateTimeXml (Parameter.Value, out this.to))
							this.from = DateTime.MaxValue;
						break;

					case "when":
						throw new HttpException (HttpStatusCode.ClientError_BadRequest);	// Not supported through HTTP interface.
						
					case "servicetoken":
						this.serviceToken = Parameter.Value;
						break;

					case "devicetoken":
						this.deviceToken = Parameter.Value;
						break;

					case "usertoken":
						this.userToken = Parameter.Value;
						break;

					case "momentary":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.MomentaryValues;
						else
							this.types &= ~ReadoutType.MomentaryValues;
						break;

					case "peak":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.PeakValues;
						else
							this.types &= ~ReadoutType.PeakValues;
						break;

					case "status":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.StatusValues;
						else
							this.types &= ~ReadoutType.StatusValues;
						break;

					case "computed":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.Computed;
						else
							this.types &= ~ReadoutType.Computed;
						break;

					case "identity":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.Identity;
						else
							this.types &= ~ReadoutType.Identity;
						break;

					case "historicalsecond":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesSecond;
						else
							this.types &= ~ReadoutType.HistoricalValuesSecond;
						break;

					case "historicalminute":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesMinute;
						else
							this.types &= ~ReadoutType.HistoricalValuesMinute;
						break;

					case "historicalhour":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesHour;
						else
							this.types &= ~ReadoutType.HistoricalValuesHour;
						break;

					case "historicalday":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesDay;
						else
							this.types &= ~ReadoutType.HistoricalValuesDay;
						break;

					case "historicalweek":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesWeek;
						else
							this.types &= ~ReadoutType.HistoricalValuesWeek;
						break;

					case "historicalmonth":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesMonth;
						else
							this.types &= ~ReadoutType.HistoricalValuesMonth;
						break;

					case "historicalquarter":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesQuarter;
						else
							this.types &= ~ReadoutType.HistoricalValuesQuarter;
						break;

					case "historicalyear":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesYear;
						else
							this.types &= ~ReadoutType.HistoricalValuesYear;
						break;

					case "historicalother":
						if (XmlUtilities.TryParseBoolean (Parameter.Value, out b) && b)
							this.types |= ReadoutType.HistoricalValuesOther;
						else
							this.types &= ~ReadoutType.HistoricalValuesOther;
						break;

					default:
						if (this.fields == null)
							this.fields = new SortedDictionary<string, bool> ();

						this.fields [Parameter.Key] = true;
						break;
				}
			}

			if ((int)this.types == 0)
				this.types = ReadoutType.All;	// If no types specified, all types are implicitly implied.

			if (!string.IsNullOrEmpty (NodeId))
				this.nodes = new NodeReference[]{ new NodeReference (NodeId, CacheType, SourceId) };
		}
Beispiel #38
0
		private static void HttpGetSensorData (HttpServerResponse resp, HttpServerRequest req, string ContentType, ISensorDataExport ExportModule)
		{
			ReadoutRequest Request = new ReadoutRequest (req);
			HttpGetSensorData (resp, ContentType, ExportModule, Request);
		}
Beispiel #39
0
		private static void HttpGetTurtle (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetSensorData (resp, req, "text/turtle", new SensorDataTurtleExport (resp.TextWriter, req));
		}
		/// <summary>
		/// Class handling export of sensor data to TURTLE.
		/// </summary>
		/// <param name="Output">TURTLE will be output here.</param>
		/// <param name="Request">HTTP Request resulting in the generation of the TURTLE document.</param>
		public SensorDataTurtleExport (StringBuilder Output, HttpServerRequest Request)
		{
			this.turtle = new TurtleWriter (Output);
			this.request = Request;
		}
Beispiel #41
0
		/// <summary>
		/// Starts exporting Sensor Data TURTLE. This call must be followed by a call to <see cref="EndExportTurtle"/>.
		/// Use <see cref="StartExportNode"/> to export node information to the Sensor Data TURTLE document.
		/// </summary>
		/// <returns>TURTLE Writer, used for the export.</returns>
		/// <param name="Output">TURTLE will be output here.</param>
		/// <param name="Request">HTTP Request resulting in the generation of the TURTLE document.</param>
		public static TurtleWriter StartExportTurtle (StringBuilder Output, HttpServerRequest Request)
		{
			string HostUrl = GetHostUrl (Request);
			TurtleWriter Turtle = new TurtleWriter (Output);
			Turtle.WritePrefix ("l", HostUrl);
			Turtle.WritePrefix ("cl", "http://clayster.com/sw/");
			//Turtle.WritePrefix ("clu", "http://clayster.com/sw/u/");
			return Turtle;
		}
		/// <summary>
		/// Initializes the export module.
		/// </summary>
		/// <param name="Output">TURTLE will be output here.</param>
		/// <param name="Request">HTTP Request resulting in the generation of the TURTLE document.</param>
		protected void Init(StringBuilder Output, HttpServerRequest Request)
		{
			this.turtle = new TurtleWriter (Output);
			this.request = Request;
		}
Beispiel #43
0
		/// <summary>
		/// Starts exporting Sensor Data TURTLE. This call must be followed by a call to <see cref="EndExportTurtle"/>.
		/// Use <see cref="StartExportNode"/> to export node information to the Sensor Data TURTLE document.
		/// </summary>
		/// <param name="Output">TURTLE will be output here.</param>
		/// <param name="Request">HTTP Request resulting in the generation of the TURTLE document.</param>
		public static void StartExportTurtle (TurtleWriter Output, HttpServerRequest Request)
		{
			string HostUrl = GetHostUrl (Request);
			Output.WritePrefix ("l", HostUrl);
			Output.WritePrefix ("cl", "http://clayster.com/sw/");
			//Output.WritePrefix ("clu", "http://clayster.com/sw/u/");
		}
Beispiel #44
0
		private static void HttpGetHtml (HttpServerResponse resp, HttpServerRequest req)
		{
			networkLed.High ();
			try
			{
				string SessionId = req.Header.GetCookie ("SessionId");
				if (!CheckSession (SessionId))
					throw new HttpTemporaryRedirectException ("/");

				resp.ContentType = "text/html";
				resp.Encoding = System.Text.Encoding.UTF8;
				resp.Expires = DateTime.Now;
				resp.ReturnCode = HttpStatusCode.Successful_OK;

				resp.Write ("<html><head><meta http-equiv='refresh' content='60'/><title>Sensor Readout</title></head><body><h1>Readout, ");
				resp.Write (DateTime.Now.ToString ());
				resp.Write ("</h1><table><tr><td>Temperature:</td><td style='width:20px'/><td>");

				lock (synchObject)
				{
					resp.Write (HtmlUtilities.Escape (temperatureC.ToString ("F1")));
					resp.Write (" C</td></tr><tr><td>Light:</td><td/><td>");
					resp.Write (HtmlUtilities.Escape (lightPercent.ToString ("F1")));
					resp.Write (" %</td></tr><tr><td>Motion:</td><td/><td>");
					resp.Write (motionDetected.ToString ());
					resp.Write ("</td></tr></table>");

					if (perSecond.Count > 1)
					{
						resp.Write ("<h2>Second Precision</h2><table><tr><td><img src='historygraph?p=temp&base=sec&w=350&h=250' width='480' height='320'/></td>");
						resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=sec&w=350&h=250' width='480' height='320'/></td>");
						resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=sec&w=350&h=250' width='480' height='320'/></td></tr></table>");

						if (perMinute.Count > 1)
						{
							resp.Write ("<h2>Minute Precision</h2><table><tr><td><img src='historygraph?p=temp&base=min&w=350&h=250' width='480' height='320'/></td>");
							resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=min&w=350&h=250' width='480' height='320'/></td>");
							resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=min&w=350&h=250' width='480' height='320'/></td></tr></table>");

							if (perHour.Count > 1)
							{
								resp.Write ("<h2>Hour Precision</h2><table><tr><td><img src='historygraph?p=temp&base=h&w=350&h=250' width='480' height='320'/></td>");
								resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=h&w=350&h=250' width='480' height='320'/></td>");
								resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=h&w=350&h=250' width='480' height='320'/></td></tr></table>");

								if (perDay.Count > 1)
								{
									resp.Write ("<h2>Day Precision</h2><table><tr><td><img src='historygraph?p=temp&base=day&w=350&h=250' width='480' height='320'/></td>");
									resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=day&w=350&h=250' width='480' height='320'/></td>");
									resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=day&w=350&h=250' width='480' height='320'/></td></tr></table>");

									if (perMonth.Count > 1)
									{
										resp.Write ("<h2>Month Precision</h2><table><tr><td><img src='historygraph?p=temp&base=month&w=350&h=250' width='480' height='320'/></td>");
										resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=month&w=350&h=250' width='480' height='320'/></td>");
										resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=month&w=350&h=250' width='480' height='320'/></td></tr></table>");
									}
								}
							}
						}
					}
				}

				resp.Write ("</body><html>");

			} finally
			{
				networkLed.Low ();
			}
		}
Beispiel #45
0
		private static void HttpGetRoot (HttpServerResponse resp, HttpServerRequest req)
		{
			networkLed.High ();
			try
			{
				string SessionId = req.Header.GetCookie ("SessionId");

				resp.ContentType = "text/html";
				resp.Encoding = System.Text.Encoding.UTF8;
				resp.ReturnCode = HttpStatusCode.Successful_OK;

				if (CheckSession (SessionId))
				{
					StringBuilder sb = new StringBuilder ();
					string EventParameters;

					lock (synchObject)
					{
						sb.Append ("?Temperature=");
						sb.Append (XmlUtilities.DoubleToString (temperatureC, 1));
						sb.Append ("&amp;TemperatureDiff=1&amp;Light=");
						sb.Append (XmlUtilities.DoubleToString (lightPercent, 1));
						sb.Append ("&amp;LightDiff=10&amp;Motion=");
						sb.Append (motionDetected ? "1" : "0");
						sb.Append ("&amp;Timeout=25");
					}

					EventParameters = sb.ToString ();

					resp.Write ("<html><head><title>Sensor</title></head><body><h1>Welcome to Sensor</h1><p>Below, choose what you want to do.</p><ul>");
					resp.Write ("<li><a href='/credentials'>Update login credentials.</a></li>");
					resp.Write ("<li>View Data</li><ul>");
					resp.Write ("<li><a href='/xml?Momentary=1'>View data as XML using REST</a></li>");
					resp.Write ("<li><a href='/json?Momentary=1'>View data as JSON using REST</a></li>");
					resp.Write ("<li><a href='/turtle?Momentary=1'>View data as TURTLE using REST</a></li>");
					resp.Write ("<li><a href='/rdf?Momentary=1'>View data as RDF using REST</a></li>");
					resp.Write ("<li><a href='/html'>Data in a HTML page with graphs</a></li></ul>");
					resp.Write ("<li>Wait for an Event</li><ul>");
					resp.Write ("<li><a href='/event/xml");
					resp.Write (EventParameters);
					resp.Write ("'>Return XML data when event occurs.</a></li>");
					resp.Write ("<li><a href='/event/json");
					resp.Write (EventParameters);
					resp.Write ("'>Return JSON data when event occurs.</a></li>");
					resp.Write ("<li><a href='/event/turtle");
					resp.Write (EventParameters);
					resp.Write ("'>Return TURTLE data when event occurs.</a></li>");
					resp.Write ("<li><a href='/event/rdf");
					resp.Write (EventParameters);
					resp.Write ("'>Return RDF data when event occurs.</a></li>");
					resp.Write ("</ul></body></html>");

				} else
					OutputLoginForm (resp, string.Empty);
			} finally
			{
				networkLed.Low ();
			}
		}
Beispiel #46
0
		private static void HttpGetXml (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetSensorData (resp, req, "text/xml", new SensorDataXmlExport (resp.TextWriter));
		}
Beispiel #47
0
		private static void HttpGetJson (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetSensorData (resp, req, "application/json", new SensorDataJsonExport (resp.TextWriter));
		}
Beispiel #48
0
        /// <summary>
        /// A regex would be nice :)
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="resultThisFar"></param>
        public override void HandleRequestPart(byte[] stream, HttpServerRequest resultThisFar)
        {
            UnparsedData = stream;

            string headerName = null;
            var bytesLeft = stream.Length;
            int headerValueStartIndex = 0;
            int headerValueEndIndex = 0;
            for (var i = 0; i < stream.Length; i++, bytesLeft--)
            {
                byte currentByte = stream[i];
                if (headerName == null && currentByte == Constants.ColonByte)
                {
                    headerName = GetHeaderString(stream, headerValueEndIndex, i);
                    headerValueStartIndex = i + 1;
                }
                else if (stream[i] == Constants.CRByte)
                {
                    // Special case when /r/n is received or /r/ncontentdata
                    if (i == 0 && bytesLeft >= 2 && stream[1] == Constants.LFByte)
                    {
                        IsFinished = true;
                        IsSucceeded = true;
                        headerValueEndIndex = 2;
                        break;
                    }

                    if (headerName != null &&
                        bytesLeft >= 2 &&
                        stream[i + 1] == Constants.LFByte)
                    {
                        // Handle end of one header scenario
                        var headerValue = GetHeaderString(stream, headerValueStartIndex, i);
                        headerValue = headerValue.TrimWhitespaces();
                        try
                        {
                            resultThisFar.AddHeader(_headerFactory.Create(headerName, headerValue));
                        }
                        catch (Exception)
                        {
                            IsFinished = true;
                            IsSucceeded = false;
                            break;
                        }
                        finally
                        {
                            headerName = null;
                            headerValueStartIndex = 0;
                            headerValueEndIndex = i + 2;
                        }
                    }

                    if (bytesLeft >= 4 &&
                        stream[i + 1] == Constants.LFByte &&
                        stream[i + 2] == Constants.CRByte &&
                        stream[i + 3] == Constants.LFByte)
                    {
                        // Handle end of headers scenario
                        headerValueEndIndex = i + 4;
                        IsFinished = true;
                        IsSucceeded = true;
                        break;
                    }
                }
            }

            UnparsedData = stream.Skip(headerValueEndIndex).ToArray();
        }
Beispiel #49
0
		private static void HttpGetRdf (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetSensorData (resp, req, "application/rdf+xml", new SensorDataRdfExport (resp.TextWriter, req));
		}
Beispiel #50
0
		private static void HttpGetRoot (HttpServerResponse resp, HttpServerRequest req)
		{
			string SessionId = req.Header.GetCookie ("SessionId");

			resp.ContentType = "text/html";
			resp.Encoding = System.Text.Encoding.UTF8;
			resp.ReturnCode = HttpStatusCode.Successful_OK;

			if (CheckSession (SessionId))
			{
				resp.Write ("<html><head><title>Actuator</title></head><body><h1>Welcome to Actuator</h1><p>Below, choose what you want to do.</p><ul>");
				resp.Write ("<li><a href='/credentials'>Update login credentials.</a></li>");
				resp.Write ("<li><a href='/set'>Control Outputs</a></li>");
				resp.Write ("<li>View Output States</li><ul>");
				resp.Write ("<li><a href='/xml?Momentary=1'>View data as XML using REST</a></li>");
				resp.Write ("<li><a href='/json?Momentary=1'>View data as JSON using REST</a></li>");
				resp.Write ("<li><a href='/turtle?Momentary=1'>View data as TURTLE using REST</a></li>");
				resp.Write ("<li><a href='/rdf?Momentary=1'>View data as RDF using REST</a></li></ul>");
				resp.Write ("</ul></body></html>");

			} else
				OutputLoginForm (resp, string.Empty);
		}
Beispiel #51
0
		private static string GetHostUrl (HttpServerRequest Request)
		{
			ParsedUri Uri = Web.ParseUri (Request.Url);
			StringBuilder sb = new StringBuilder ();

			sb.Append (Uri.Scheme);
			sb.Append ("://");
			sb.Append (Uri.Host);
			if (Uri.Port != Uri.UriScheme.DefaultPort && Uri.Port != 0)
			{
				sb.Append (":");
				sb.Append (Uri.Port.ToString ());
			}
			sb.Append ("/");

			return sb.ToString ();
		}
Beispiel #52
0
		private static void HttpPostRoot (HttpServerResponse resp, HttpServerRequest req)
		{
			FormParameters Parameters = req.Data as FormParameters;
			if (Parameters == null)
				throw new HttpException (HttpStatusCode.ClientError_BadRequest);

			string UserName = Parameters ["UserName"];
			string Password = Parameters ["Password"];
			string Hash;
			object AuthorizationObject;

			GetDigestUserPasswordHash (UserName, out Hash, out  AuthorizationObject);

			if (AuthorizationObject == null || Hash != CalcHash (UserName, Password))
			{
				resp.ContentType = "text/html";
				resp.Encoding = System.Text.Encoding.UTF8;
				resp.ReturnCode = HttpStatusCode.Successful_OK;

				Log.Warning ("Invalid login attempt.", EventLevel.Minor, UserName, req.ClientAddress);
				OutputLoginForm (resp, "<p>The login was incorrect. Either the user name or the password was incorrect. Please try again.</p>");
			} else
			{
				Log.Information ("User logged in.", EventLevel.Minor, UserName, req.ClientAddress);

				string SessionId = CreateSessionId (UserName);
				resp.SetCookie ("SessionId", SessionId, "/");
				resp.ReturnCode = HttpStatusCode.Redirection_SeeOther;
				resp.AddHeader ("Location", "/");
				resp.SendResponse ();
				// PRG pattern, to avoid problems with post back warnings in the browser: http://en.wikipedia.org/wiki/Post/Redirect/Get
			}
		}
Beispiel #53
0
		private static void HttpGetHistoryGraph (HttpServerResponse resp, HttpServerRequest req)
		{
			networkLed.High ();
			try
			{
				string SessionId = req.Header.GetCookie ("SessionId");
				if (!CheckSession (SessionId))
					throw new HttpException (HttpStatusCode.ClientError_Forbidden);

				string ValueAxis;
				string ParameterName;
				string s;
				int Width, Height;

				if (!req.Query.TryGetValue ("w", out s) || !int.TryParse (s, out Width) || Width <= 0 || Width > 2048)
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				if (!req.Query.TryGetValue ("h", out s) || !int.TryParse (s, out Height) || Height <= 0 || Height > 2048)
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				if (!req.Query.TryGetValue ("p", out s))
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				switch (s)
				{
					case "temp":
						ParameterName = "TemperatureC";
						ValueAxis = "Temperature (C)";
						break;

					case "light":
						ParameterName = "LightPercent";
						ValueAxis = "Light (%)";
						break;

					case "motion":
						ParameterName = "Motion";
						ValueAxis = "Motion";
						break;

					default:
						throw new HttpException (HttpStatusCode.ClientError_BadRequest);
				}

				if (!req.Query.TryGetValue ("base", out s))
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				Variables v = new Variables ();
				DateTime Now = DateTime.Now;

				lock (synchObject)
				{
					switch (s)
					{
						case "sec":
							v ["Records"] = perSecond.ToArray ();
							resp.Expires = Now;
							break;

						case "min":
							v ["Records"] = perMinute.ToArray ();
							resp.Expires = new DateTime (Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute, 0).AddMinutes (1);
							break;

						case "h":
							v ["Records"] = perHour.ToArray ();
							resp.Expires = new DateTime (Now.Year, Now.Month, Now.Day, Now.Hour, 0, 0).AddHours (1);
							break;

						case "day":
							v ["Records"] = perDay.ToArray ();
							resp.Expires = new DateTime (Now.Year, Now.Month, Now.Day, 0, 0, 0).AddDays (1);
							break;

						case "month":
							v ["Records"] = perMonth.ToArray ();
							resp.Expires = new DateTime (Now.Year, Now.Month, 1, 0, 0, 0).AddMonths (1);
							break;

						default:
							throw new HttpException (HttpStatusCode.ClientError_BadRequest);
					}
				}
				Graph Result;

				if (ParameterName == "Motion")
					Result = Expression.ParseCached ("scatter2d(Records.Timestamp,if (Values:=Records.Motion) then 1 else 0,5,if Values then 'Red' else 'Blue','','Motion')").Evaluate (v) as Graph;
				else
					Result = Expression.ParseCached ("line2d(Records.Timestamp,Records." + ParameterName + ",'','" + ValueAxis + "')").Evaluate (v)as Graph;

				Image Img = Result.GetImage (Width, Height);
				byte[] Data = MimeUtilities.Encode (Img, out s);

				resp.ContentType = s;
				resp.ReturnCode = HttpStatusCode.Successful_OK;

				resp.WriteBinary (Data);

			} finally
			{
				networkLed.Low ();
			}
		}
Beispiel #54
0
		private static void HttpGetCredentials (HttpServerResponse resp, HttpServerRequest req)
		{
			string SessionId = req.Header.GetCookie ("SessionId");
			if (!CheckSession (SessionId))
				throw new HttpTemporaryRedirectException ("/");

			resp.ContentType = "text/html";
			resp.Encoding = System.Text.Encoding.UTF8;
			resp.ReturnCode = HttpStatusCode.Successful_OK;

			OutputCredentialsForm (resp, string.Empty);
		}