public void Read_PastEndOfStream_ReturnsAmountRead()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);

            stream.Seek (-1, SeekOrigin.End);
            int amount_read = stream.Read (buffer, 0, 2);

            Assert.AreEqual (1, amount_read);
        }
        public void Read_ReadLastItem_UpdatesPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);

            stream.Seek (-1, SeekOrigin.End);
            stream.Read (buffer, 0, 1);

            long position = stream.Position;
            Assert.AreEqual (10, position);
        }
Exemple #3
0
        public HttpResponse(IHttpTransaction transaction, IOStream stream)
        {
            Transaction = transaction;
            IOStream = stream;

            StatusCode = 200;

            WriteHeaders = true;

            Headers = new HttpHeaders ();
            Stream = new HttpResponseStream (this, IOStream);
            Stream.Chunked = (transaction.Request.MajorVersion > 0 && transaction.Request.MinorVersion > 0);
        }
        public void Insert_BeginningOfStream_SetsCorrectPosition()
        {
            var stream = new HttpResponseStream ();
            var write_buffer = new byte [10];

            stream.Write (write_buffer, 0, 10);
            stream.Position = 0;

            stream.Insert (write_buffer, 0, 5);

            var position = stream.Position;
            Assert.AreEqual (5, position);
        }
        public void Insert_BeginningOfStream_SetsCorrectLength()
        {
            var stream = new HttpResponseStream ();
            var write_buffer = new byte [10];

            stream.Write (write_buffer, 0, 10);
            stream.Position = 0;

            stream.Insert (write_buffer, 0, 10);

            var length = stream.Length;
            Assert.AreEqual (20, length);
        }
        public void Read_MultipleBuffers_UpdatesPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            stream.Seek (15, SeekOrigin.Begin);
            stream.Read (buffer, 0, 5);

            long position = stream.Position;
            Assert.AreEqual (20, position);
        }
Exemple #7
0
        public HttpResponse(IHttpTransaction transaction)
        {
            Transaction = transaction;

            StatusCode = 200;

            WriteHeaders = true;

            Headers = new HttpHeaders ();
            Stream = new HttpResponseStream ();
            Writer = new StreamWriter (Stream);
            Cookies = new Dictionary<string, HttpCookie> ();

            SetStandardHeaders ();
        }
        public void Read_SingleBuffer_CorrectData()
        {
            var stream = new HttpResponseStream ();
            var write_buffer = new byte [3];
            var read_buffer = new byte [1];

            write_buffer [2] = 0xFA;

            stream.Write (write_buffer, 0, 3);

            stream.Seek (-1, SeekOrigin.End);
            stream.Read (read_buffer, 0, 1);

            byte read_byte = read_buffer [0];
            Assert.AreEqual (0xFA, read_byte);
        }
Exemple #9
0
        public HttpResponse(IHttpTransaction transaction, Encoding encoding)
        {
            Transaction = transaction;
            Encoding = encoding;

            StatusCode = 200;

            WriteHeaders = true;
            WriteStatusLine = true;

            Headers = new HttpHeaders ();
            Stream = new HttpResponseStream ();
            Cookies = new Dictionary<string, HttpCookie> ();

            SetStandardHeaders ();
        }
        public void Insert_BeginningOfStream_SetsCorrectData()
        {
            var stream = new HttpResponseStream ();
            var write_buffer = new byte [10];
            var write_buffer2 = new byte [10];

            stream.Write (write_buffer, 0, 10);
            stream.Position = 0;

            write_buffer2 [2] = 0xFA;
            stream.Insert (write_buffer2, 0, 10);

            stream.Position = 2;
            var data = stream.ReadByte ();
            Assert.AreEqual (0xFA, data);
        }
Exemple #11
0
        public HttpResponse(IHttpTransaction transaction, IOStream stream)
        {
            Transaction = transaction;
            IOStream = stream;

            StatusCode = 200;

            WriteHeaders = true;

            Headers = new HttpHeaders ();
            Stream = new HttpResponseStream (this, IOStream);
            Stream.Chunked = (transaction.Request.MajorVersion > 0 && transaction.Request.MinorVersion > 0);

            end_watcher = new AsyncWatcher (IOLoop.Instance.EventLoop, OnEnd);
            end_watcher.Start ();
        }
        public void Read_MultipleBuffers_CorrectData()
        {
            var stream = new HttpResponseStream ();
            var write_buffer1 = new byte [3];
            var write_buffer2 = new byte [3];
            var read_buffer = new byte [6];

            stream.Write (write_buffer1, 0, 3);

            write_buffer2 [0] = 0xFA;
            stream.Write (write_buffer2, 0, 3);

            stream.Seek (0, SeekOrigin.Begin);
            stream.Read (read_buffer, 0, 6);

            byte read_byte = read_buffer [3];
            Assert.AreEqual (0xFA, read_byte);
        }
        public WebSocketHttpListenerDuplexStream(HttpRequestStream inputStream,
            HttpResponseStream outputStream,
            HttpListenerContext context)
        {
            Debug.Assert(inputStream != null, "'inputStream' MUST NOT be NULL.");
            Debug.Assert(outputStream != null, "'outputStream' MUST NOT be NULL.");
            Debug.Assert(context != null, "'context' MUST NOT be NULL.");
            Debug.Assert(inputStream.CanRead, "'inputStream' MUST support read operations.");
            Debug.Assert(outputStream.CanWrite, "'outputStream' MUST support write operations.");

            _inputStream = inputStream;
            _outputStream = outputStream;
            _context = context;

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Associate(inputStream, this);
                NetEventSource.Associate(outputStream, this);
            }
        }
        public void Seek_SeekToBeginningOfEmptyStream_SetsPosition()
        {
            var stream = new HttpResponseStream ();

            stream.Seek (0, SeekOrigin.Begin);

            var position = stream.Position;
            Assert.AreEqual (0, position);
        }
        public void SetLength_EqualToCurrentLength_LengthStaysTheSame()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            stream.SetLength (20);

            long length = stream.Length;
            Assert.AreEqual (20, length);
        }
        public void CanWriteReturnsTrue()
        {
            var stream = new HttpResponseStream(Mock.Of <IHttpBodyControlFeature>(), new MockHttpResponseControl());

            Assert.True(stream.CanWrite);
        }
        public void Seek_FromEnd_SetsPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Seek (-3, SeekOrigin.End);

            long pos = stream.Position;
            Assert.AreEqual (7, pos);
        }
        public void Write_InFirstBufferOfTwoBufferStream_SetsCorrectLength()
        {
            var stream = new HttpResponseStream ();
            var write_buffer = new byte [5];

            stream.Write (write_buffer, 0, 5);
            stream.Write (write_buffer, 0, 5);
            stream.Seek (-6, SeekOrigin.End);

            stream.Write (write_buffer, 0, 5);

            var length = stream.Length;
            Assert.AreEqual (10, length);
        }
        public void SetLengthThrows()
        {
            var stream = new HttpResponseStream(Mock.Of <IHttpBodyControlFeature>(), new MockHttpResponseControl());

            Assert.Throws <NotSupportedException>(() => stream.SetLength(0));
        }
Exemple #20
0
 public HttpStreams(Stream request, IHttpResponseControl httpResponseControl)
 {
     _request  = new HttpStreamRequestStream(request);
     _response = new HttpResponseStream(httpResponseControl);
 }
        public void Write_AcrossEntireMiddleBufferOfThreeBufferStream_SetsCorrectLength()
        {
            var stream = new HttpResponseStream ();
            var write_buffer = new byte [5];
            var write_buffer2 = new byte [6];

            stream.Write (write_buffer, 0, 5);
            stream.Write (write_buffer, 0, 5);
            stream.Write (write_buffer, 0, 5);
            stream.Seek (2, SeekOrigin.Begin);

            stream.Write (write_buffer2, 0, 6);

            var length = stream.Length;
            Assert.AreEqual (15, length);
        }
Exemple #22
0
        void System.Web.IHttpHandler.ProcessRequest(HttpContext context)
#endif
        {
            HttpRequest request = context.Request;
            // val is URL-encoded, which means every + has been replaced with ' ', we
            // need to revert that or the base64 conversion will fail.
            string d = request.QueryString ["d"];

            if (!String.IsNullOrEmpty(d))
            {
                d = d.Replace(' ', '+');
            }

            AssemblyEmbeddedResources entry;
            EmbeddedResource          res = DecryptAssemblyResource(d, out entry);
            WebResourceAttribute      wra = res != null ? res.Attribute : null;

            if (wra == null)
            {
                throw new HttpException(404, "Resource not found");
            }

            Assembly assembly;

            if (entry.AssemblyName == "s")
            {
                assembly = currAsm;
            }
            else
            {
                assembly = Assembly.Load(entry.AssemblyName);
            }

            HttpResponse response  = context.Response;
            string       req_cache = request.Headers ["Cache-Control"];

            if (String.Compare(req_cache, "max-age=0", StringComparison.Ordinal) == 0)
            {
                long atime;
                if (Int64.TryParse(request.QueryString ["t"], out atime))
                {
                    if (atime == File.GetLastWriteTimeUtc(assembly.Location).Ticks)
                    {
                        response.Clear();
                        response.StatusCode   = 304;
                        response.ContentType  = null;
                        response.CacheControl = "public";                         // easier to set it to public as MS than remove it
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }
                }
            }
            string modif_since = request.Headers ["If-Modified-Since"];

            if (!String.IsNullOrEmpty(modif_since))
            {
                try {
                    DateTime modif;
                    if (DateTime.TryParseExact(modif_since, "r", null, 0, out modif))
                    {
                        if (File.GetLastWriteTimeUtc(assembly.Location) <= modif)
                        {
                            response.Clear();
                            response.StatusCode   = 304;
                            response.ContentType  = null;
                            response.CacheControl = "public";                             // easier to set it to public as MS than remove it
                            context.ApplicationInstance.CompleteRequest();
                            return;
                        }
                    }
                } catch {}
            }

            response.ContentType = wra.ContentType;

            DateTime utcnow = DateTime.UtcNow;

            response.Headers.Add("Last-Modified", utcnow.ToString("r"));
            response.ExpiresAbsolute = utcnow.AddYears(1);
            response.CacheControl    = "public";

            Stream s = assembly.GetManifestResourceStream(res.Name);

            if (s == null)
            {
                throw new HttpException(404, "Resource " + res.Name + " not found");
            }

            if (wra.PerformSubstitution)
            {
                using (StreamReader r = new StreamReader(s)) {
                    TextWriter w = response.Output;
                    new PerformSubstitutionHelper(assembly).PerformSubstitution(r, w);
                }
            }
            else if (response.OutputStream is HttpResponseStream)
            {
                UnmanagedMemoryStream st      = (UnmanagedMemoryStream)s;
                HttpResponseStream    hstream = (HttpResponseStream)response.OutputStream;
                unsafe {
                    hstream.WritePtr(new IntPtr(st.PositionPointer), (int)st.Length);
                }
            }
            else
            {
                byte [] buf    = new byte [1024];
                Stream  output = response.OutputStream;
                int     c;
                do
                {
                    c = s.Read(buf, 0, 1024);
                    output.Write(buf, 0, c);
                } while (c > 0);
            }
#if SYSTEM_WEB_EXTENSIONS
            TextWriter writer = response.Output;
            foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes(typeof(ScriptResourceAttribute), false))
            {
                if (String.Compare(sra.ScriptName, res.Name, StringComparison.Ordinal) == 0)
                {
                    string      scriptResourceName = sra.ScriptResourceName;
                    ResourceSet rset = null;
                    try {
                        rset = new ResourceManager(scriptResourceName, assembly).GetResourceSet(Threading.Thread.CurrentThread.CurrentUICulture, true, true);
                    }
                    catch (MissingManifestResourceException) {
#if TARGET_JVM // GetResourceSet does not throw  MissingManifestResourceException if ressource is not exists
                    }
                    if (rset == null)
                    {
#endif
                        if (scriptResourceName.EndsWith(".resources"))
                        {
                            scriptResourceName = scriptResourceName.Substring(0, scriptResourceName.Length - 10);
                            rset = new ResourceManager(scriptResourceName, assembly).GetResourceSet(Threading.Thread.CurrentThread.CurrentUICulture, true, true);
                        }
#if !TARGET_JVM
                        else
                        {
                            throw;
                        }
#endif
                    }
                    if (rset == null)
                    {
                        break;
                    }
                    writer.WriteLine();
                    string ns   = sra.TypeName;
                    int    indx = ns.LastIndexOf('.');
                    if (indx > 0)
                    {
                        writer.WriteLine("Type.registerNamespace('" + ns.Substring(0, indx) + "')");
                    }
                    writer.Write("{0}={{", sra.TypeName);
                    bool first = true;
                    foreach (DictionaryEntry de in rset)
                    {
                        string value = de.Value as string;
                        if (value != null)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                writer.Write(',');
                            }
                            writer.WriteLine();
                            writer.Write("{0}:{1}", GetScriptStringLiteral((string)de.Key), GetScriptStringLiteral(value));
                        }
                    }
                    writer.WriteLine();
                    writer.WriteLine("};");
                    break;
                }
            }

            bool notifyScriptLoaded = request.QueryString ["n"] == "t";
            if (notifyScriptLoaded)
            {
                writer.WriteLine();
                writer.WriteLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
            }
#endif
        }
        public void BeginReadThrows()
        {
            var stream = new HttpResponseStream(Mock.Of <IHttpBodyControlFeature>(), new MockHttpResponseControl());

            Assert.Throws <NotSupportedException>(() => stream.BeginRead(new byte[1], 0, 1, null, null));
        }
 public AsyncHttpRequest(HttpWebRequest request, TextWriter logWriter, bool debug, Stopwatch stopwatch, HttpResponseStream responseStreamCallback)
 {
     m_request        = request;
     m_responseStream = responseStreamCallback;
     m_logWriter      = logWriter;
     m_DEBUG          = debug;
     m_stopwatch      = stopwatch;
     if (DEBUG)
     {
         m_stopwatch.Start();
     }
     if (DEBUG)
     {
         m_logWriter.WriteLine("Beginning call to {0} on thread: {1}", request.RequestUri, Thread.CurrentThread.ManagedThreadId);
     }
     request.BeginGetResponse(RequestIsComplete, request);
 }
        private static async Task <HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context,
                                                                                          string?subProtocol,
                                                                                          int receiveBufferSize,
                                                                                          TimeSpan keepAliveInterval,
                                                                                          ArraySegment <byte> internalBuffer)
        {
            HttpListenerWebSocketContext?webSocketContext = null;

            try
            {
                // get property will create a new response if one doesn't exist.
                HttpListenerResponse response = context.Response;
                HttpListenerRequest  request  = context.Request;
                ValidateWebSocketHeaders(context);

                string?secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];

                // Optional for non-browser client
                string?origin = request.Headers[HttpKnownHeaderNames.Origin];

                List <string> secWebSocketProtocols = new List <string>();
                string        outgoingSecWebSocketProtocolString;
                bool          shouldSendSecWebSocketProtocolHeader =
                    ProcessWebSocketProtocolHeader(
                        request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol],
                        subProtocol,
                        out outgoingSecWebSocketProtocolString);

                if (shouldSendSecWebSocketProtocolHeader)
                {
                    secWebSocketProtocols.Add(outgoingSecWebSocketProtocolString);
                    response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol,
                                         outgoingSecWebSocketProtocolString);
                }

                // negotiate the websocket key return value
                string?secWebSocketKey    = request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
                string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey);

                response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
                response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken);
                response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept);

                response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101
                response.ComputeCoreHeaders();
                ulong hresult = SendWebSocketHeaders(response);
                if (hresult != 0)
                {
                    throw new WebSocketException((int)hresult,
                                                 SR.Format(SR.net_WebSockets_NativeSendResponseHeaders,
                                                           nameof(AcceptWebSocketAsync),
                                                           hresult));
                }

                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.Origin} = {origin}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketVersion} = {secWebSocketVersion}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketKey} = {secWebSocketKey}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketAccept} = {secWebSocketAccept}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketProtocol} = {request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol]}");
                    NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketProtocol} = {outgoingSecWebSocketProtocolString}");
                }

                await response.OutputStream.FlushAsync().SuppressContextFlow();

                HttpResponseStream responseStream = (response.OutputStream as HttpResponseStream) !;
                Debug.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream.");
                ((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode();
                HttpRequestStream requestStream = new HttpRequestStream(context);
                requestStream.SwitchToOpaqueMode();
                WebSocketHttpListenerDuplexStream webSocketStream =
                    new WebSocketHttpListenerDuplexStream(requestStream, responseStream, context);
                WebSocket webSocket = ServerWebSocket.Create(webSocketStream,
                                                             subProtocol,
                                                             receiveBufferSize,
                                                             keepAliveInterval,
                                                             internalBuffer);

                webSocketContext = new HttpListenerWebSocketContext(
                    request.Url !,
                    request.Headers,
                    request.Cookies,
                    context.User !,
                    request.IsAuthenticated,
                    request.IsLocal,
                    request.IsSecureConnection,
                    origin !,
                    secWebSocketProtocols.AsReadOnly(),
                    secWebSocketVersion !,
                    secWebSocketKey !,
                    webSocket);

                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Associate(context, webSocketContext);
                    NetEventSource.Associate(webSocketContext, webSocket);
                }
            }
            catch (Exception ex)
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Error(context, ex);
                }
                throw;
            }

            return(webSocketContext);
        }
Exemple #26
0
        internal static async Task <HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context,
                                                                                           string subProtocol,
                                                                                           int receiveBufferSize,
                                                                                           TimeSpan keepAliveInterval,
                                                                                           ArraySegment <byte>?internalBuffer = null)
        {
            ValidateOptions(subProtocol, receiveBufferSize, MinSendBufferSize, keepAliveInterval);

            // get property will create a new response if one doesn't exist.
            HttpListenerResponse response = context.Response;
            HttpListenerRequest  request  = context.Request;

            ValidateWebSocketHeaders(context);

            string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];

            // Optional for non-browser client
            string origin = request.Headers[HttpKnownHeaderNames.Origin];

            string[] secWebSocketProtocols = null;
            string   outgoingSecWebSocketProtocolString;
            bool     shouldSendSecWebSocketProtocolHeader =
                ProcessWebSocketProtocolHeader(
                    request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol],
                    subProtocol,
                    out outgoingSecWebSocketProtocolString);

            if (shouldSendSecWebSocketProtocolHeader)
            {
                secWebSocketProtocols = new string[] { outgoingSecWebSocketProtocolString };
                response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, outgoingSecWebSocketProtocolString);
            }

            // negotiate the websocket key return value
            string secWebSocketKey    = request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
            string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey);

            response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
            response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken);
            response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept);

            response.StatusCode        = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101
            response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols);

            HttpResponseStream responseStream = response.OutputStream as HttpResponseStream;

            // Send websocket handshake headers
            await responseStream.WriteWebSocketHandshakeHeadersAsync().ConfigureAwait(false);

            const int     MinBufferSize = 14;                                                                  // from ManagedWebSocket.MaxMessageHeaderLength
            Memory <byte> buffer        =
                internalBuffer.GetValueOrDefault().Count >= MinBufferSize?internalBuffer.GetValueOrDefault() : // use provided buffer if it's big enough
                    receiveBufferSize >= MinBufferSize ? new byte[receiveBufferSize] :                         // or use provided size if it's big enough
                    Memory <byte> .Empty;                                                                      // or use the default

            WebSocket webSocket = WebSocket.CreateFromStream(context.Connection.ConnectedStream, isServer: true, subProtocol, keepAliveInterval, buffer);

            HttpListenerWebSocketContext webSocketContext = new HttpListenerWebSocketContext(
                request.Url,
                request.Headers,
                request.Cookies,
                context.User,
                request.IsAuthenticated,
                request.IsLocal,
                request.IsSecureConnection,
                origin,
                secWebSocketProtocols != null ? secWebSocketProtocols : Array.Empty <string>(),
                secWebSocketVersion,
                secWebSocketKey,
                webSocket);

            return(webSocketContext);
        }
        public void SetLength_LessThanSingleBuffer_Truncates()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.SetLength (5);

            long length = stream.Length;
            Assert.AreEqual (5, length);
        }
        public void Write_SeekedBackPastLastSegmentWriteOverAll_SetsPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];
            var buffer_big = new byte [25];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            stream.Seek (-15, SeekOrigin.Current);
                        Assert.AreEqual (5, stream.Position);

            stream.Write (buffer_big, 0, 25);

            long pos = stream.Position;
            Assert.AreEqual (30, pos);
        }
        public void SetLength_MultiBuffer_AddsFiller()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            stream.SetLength (25);

            long length = stream.Length;
            Assert.AreEqual (25, length);
        }
        public void Write_TruncatedSegment_SetsLength()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 5);

            long len = stream.Length;
            Assert.AreEqual (5, len);
        }
 public async Task ReadAsyncThrows()
 {
     var stream = new HttpResponseStream(Mock.Of <IHttpBodyControlFeature>(), new MockHttpResponseControl());
     await Assert.ThrowsAsync <NotSupportedException>(() => stream.ReadAsync(new byte[1], 0, 1));
 }
        public void Write_TwoSegments_SetsPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            long pos = stream.Position;
            Assert.AreEqual (20, pos);
        }
        public void Write_SeekedBackInLastSegment_SetsPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            stream.Seek (-5, SeekOrigin.Current);
            stream.Write (buffer, 0, 10);

            long pos = stream.Position;
            Assert.AreEqual (25, pos);
        }
        public void SeekThrows()
        {
            var stream = new HttpResponseStream(Mock.Of <IHttpBodyControlFeature>(), new MockHttpResponseControl());

            Assert.Throws <NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin));
        }
        public void Write_ShorterThanBufferInSingleBuffer_SetsCorrectLength()
        {
            var stream = new HttpResponseStream ();
            var write_buffer = new byte [5];

            stream.Write (write_buffer, 0, 5);

            stream.Position = 2;
            stream.Write (write_buffer, 0, 2);

            var length = stream.Length;
            Assert.AreEqual (5, length);
        }
        public void Seek_FromCurrentBackwards_SetsPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            stream.Seek (-5, SeekOrigin.Current);

            long pos = stream.Position;
            Assert.AreEqual (15, pos);
        }
        public void Write_TwoSegments_SetsLength()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            long len = stream.Length;
            Assert.AreEqual (20, len);
        }
        public void Seek_FromEndMultipleBuffersAcrossBoundries_SetsPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);
            stream.Seek (-25, SeekOrigin.End);

            long pos = stream.Position;
            Assert.AreEqual (5, pos);
        }
Exemple #39
0
        void SendEmbeddedResource(HttpContext context, out EmbeddedResource res, out Assembly assembly)
        {
            HttpRequest         request     = context.Request;
            NameValueCollection queryString = request.QueryString;

            // val is URL-encoded, which means every + has been replaced with ' ', we
            // need to revert that or the base64 conversion will fail.
            string d = queryString ["d"];

            if (!String.IsNullOrEmpty(d))
            {
                d = d.Replace(' ', '+');
            }

            AssemblyEmbeddedResources entry;

            res = DecryptAssemblyResource(d, out entry);
            WebResourceAttribute wra = res != null ? res.Attribute : null;

            if (wra == null)
            {
                throw new HttpException(404, "Resource not found");
            }

            if (entry.AssemblyName == "s")
            {
                assembly = currAsm;
            }
            else
            {
                assembly = Assembly.Load(entry.AssemblyName);
            }

            DateTime modified;

            if (HasIfModifiedSince(request, out modified))
            {
                if (File.GetLastWriteTimeUtc(assembly.Location) <= modified)
                {
                    RespondWithNotModified(context);
                    return;
                }
            }

            HttpResponse response = context.Response;

            response.ContentType = wra.ContentType;

            DateTime utcnow = DateTime.UtcNow;

            response.Headers.Add("Last-Modified", utcnow.ToString("r"));
            response.ExpiresAbsolute = utcnow.AddYears(1);
            response.CacheControl    = "public";

            Stream s = assembly.GetManifestResourceStream(res.Name);

            if (s == null)
            {
                throw new HttpException(404, "Resource " + res.Name + " not found");
            }

            if (wra.PerformSubstitution)
            {
                using (StreamReader r = new StreamReader(s)) {
                    TextWriter w = response.Output;
                    new PerformSubstitutionHelper(assembly).PerformSubstitution(r, w);
                }
            }
            else if (response.OutputStream is HttpResponseStream)
            {
                UnmanagedMemoryStream st      = (UnmanagedMemoryStream)s;
                HttpResponseStream    hstream = (HttpResponseStream)response.OutputStream;
                unsafe {
                    hstream.WritePtr(new IntPtr(st.PositionPointer), (int)st.Length);
                }
            }
            else
            {
                byte [] buf    = new byte [1024];
                Stream  output = response.OutputStream;
                int     c;
                do
                {
                    c = s.Read(buf, 0, 1024);
                    output.Write(buf, 0, c);
                } while (c > 0);
            }
        }
        public void CanSeekReturnsFalse()
        {
            var stream = new HttpResponseStream(Mock.Of <IHttpBodyControlFeature>(), new MockHttpResponseControl());

            Assert.False(stream.CanSeek);
        }
        internal static async Task <HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context,
                                                                                           string?subProtocol,
                                                                                           int receiveBufferSize,
                                                                                           TimeSpan keepAliveInterval,
                                                                                           ArraySegment <byte>?internalBuffer = null)
        {
            ValidateOptions(subProtocol, receiveBufferSize, MinSendBufferSize, keepAliveInterval);

            // get property will create a new response if one doesn't exist.
            HttpListenerResponse response = context.Response;
            HttpListenerRequest  request  = context.Request;

            ValidateWebSocketHeaders(context);

            string?secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];

            // Optional for non-browser client
            string?origin = request.Headers[HttpKnownHeaderNames.Origin];

            string[]? secWebSocketProtocols = null;
            string outgoingSecWebSocketProtocolString;
            bool   shouldSendSecWebSocketProtocolHeader =
                ProcessWebSocketProtocolHeader(
                    request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol],
                    subProtocol,
                    out outgoingSecWebSocketProtocolString);

            if (shouldSendSecWebSocketProtocolHeader)
            {
                secWebSocketProtocols = new string[] { outgoingSecWebSocketProtocolString };
                response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, outgoingSecWebSocketProtocolString);
            }

            // negotiate the websocket key return value
            string?secWebSocketKey    = request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
            string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey);

            response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
            response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken);
            response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept);

            response.StatusCode        = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101
            response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols) !;

            HttpResponseStream responseStream = (response.OutputStream as HttpResponseStream) !;

            // Send websocket handshake headers
            await responseStream.WriteWebSocketHandshakeHeadersAsync().ConfigureAwait(false);

            WebSocket webSocket = WebSocket.CreateFromStream(context.Connection.ConnectedStream, isServer: true, subProtocol, keepAliveInterval);

            HttpListenerWebSocketContext webSocketContext = new HttpListenerWebSocketContext(
                request.Url !,
                request.Headers,
                request.Cookies,
                context.User !,
                request.IsAuthenticated,
                request.IsLocal,
                request.IsSecureConnection,
                origin !,
                secWebSocketProtocols ?? Array.Empty <string>(),
                secWebSocketVersion !,
                secWebSocketKey !,
                webSocket);

            return(webSocketContext);
        }
        public void Seek_FromBeginningMultipleSegments_SetsPosition()
        {
            var stream = new HttpResponseStream ();
            var buffer = new byte [10];

            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);
            stream.Write (buffer, 0, 10);

            stream.Seek (25, SeekOrigin.Begin);

            long pos = stream.Position;
            Assert.AreEqual (25, pos);
        }
Exemple #43
0
        /// <summary>
        /// Возвращает поток тела сообщения.
        /// </summary>
        /// <returns>>Если тело сообщения отсутствует, или оно уже было загружено, то будет возвращено значение <see langword="null"/>.</returns>
        /// <exception cref="System.InvalidOperationException">Вызов метода из ошибочного ответа.</exception>
        /// <exception cref="xNet.Net.HttpException">Ошибка при работе с HTTP-протоколом.</exception>
        public Stream ToStream()
        {
            #region Проверка состояния

            if (HasError)
            {
                throw new InvalidOperationException(
                    Resources.InvalidOperationException_HttpResponse_HasError);
            }

            #endregion

            if (MessageBodyLoaded)
            {
                return null;
            }

            var stream = new HttpResponseStream(_request.ClientStream, _receiverHelper, (ex) =>
            {
                if (ex != null)
                {
                    HasError = true;

                    if (ex is IOException || ex is InvalidOperationException)
                    {
                        throw NewHttpException(Resources.HttpException_FailedReceiveMessageBody, ex);
                    }

                    throw ex;
                }

                if (ConnectionClosed())
                {
                    _request.Dispose();
                }

                MessageBodyLoaded = true;
            });

            if (_headers.ContainsKey("Content-Encoding"))
            {
                return GetZipStream(stream);
            }

            return stream;
        }
        private static async Task <HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context,
                                                                                          string subProtocol,
                                                                                          int receiveBufferSize,
                                                                                          TimeSpan keepAliveInterval,
                                                                                          ArraySegment <byte> internalBuffer)
        {
            HttpListenerWebSocketContext webSocketContext = null;

            if (Logging.On)
            {
                Logging.Enter(Logging.WebSockets, context, "AcceptWebSocketAsync", "");
            }

            try
            {
                // get property will create a new response if one doesn't exist.
                HttpListenerResponse response = context.Response;
                HttpListenerRequest  request  = context.Request;
                ValidateWebSocketHeaders(context);

                string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];

                // Optional for non-browser client
                string origin = request.Headers[HttpKnownHeaderNames.Origin];

                List <string> secWebSocketProtocols = new List <string>();
                string        outgoingSecWebSocketProtocolString;
                bool          shouldSendSecWebSocketProtocolHeader =
                    WebSocketHelpers.ProcessWebSocketProtocolHeader(
                        request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol],
                        subProtocol,
                        out outgoingSecWebSocketProtocolString);

                if (shouldSendSecWebSocketProtocolHeader)
                {
                    secWebSocketProtocols.Add(outgoingSecWebSocketProtocolString);
                    response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol,
                                         outgoingSecWebSocketProtocolString);
                }

                // negotiate the websocket key return value
                string secWebSocketKey    = request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
                string secWebSocketAccept = WebSocketHelpers.GetSecWebSocketAcceptString(secWebSocketKey);

                response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
                response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketHelpers.WebSocketUpgradeToken);
                response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept);

                response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101
                response.ComputeCoreHeaders();
                ulong hresult = SendWebSocketHeaders(response);
                if (hresult != 0)
                {
                    throw new WebSocketException((int)hresult,
                                                 SR.GetString(SR.net_WebSockets_NativeSendResponseHeaders,
                                                              WebSocketHelpers.MethodNames.AcceptWebSocketAsync,
                                                              hresult));
                }

                if (Logging.On)
                {
                    Logging.PrintInfo(Logging.WebSockets, string.Format("{0} = {1}",
                                                                        HttpKnownHeaderNames.Origin, origin));
                    Logging.PrintInfo(Logging.WebSockets, string.Format("{0} = {1}",
                                                                        HttpKnownHeaderNames.SecWebSocketVersion, secWebSocketVersion));
                    Logging.PrintInfo(Logging.WebSockets, string.Format("{0} = {1}",
                                                                        HttpKnownHeaderNames.SecWebSocketKey, secWebSocketKey));
                    Logging.PrintInfo(Logging.WebSockets, string.Format("{0} = {1}",
                                                                        HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept));
                    Logging.PrintInfo(Logging.WebSockets, string.Format("Request  {0} = {1}",
                                                                        HttpKnownHeaderNames.SecWebSocketProtocol,
                                                                        request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol]));
                    Logging.PrintInfo(Logging.WebSockets, string.Format("Response {0} = {1}",
                                                                        HttpKnownHeaderNames.SecWebSocketProtocol, outgoingSecWebSocketProtocolString));
                }

                await response.OutputStream.FlushAsync().SuppressContextFlow();

                HttpResponseStream responseStream = response.OutputStream as HttpResponseStream;
                Contract.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream.");
                ((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode();
                HttpRequestStream requestStream = new HttpRequestStream(context);
                requestStream.SwitchToOpaqueMode();
                WebSocketHttpListenerDuplexStream webSocketStream =
                    new WebSocketHttpListenerDuplexStream(requestStream, responseStream, context);
                WebSocket webSocket = WebSocket.CreateServerWebSocket(webSocketStream,
                                                                      subProtocol,
                                                                      receiveBufferSize,
                                                                      keepAliveInterval,
                                                                      internalBuffer);

                webSocketContext = new HttpListenerWebSocketContext(
                    request.Url,
                    request.Headers,
                    request.Cookies,
                    context.User,
                    request.IsAuthenticated,
                    request.IsLocal,
                    request.IsSecureConnection,
                    origin,
                    secWebSocketProtocols.AsReadOnly(),
                    secWebSocketVersion,
                    secWebSocketKey,
                    webSocket);

                if (Logging.On)
                {
                    Logging.Associate(Logging.WebSockets, context, webSocketContext);
                    Logging.Associate(Logging.WebSockets, webSocketContext, webSocket);
                }
            }
            catch (Exception ex)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.WebSockets, context, "AcceptWebSocketAsync", ex);
                }
                throw;
            }
            finally
            {
                if (Logging.On)
                {
                    Logging.Exit(Logging.WebSockets, context, "AcceptWebSocketAsync", "");
                }
            }

            return(webSocketContext);
        }