Esempio n. 1
0
        public Boolean ParseMandatory(IEnumerable <String> PropertyNames,
                                      String PropertyDescription,
                                      String DefaultServerName,
                                      out DateTime Timestamp,
                                      HTTPRequest HTTPRequest,
                                      out HTTPResponse HTTPResponse)

        {
            Object JSONToken = null;

            Timestamp = DateTime.MinValue;

            // Attention: JSONToken is a side-effect!
            var FirstMatchingPropertyName = PropertyNames.
                                            Where(propertyname => TryGetValue(propertyname, out JSONToken)).
                                            FirstOrDefault();

            if (FirstMatchingPropertyName != null)
            {
                if (JSONToken != null)
                {
                    try
                    {
                        Timestamp = (DateTime)JSONToken;
                    }
                    catch (Exception)
                    {
                        HTTPResponse = new HTTPResponseBuilder(HTTPRequest)
                        {
                            HTTPStatusCode = HTTPStatusCode.BadRequest,
                            Server         = DefaultServerName,
                            Date           = DateTime.Now,
                            ContentType    = HTTPContentType.JSON_UTF8,
                            Content        = JSONObject.Create(
                                new JProperty("description", "Invalid timestamp '" + JSONToken.ToString() + "'!")
                                ).ToUTF8Bytes()
                        };

                        return(false);
                    }
                }

                HTTPResponse = null;
                return(true);
            }

            else
            {
                HTTPResponse = new HTTPResponseBuilder(HTTPRequest)
                {
                    HTTPStatusCode = HTTPStatusCode.BadRequest,
                    Server         = DefaultServerName,
                    Date           = DateTime.Now,
                    ContentType    = HTTPContentType.JSON_UTF8,
                    Content        = JSONObject.Create(
                        new JProperty("description", "Missing at least one of the following properties: " + PropertyNames.AggregateWith(", ") + "!")
                        ).ToUTF8Bytes()
                };

                return(false);
            }
        }
Esempio n. 2
0
        public Boolean ParseHTTP(String ParameterName, HTTPRequest HTTPRequest, out String Value, out HTTPResponse HTTPResp, String Context = null, String DefaultValue = null)
        {
            Object JSONToken;

            if (!TryGetValue(ParameterName, out JSONToken))
            {
                Value    = DefaultValue;
                HTTPResp = HTTPExtentions.CreateBadRequest(HTTPRequest, Context, ParameterName);

                return(false);
            }

            if (JSONToken != null)
            {
                Value = JSONToken.ToString();

                if (Value.IsNullOrEmpty())
                {
                    Value    = DefaultValue;
                    HTTPResp = HTTPExtentions.CreateBadRequest(HTTPRequest, Context, ParameterName, JSONToken.ToString());

                    return(false);
                }
            }

            else
            {
                Value    = DefaultValue;
                HTTPResp = null;
                return(false);
            }

            HTTPResp = null;
            return(true);
        }
Esempio n. 3
0
        public Boolean ParseHTTP(String ParameterName, HTTPRequest HTTPRequest, out Double Value, out HTTPResponse HTTPResp, String Context = null, Double DefaultValue = 0)
        {
            Object JSONToken;

            if (!TryGetValue(ParameterName, out JSONToken))
            {
                Value    = DefaultValue;
                HTTPResp = HTTPExtentions.CreateBadRequest(HTTPRequest, Context, ParameterName);

                return(false);
            }

            if (JSONToken != null)
            {
                if (!Double.TryParse(JSONToken.ToString(), NumberStyles.Any, CultureInfo.CreateSpecificCulture("en-US"), out Value))
                {
                    Log.Timestamp("Bad request: Invalid \"" + ParameterName + "\" property value!");

                    Value    = DefaultValue;
                    HTTPResp = HTTPExtentions.CreateBadRequest(HTTPRequest, Context, ParameterName, JSONToken.ToString());

                    return(false);
                }
            }

            else
            {
                Value    = 0;
                HTTPResp = null;
                return(false);
            }

            HTTPResp = null;
            return(true);
        }
Esempio n. 4
0
        public Boolean ParseHTTP(String ParameterName, HTTPRequest HTTPRequest, out DateTime Value, out HTTPResponse HTTPResp, String Context = null, DateTime DefaultValue = default(DateTime))
        {
            Object JSONToken;

            if (!TryGetValue(ParameterName, out JSONToken))
            {
                Value    = DefaultValue;
                HTTPResp = HTTPExtentions.CreateBadRequest(HTTPRequest, Context, ParameterName);

                return(false);
            }

            if (JSONToken != null)
            {
                try
                {
                    Value = (DateTime)JSONToken;
                }
                catch (Exception)
                {
                    Log.Timestamp("Bad request: Invalid \"" + ParameterName + "\" property value!");

                    Value    = DefaultValue;
                    HTTPResp = HTTPExtentions.CreateBadRequest(HTTPRequest, Context, ParameterName, JSONToken.ToString());

                    return(false);
                }
            }

            else
            {
                Value    = DateTime.Now;
                HTTPResp = null;
                return(false);
            }

            HTTPResp = null;
            return(true);
        }
Esempio n. 5
0
        public void ProcessArrow(TCPConnection TCPConnection)
        {
            //lock (myLock)
            //{

            #region Start

            //TCPConnection.WriteLineToResponseStream(ServiceBanner);
            TCPConnection.NoDelay = true;

            Byte Byte;
            var  MemoryStream    = new MemoryStream();
            var  EndOfHTTPHeader = EOLSearch.NotYet;
            var  ClientClose     = false;
            var  ServerClose     = false;

            #endregion

            try
            {
                do
                {
                    switch (TCPConnection.TryRead(out Byte, MaxInitialWaitingTimeMS: ReadTimeout))
                    {
                        #region DataAvailable

                    case TCPClientResponse.DataAvailable:

                        #region Check for end of HTTP header...

                        if (EndOfHTTPHeader == EOLSearch.NotYet)
                        {
                            // \n
                            if (Byte == 0x0a)
                            {
                                EndOfHTTPHeader = EOLSearch.EoL_Found;
                            }

                            // \r
                            else if (Byte == 0x0d)
                            {
                                EndOfHTTPHeader = EOLSearch.R_Read;
                            }
                        }

                        // \n after a \r
                        else if (EndOfHTTPHeader == EOLSearch.R_Read)
                        {
                            if (Byte == 0x0a)
                            {
                                EndOfHTTPHeader = EOLSearch.EoL_Found;
                            }
                            else
                            {
                                EndOfHTTPHeader = EOLSearch.NotYet;
                            }
                        }

                        // \r after a \r\n
                        else if (EndOfHTTPHeader == EOLSearch.EoL_Found)
                        {
                            if (Byte == 0x0d)
                            {
                                EndOfHTTPHeader = EOLSearch.RN_Read;
                            }
                            else
                            {
                                EndOfHTTPHeader = EOLSearch.NotYet;
                            }
                        }

                        // \r\n\r after a \r\n\r
                        else if (EndOfHTTPHeader == EOLSearch.RN_Read)
                        {
                            if (Byte == 0x0a)
                            {
                                EndOfHTTPHeader = EOLSearch.Double_EoL_Found;
                            }
                            else
                            {
                                EndOfHTTPHeader = EOLSearch.NotYet;
                            }
                        }

                        #endregion

                        MemoryStream.WriteByte(Byte);

                        #region If end-of-line -> process data...

                        if (EndOfHTTPHeader == EOLSearch.Double_EoL_Found)
                        {
                            if (MemoryStream.Length > 0)
                            {
                                var RequestTimestamp = DateTime.Now;

                                #region Check UTF8 encoding

                                var HTTPHeaderString = String.Empty;

                                try
                                {
                                    HTTPHeaderString = Encoding.UTF8.GetString(MemoryStream.ToArray());
                                }
                                catch (Exception)
                                {
                                    NotifyErrors(null,
                                                 TCPConnection,
                                                 RequestTimestamp,
                                                 HTTPStatusCode.BadRequest,
                                                 Error: "Protocol Error: Invalid UTF8 encoding!");
                                }

                                #endregion

                                #region Try to parse the HTTP header

                                HTTPRequest HttpRequest = null;
                                var         CTS         = new CancellationTokenSource();

                                try
                                {
                                    HttpRequest = new HTTPRequest(_HTTPServer,
                                                                  CTS.Token,
                                                                  EventTracking_Id.New,
                                                                  TCPConnection.RemoteSocket,
                                                                  TCPConnection.LocalSocket,
                                                                  HTTPHeaderString.Trim(),
                                                                  TCPConnection.NetworkStream);
                                }
                                catch (Exception e)
                                {
                                    NotifyErrors(null,
                                                 TCPConnection,
                                                 RequestTimestamp,
                                                 HTTPStatusCode.BadRequest,
                                                 LastException:  e,
                                                 Error:          "Invalid HTTP header!");
                                }

                                #endregion

                                #region Call RequestLog delegate

                                var RequestLogLocal = RequestLog;
                                if (RequestLogLocal != null &&
                                    HttpRequest != null)
                                {
                                    RequestLogLocal(this, RequestTimestamp, HttpRequest);
                                }

                                #endregion

                                #region Call OnNotification delegate

                                HTTPResponse _HTTPResponse = null;

                                var OnNotificationLocal = OnNotification;
                                if (OnNotificationLocal != null &&
                                    HttpRequest != null)
                                {
                                    // ToDo: How to read request body by application code?!
                                    _HTTPResponse = OnNotification("TCPConnectionId",
                                                                   RequestTimestamp,
                                                                   HttpRequest).Result;

                                    TCPConnection.WriteToResponseStream((_HTTPResponse.RawHTTPHeader.Trim() +
                                                                         "\r\n\r\n").
                                                                        ToUTF8Bytes());

                                    if (_HTTPResponse.HTTPBody != null)
                                    {
                                        TCPConnection.WriteToResponseStream(_HTTPResponse.HTTPBody);
                                    }

                                    else if (_HTTPResponse.HTTPBodyStream != null)
                                    {
                                        TCPConnection.WriteToResponseStream(_HTTPResponse.HTTPBodyStream);
                                        _HTTPResponse.HTTPBodyStream.Dispose();
                                    }

                                    if (_HTTPResponse.Connection.ToLower().Contains("close"))
                                    {
                                        ServerClose = true;
                                    }
                                }

                                #endregion

                                #region Call AccessLog delegate

                                if (HttpRequest != null &&
                                    _HTTPResponse != null)
                                {
                                    AccessLog?.Invoke(this,
                                                      RequestTimestamp,
                                                      HttpRequest,
                                                      _HTTPResponse);
                                }

                                #endregion

                                #region if HTTP Status Code == 4xx | 5xx => Call ErrorLog delegate

                                if (HttpRequest != null &&
                                    _HTTPResponse != null &&
                                    _HTTPResponse.HTTPStatusCode.Code > 400 &&
                                    _HTTPResponse.HTTPStatusCode.Code <= 599)
                                {
                                    ErrorLog?.Invoke(this,
                                                     RequestTimestamp,
                                                     HttpRequest,
                                                     _HTTPResponse);
                                }

                                #endregion
                            }

                            MemoryStream.SetLength(0);
                            MemoryStream.Seek(0, SeekOrigin.Begin);
                            EndOfHTTPHeader = EOLSearch.NotYet;
                        }

                        #endregion

                        break;

                        #endregion

                        #region CanNotRead

                    case TCPClientResponse.CanNotRead:
                        ServerClose = true;
                        break;

                        #endregion

                        #region ClientClose

                    case TCPClientResponse.ClientClose:
                        ClientClose = true;
                        break;

                        #endregion

                        #region Timeout

                    case TCPClientResponse.Timeout:
                        ServerClose = true;
                        break;

                        #endregion
                    }
                } while (!ClientClose && !ServerClose);
            }

            #region Process exceptions

            catch (IOException ioe)
            {
                if (ioe.Message.StartsWith("Unable to read data from the transport connection"))
                {
                }
                else if (ioe.Message.StartsWith("Unable to write data to the transport connection"))
                {
                }

                else
                {
                    //if (OnError != null)
                    //    OnError(this, DateTime.Now, ConnectionIdBuilder(newTCPConnection.RemoteIPAddress, newTCPConnection.RemotePort), ioe, MemoryStream);
                }
            }

            catch (Exception e)
            {
                //if (OnError != null)
                //    OnError(this, DateTime.Now, ConnectionIdBuilder(newTCPConnection.RemoteIPAddress, newTCPConnection.RemotePort), e, MemoryStream);
            }

            #endregion

            #region Close the TCP connection

            try
            {
                TCPConnection.Close((ClientClose) ? ConnectionClosedBy.Client : ConnectionClosedBy.Server);
            }
            catch (Exception)
            { }

            #endregion

            //}
        }