Exemplo n.º 1
0
 protected override void DoSetHeaders()
 {
     base.DoSetHeaders();
     if (Server != "")
     {
         _RawHeaders.Values("Server", Server);
     }
     if (ContentType != "")
     {
         _RawHeaders.Values("Content-Type", ContentType);
     }
     if (Location != "")
     {
         _RawHeaders.Values("Location", Location);
     }
     if (ContentLength > -1)
     {
         _RawHeaders.Values("Content-Length", ContentLength.ToString());
     }
     if (LastModified.Ticks > 0)
     {
         _RawHeaders.Values("Last-Modified", Http.DateTimeGmtToHttpStr(LastModified));
     }
     if (AuthRealm != "")
     {
         ResponseNo = 401;
         _RawHeaders.Values("WWW-Authenticate", "Basic realm=\"" + AuthRealm + "\"");
         _ContentText = "<HTML><BODY><B>" + ResponseNo + " " + ResourceStrings.Unauthorized + "</B></BODY></HTML>";
     }
 }
Exemplo n.º 2
0
        public void ReportReceivedBatch(
            string contentType,
            string contentEncoding,
            int contentLength,
            int batchSize,
            int[] logEventSizes)
        {
            if (Start == null)
            {
                Start = _clock.Now;
            }

            // Request
            ContentType     = contentType;
            ContentEncoding = contentEncoding;
            ContentLength.Update(contentLength);

            // Batch
            BatchSize.Update(batchSize);
            _batchDistribution.AddOrUpdate(
                SizeBucketConverter.From(batchSize),
                1,
                (key, oldValue) => oldValue + 1);

            // Log events
            LogEventsPerBatch.Update(logEventSizes.Length);

            foreach (var logEventSize in logEventSizes)
            {
                LogEventSize.Update(logEventSize);

                var sizeBucket = SizeBucketConverter.From(logEventSize);
                _logEventDistribution.AddOrUpdate(sizeBucket, 1, (key, oldValue) => oldValue + 1);
            }
        }
Exemplo n.º 3
0
        public override String ToString()
        {
            var result = new StringBuilder();

            result.AppendLine(HttpStatusCodeToString(HttpStatusCode));

            AddToResponseString(result, "Cache-Control", CacheControl);
            AddToResponseString(result, "Content-length", ContentLength.ToString());
            AddToResponseString(result, "content-type", ContentType.ToString());
            AddToResponseString(result, "Date", DateTime.Now.ToString());
            AddToResponseString(result, "Server", ServerName);
            if (KeepAlive)
            {
                AddToResponseString(result, "Connection", "Keep-Alive");
            }

            foreach (var key in Headers.AllKeys)
            {
                AddToResponseString(result, key, Headers[key]);
            }

            result.AppendLine();

            return(result.ToString());
        }
Exemplo n.º 4
0
 public override int GetHashCode()
 {
     return
         (BucketID.GetHashCode() ^
          FileID.GetHashCode() ^
          ContentLength.GetHashCode());
 }
Exemplo n.º 5
0
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Clear();

            if (!String.IsNullOrEmpty(FileDownloadName))
            {
                context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=\"" + this.FileDownloadName + "\"");
            }

            if (!String.IsNullOrEmpty(ContentType))
            {
                context.HttpContext.Response.ContentType = ContentType;
            }

            if (ContentLength > 0)
            {
                context.HttpContext.Response.AddHeader("content-length", ContentLength.ToString());
            }

            if (Content != null && Content.Length > 0)
            {
                context.HttpContext.Response.BinaryWrite(Content);
            }

            if (!String.IsNullOrEmpty(VirtualPath))
            {
                context.HttpContext.Response.TransmitFile(VirtualPath);
            }

            context.HttpContext.Response.End();
        }
 public override int GetHashCode()
 {
     return(ContentLength.GetHashCode() ^
            ContentType?.GetHashCode() ?? 0 ^
            FileName?.GetHashCode() ?? 0 ^
            ContentSha1?.GetHashCode() ?? 0 ^
            TimeStamp.GetHashCode());
 }
Exemplo n.º 7
0
        private string BuildHttpRequestMessage()
        {
            var message = new StringBuilder();

            message.AppendFormat("{0} {1} HTTP/1.1{2}", Method, RequestUri.PathAndQuery, HttpControlChars.CRLF);

            var messageHeaders = new WebHeaderCollection
            {
                [HttpRequestHeader.Host]           = RequestUri.Host,
                [HttpRequestHeader.Connection]     = "Close",
                [HttpRequestHeader.AcceptEncoding] = "gzip, deflate"
            };

            // Add content type information
            if (!string.IsNullOrEmpty(ContentType))
            {
                messageHeaders[HttpRequestHeader.ContentType] = ContentType;
            }

            // Add content length information
            if (ContentLength > 0)
            {
                messageHeaders[HttpRequestHeader.ContentLength] = ContentLength.ToString();
            }

            // Add the headers
            foreach (string key in Headers.Keys)
            {
                messageHeaders.Add(key, Headers[key]);
            }

            foreach (string key in messageHeaders)
            {
                message.AppendFormat("{0}: {1}{2}", key, messageHeaders[key], HttpControlChars.CRLF);
            }

            Headers = messageHeaders;

            // Add a blank line to indicate the end of the headers
            message.Append(HttpControlChars.CRLF);

            // No content to add
            if (_requestContentBuffer == null || _requestContentBuffer.Length <= 0)
            {
                return(message.ToString());
            }

            // Add content by reading data back from the content buffer
            using (var stream = new MemoryStream(_requestContentBuffer, false))
            {
                using (var reader = new StreamReader(stream))
                {
                    message.Append(reader.ReadToEnd());
                }
            }

            return(message.ToString());
        }
 public override int GetHashCode()
 {
     return(FileID?.GetHashCode() ?? 0 ^
            FileName?.GetHashCode() ?? 0 ^
            ContentLength.GetHashCode() ^
            ContentType?.GetHashCode() ?? 0 ^
            ContentSha1?.GetHashCode() ?? 0 ^
            Action?.GetHashCode() ?? 0 ^
            UploadTimeStamp.GetHashCode());
 }
Exemplo n.º 9
0
 public override int GetHashCode()
 {
     return(AccountID.GetHashCode() ^
            BucketID.GetHashCode() ^
            ContentLength.GetHashCode() ^
            ContentSHA1.GetHashCode() ^
            FileID.GetHashCode() ^
            FileName.GetHashCode() ^
            UploadTimeStamp.GetHashCode());
 }
Exemplo n.º 10
0
        public void Should_Not_Set_Content_Length_When_Transfer_Encoding_Is_Chunked()
        {
            var app =
                DetachedApplication.Create(
                    env => new dynamic[] {200, new Hash {{"Transfer-Encoding", "chunked"}}, string.Empty});

            var response = new ContentLength(app).Call(new Dictionary<string, dynamic>());

            Assert.IsFalse(response[1].ContainsKey("Content-Length"));
        }
Exemplo n.º 11
0
        public void Should_Not_Set_Content_Length_On_304_Responses()
        {
            var app =
                DetachedApplication.Create(
                    env => new dynamic[] {304, new Hash {{"Content-Type", "text/plain"}}, string.Empty});

            var response = new ContentLength(app).Call(new Dictionary<string, dynamic>());

            Assert.IsFalse(response[1].ContainsKey("Content-Length"));
        }
Exemplo n.º 12
0
        public void Should_Set_Content_Length_On_Array_Bodies_If_None_Is_Set()
        {
            var app =
                DetachedApplication.Create(
                    env =>
                    new dynamic[]
                        {200, new Hash {{"Content-Type", "text/plain"}}, "Hello, World!"});

            var response = new ContentLength(app).Call(new Dictionary<string, dynamic>());

            Assert.AreEqual("13", response[1]["Content-Length"]);
        }
Exemplo n.º 13
0
        public void Should_Not_Change_Content_Length_If_It_Is_Already_Set()
        {
            var app =
                DetachedApplication.Create(
                    env =>
                    new dynamic[]
                        {200, new Hash {{"Content-Type", "text/plain"}, {"Content-Length", "1"}}, "Hello, World!"});

            var response = new ContentLength(app).Call(new Dictionary<string, dynamic>());

            Assert.AreEqual("1", response[1]["Content-Length"]);
        }
Exemplo n.º 14
0
        public void Should_Not_Set_Content_Length_When_Transfer_Encoding_Is_Chunked()
        {
            var app =
                DetachedApplication.Create(
                    env => new dynamic[] { 200, new Hash {
                                               { "Transfer-Encoding", "chunked" }
                                           }, string.Empty });

            var response = new ContentLength(app).Call(new Dictionary <string, dynamic>());

            Assert.IsFalse(response[1].ContainsKey("Content-Length"));
        }
Exemplo n.º 15
0
        public string ResponseToString()
        {
            string response = "";

            response += HttpVersion + " " + StatusCode + " " + StatusString + "\n";
            response += "Via: Florian Weiss SWE1-MTCG-Server\n";
            response += "Content-type: " + ContentType + "\n";
            response += "Content-length: " + ContentLength.ToString() + "\n\n";
            response += Content;

            return(response);
        }
Exemplo n.º 16
0
        public void Should_Not_Set_Content_Length_On_304_Responses()
        {
            var app =
                DetachedApplication.Create(
                    env => new dynamic[] { 304, new Hash {
                                               { "Content-Type", "text/plain" }
                                           }, string.Empty });

            var response = new ContentLength(app).Call(new Dictionary <string, dynamic>());

            Assert.IsFalse(response[1].ContainsKey("Content-Length"));
        }
Exemplo n.º 17
0
        public void Test_WriteOnStream_Should_Return_NULL_When_BodyLength_is_ZERO()
        {
            //Given
            var stream         = new StubNetworkStream(TenBytes);
            var contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(null, "0 ");
            byte[] writtenToStream = stream.GetWrittenBytes;

            //Then
            Assert.Null(writtenToStream);
        }
Exemplo n.º 18
0
        public void Should_Not_Set_Content_Length_On_Variable_Length_Bodies()
        {
            Func<string> body = () => "Hello World!";
            var iterableBody = new IterableAdapter(new Proc(body), lambda => lambda.Call());

            var app =
                DetachedApplication.Create(
                    env => new dynamic[] {200, new Hash {{"Content-Type", "text/plain"}}, iterableBody});

            var response = new ContentLength(app).Call(new Dictionary<string, dynamic>());

            Assert.IsFalse(response[1].ContainsKey("Content-Length"));
        }
Exemplo n.º 19
0
        public void Test_WriteOnStream_BodyLength_Is_Smaller_Than_DataLength()
        {
            //Given
            var stream         = new StubNetworkStream(TenBytes);
            var contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(null, " 4");
            byte[] writtenToStream = stream.GetWrittenBytes;

            //Then
            Assert.Equal("1234", Encoding.UTF8.GetString(writtenToStream));
        }
Exemplo n.º 20
0
        public void Should_Set_Content_Length_On_Array_Bodies_If_None_Is_Set()
        {
            var app =
                DetachedApplication.Create(
                    env =>
                    new dynamic[]
                    { 200, new Hash {
                          { "Content-Type", "text/plain" }
                      }, "Hello, World!" });

            var response = new ContentLength(app).Call(new Dictionary <string, dynamic>());

            Assert.AreEqual("13", response[1]["Content-Length"]);
        }
Exemplo n.º 21
0
        public void Test_WriteOnStream_Should_Prepend_BodyPart_To_WrittenBytes()
        {
            //Given
            byte[] body           = Encoding.UTF8.GetBytes("abcd");
            var    stream         = new StubNetworkStream(TenBytes);
            var    contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(body, "10");
            byte[] writtenToStream = stream.GetWrittenBytes;

            //Then
            Assert.Equal("abcd123456", Encoding.UTF8.GetString(writtenToStream));
        }
Exemplo n.º 22
0
        public void Test_WriteOnStream_Longer_Data()
        {
            //Given
            const string data           = "123456789";
            var          stream         = new StubNetworkStream(data);
            var          contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(null, "9");
            byte[] writtenToStream = stream.GetWrittenBytes;

            //Then
            Assert.Equal("123456789", Encoding.UTF8.GetString(writtenToStream));
        }
Exemplo n.º 23
0
        public void Test_WriteOnStream_ContentLengthValue_Larger_Than_StreamData()
        {
            //Given
            byte[] body           = Encoding.UTF8.GetBytes("abcd");
            var    stream         = new StubNetworkStream("123456789abcdefghijklmno");
            var    contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(body, "37");
            byte[] writtenToStream = stream.GetWrittenBytes;

            //Then
            Assert.Equal("abcd123456789abcdefghijklmno", Encoding.UTF8.GetString(writtenToStream));
        }
Exemplo n.º 24
0
        public void Should_Not_Change_Content_Length_If_It_Is_Already_Set()
        {
            var app =
                DetachedApplication.Create(
                    env =>
                    new dynamic[]
                    { 200, new Hash {
                          { "Content-Type", "text/plain" }, { "Content-Length", "1" }
                      }, "Hello, World!" });

            var response = new ContentLength(app).Call(new Dictionary <string, dynamic>());

            Assert.AreEqual("1", response[1]["Content-Length"]);
        }
Exemplo n.º 25
0
        public void Test_ReadFromStream_When_One_Read_Should_Be_Invoked()
        {
            //Given
            byte[] body           = Encoding.UTF8.GetBytes("abcd");
            var    stream         = new StubNetworkStream(TenBytes);
            var    contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(body, " 10 ");
            byte[] readFromStream = stream.GetReadBytes;

            //Then
            Assert.Equal("123456", Encoding.UTF8.GetString(readFromStream));
        }
Exemplo n.º 26
0
        public void Test_GetRemainder_NoRemainder_When_BodyPart_is_NOT_Sufficient()
        {
            //Given
            byte[] body           = Encoding.UTF8.GetBytes("abcd");
            var    stream         = new StubNetworkStream(TenBytes);
            var    contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(body, "10");
            byte[] remainder = contentHandler.Remainder;

            //Then
            Assert.Null(remainder);
        }
Exemplo n.º 27
0
        public void Test_GetRemainder_BodyPartLength_Equals_TotalBodyLength()
        {
            //Given
            byte[] body           = Encoding.UTF8.GetBytes("abcdef");
            var    stream         = new StubNetworkStream("abcdefghijklmno");
            var    contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(body, "6");
            byte[] remainder = contentHandler.Remainder;

            //Then
            Assert.Null(remainder);
        }
Exemplo n.º 28
0
        public void Test_GetRemainder_BodyPart_is_Sufficient()
        {
            //Given
            byte[] body           = Encoding.UTF8.GetBytes("abcdef");
            var    stream         = new StubNetworkStream("abcdefghijklmno");
            var    contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(body, "5");
            byte[] remainder = contentHandler.Remainder;

            //Then
            Assert.Equal("f", Encoding.UTF8.GetString(remainder));
        }
Exemplo n.º 29
0
        public void Test_ReadFromStream_Given_BodyPart_is_Sufficient()
        {
            //Given
            byte[] body           = Encoding.UTF8.GetBytes("abcd");
            var    stream         = new StubNetworkStream(TenBytes);
            var    contentHandler = new ContentLength(stream, stream);

            //When
            contentHandler.HandleResponseBody(body, "4");
            byte[] read = stream.GetReadBytes;

            //Then
            Assert.Null(read);
        }
Exemplo n.º 30
0
        private void BuildServerVariables(HttpClient client)
        {
            ServerVariables = new NameValueCollection();

            // Add all headers.

            var allHttp = new StringBuilder();
            var allRaw  = new StringBuilder();

            foreach (var item in client.Headers)
            {
                ServerVariables[item.Key] = item.Value;

                string httpKey = "HTTP_" + (item.Key.Replace('-', '_')).ToUpperInvariant();

                ServerVariables[httpKey] = item.Value;

                allHttp.Append(httpKey);
                allHttp.Append('=');
                allHttp.Append(item.Value);
                allHttp.Append("\r\n");

                allRaw.Append(item.Key);
                allRaw.Append('=');
                allRaw.Append(item.Value);
                allRaw.Append("\r\n");
            }

            ServerVariables["ALL_HTTP"] = allHttp.ToString();
            ServerVariables["ALL_RAW"]  = allRaw.ToString();

            ServerVariables["CONTENT_LENGTH"] = ContentLength.ToString(CultureInfo.InvariantCulture);
            ServerVariables["CONTENT_TYPE"]   = ContentType;

            ServerVariables["LOCAL_ADDR"] = client.Server.EndPoint.Address.ToString();
            ServerVariables["PATH_INFO"]  = Path;

            string[] parts = client.Request.Split(new[] { '?' }, 2);

            ServerVariables["QUERY_STRING"]    = parts.Length == 2 ? parts[1] : "";
            ServerVariables["REMOTE_ADDR"]     = UserHostAddress;
            ServerVariables["REMOTE_HOST"]     = UserHostName;
            ServerVariables["REMOTE_PORT"]     = null;
            ServerVariables["REQUEST_METHOD"]  = RequestType;
            ServerVariables["SCRIPT_NAME"]     = Path;
            ServerVariables["SERVER_NAME"]     = client.Server.ServerUtility.MachineName;
            ServerVariables["SERVER_PORT"]     = client.Server.EndPoint.Port.ToString(CultureInfo.InvariantCulture);
            ServerVariables["SERVER_PROTOCOL"] = client.Protocol;
            ServerVariables["URL"]             = Path;
        }
Exemplo n.º 31
0
 internal void Apply(HttpRequestMessageProperty hp)
 {
     if (Headers != null)
     {
         foreach (var key in Headers.AllKeys)
         {
             hp.Headers [key] = Headers [key];
         }
     }
     if (Accept != null)
     {
         hp.Headers ["Accept"] = Accept;
     }
     if (ContentLength > 0)
     {
         hp.Headers ["Content-Length"] = ContentLength.ToString(NumberFormatInfo.InvariantInfo);
     }
     if (ContentType != null)
     {
         hp.Headers ["Content-Type"] = ContentType;
     }
     if (IfMatch != null)
     {
         hp.Headers ["If-Match"] = IfMatch;
     }
     if (IfModifiedSince != null)
     {
         hp.Headers ["If-Modified-Since"] = IfModifiedSince;
     }
     if (IfNoneMatch != null)
     {
         hp.Headers ["If-None-Match"] = IfNoneMatch;
     }
     if (IfUnmodifiedSince != null)
     {
         hp.Headers ["If-Unmodified-Since"] = IfUnmodifiedSince;
     }
     if (Method != null)
     {
         hp.Method = Method;
     }
     if (SuppressEntityBody)
     {
         hp.SuppressEntityBody = true;
     }
     if (UserAgent != null)
     {
         hp.Headers ["User-Agent"] = UserAgent;
     }
 }
Exemplo n.º 32
0
 private void CreateCommonHeaders(SipUser sipUser, LocalSipUserAgentServer localSipUas, SipTransportManager sipTransportManager)
 {
     this.viaHeader     = new ViaHeader(localSipUas, sipTransportManager.SipProtocol, sipTransportManager.SipTransport);
     this.fromHeader    = new FromHeader(sipUser, localSipUas, sipTransportManager.SipProtocol);
     this.toHeader      = new ToHeader(localSipUas, sipTransportManager.SipProtocol);
     this.callIdHeader  = new CallIdHeader();
     this.contactHeader = new ContactHeader(localSipUas, sipTransportManager.SipProtocol);
     this.routeHeader   = new RouteHeader(localSipUas, sipTransportManager.SipProtocol);
     this.userAgent     = new UserAgentHeader();
     this.expiresHeader = new ExpiresHeader();
     this.maxForwards   = new MaxForwardsHeader();
     this.allowHeader   = new AllowHeader();
     this.contentLength = new ContentLength(body);
 }
Exemplo n.º 33
0
        public void Should_Not_Set_Content_Length_On_Variable_Length_Bodies()
        {
            Func <string> body         = () => "Hello World!";
            var           iterableBody = new IterableAdapter(new Proc(body), lambda => lambda.Call());

            var app =
                DetachedApplication.Create(
                    env => new dynamic[] { 200, new Hash {
                                               { "Content-Type", "text/plain" }
                                           }, iterableBody });

            var response = new ContentLength(app).Call(new Dictionary <string, dynamic>());

            Assert.IsFalse(response[1].ContainsKey("Content-Length"));
        }
Exemplo n.º 34
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Via.ToString());
            sb.Append(From.ToString());
            sb.Append($"To: <sip:{To.ToString()}>").AppendLine();
            sb.Append(CallId.ToString());
            sb.Append(CSeq.ToString());
            if (!string.IsNullOrEmpty(UserAgent))
            {
                sb.Append($"User-Agent: {UserAgent}").AppendLine();
            }
            if (Expires > 0)
            {
                sb.Append($"Expires: {Expires.ToString()}").AppendLine();
            }
            if (!string.IsNullOrEmpty(Accept))
            {
                sb.Append($"Accept: {Accept}").AppendLine();
            }
            if (!string.IsNullOrEmpty(ContentType))
            {
                sb.Append($"Content-Type: {ContentType}").AppendLine();
            }
            if (ContentLength > 0)
            {
                sb.Append($"Content-Length: {ContentLength.ToString()}").AppendLine();
            }
            sb.Append($"Max-Forwards: {MaxForwards}").AppendLine();
            if (Allow != null && Allow.Count > 0)
            {
                sb.Append($"Allow: {string.Join(",",Allow)}").AppendLine();
            }
            if (CustomHeaders.Count() > 0)
            {
                foreach (KeyValuePair <string, string> Header in CustomHeaders)
                {
                    sb.Append($"X-{Header.Key}: {Header.Value}").AppendLine();
                }
            }

            return(sb.ToString());
        }
Exemplo n.º 35
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("URI:" + uri.AbsoluteUri);
            if (Cookies != null)
            {
                foreach (HttpCookie cookie in Cookies)
                {
                    sb.AppendLine("Cookie:" + cookie.Name + ":" + cookie.Value);
                }
            }
            sb.AppendLine("Gzip:" + Gzip.ToString());
            sb.AppendLine("Method:" + Method);
            sb.AppendLine("ContentLength:" + ContentLength.ToString());
            sb.AppendLine("KeepAlive:" + KeepAlive.ToString());
            sb.AppendLine();
            sb.AppendLine(Data);
            return(sb.ToString());
        }