private void disposeStream()
        {
            if (_stream == null)
            {
                return;
            }

            _inputStream  = null;
            _outputStream = null;

            try {
                _stream.Dispose();
            }
            catch { }
            _stream = null;
        }
示例#2
0
        internal void Close(bool force)
        {
            if (this._socket == null)
            {
                return;
            }
            if (this._outputStream != null)
            {
                this._outputStream.Close();
                this._outputStream = null;
            }
            HttpListenerRequest  request  = this._context.Request;
            HttpListenerResponse response = this._context.Response;

            force |= !request.KeepAlive;
            if (!force)
            {
                force = (response.Headers["Connection"] == "close");
            }
            if (!force && request.FlushInput() && (!this._chunked || (this._chunked && !response.ForceCloseChunked)))
            {
                this._reuses++;
                this.unbind();
                this.init();
                this.BeginReadRequest();
                return;
            }
            Socket socket = this._socket;

            this._socket = null;
            try
            {
                socket.Shutdown(SocketShutdown.Both);
            }
            catch
            {
            }
            finally
            {
                if (socket != null)
                {
                    socket.Close();
                }
            }
            this.unbind();
            this.removeConnection();
        }
示例#3
0
 public ResponseStream GetResponseStream()
 {
     //Discarded unreachable code: IL_0089
     if (_outputStream != null || _socket == null)
     {
         return(_outputStream);
     }
     lock (_sync)
     {
         if (_socket == null)
         {
             return(_outputStream);
         }
         bool ignoreErrors = _context.Listener?.IgnoreWriteExceptions ?? true;
         _outputStream = new ResponseStream(_stream, _context.Response, ignoreErrors);
         return(_outputStream);
     }
 }
 protected internal HttpListenerResponse(HttpListenerResponse response)
 {
     _closeConnection   = response._closeConnection;
     _contentEncoding   = response._contentEncoding;
     _contentLength     = response._contentLength;
     _contentType       = response._contentType;
     _context           = response._context;
     _cookies           = response._cookies;
     _disposed          = response._disposed;
     _headers           = response._headers;
     _headersSent       = response._headersSent;
     _keepAlive         = response._keepAlive;
     _location          = response._location;
     _outputStream      = response._outputStream;
     _sendChunked       = response._sendChunked;
     _statusCode        = response._statusCode;
     _statusDescription = response._statusDescription;
     _version           = response._version;
 }
示例#5
0
        public ResponseStream GetResponseStream()
        {
            lock (_sync) {
                if (_socket == null)
                {
                    return(null);
                }

                if (_outputStream != null)
                {
                    return(_outputStream);
                }

                var lsnr   = _context.Listener;
                var ignore = lsnr != null ? lsnr.IgnoreWriteExceptions : true;
                _outputStream = new ResponseStream(_stream, _context.Response, ignore);

                return(_outputStream);
            }
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (this._disposed)
            {
                throw new ObjectDisposedException(base.GetType().ToString());
            }
            MemoryStream headers     = this.getHeaders(false);
            bool         sendChunked = this._response.SendChunked;

            if (headers != null)
            {
                long position = headers.Position;
                headers.Position = headers.Length;
                if (sendChunked)
                {
                    byte[] chunkSizeBytes = ResponseStream.getChunkSizeBytes(count, false);
                    headers.Write(chunkSizeBytes, 0, chunkSizeBytes.Length);
                }
                int num = Math.Min(count, 16384 - (int)headers.Position + (int)position);
                headers.Write(buffer, offset, num);
                count  -= num;
                offset += num;
                this.InternalWrite(headers.GetBuffer(), (int)position, (int)(headers.Length - position));
                headers.SetLength(0L);
                headers.Capacity = 0;
            }
            else if (sendChunked)
            {
                byte[] chunkSizeBytes = ResponseStream.getChunkSizeBytes(count, false);
                this.InternalWrite(chunkSizeBytes, 0, chunkSizeBytes.Length);
            }
            if (count > 0)
            {
                this.InternalWrite(buffer, offset, count);
            }
            if (sendChunked)
            {
                this.InternalWrite(ResponseStream._crlf, 0, 2);
            }
        }
        public ResponseStream GetResponseStream()
        {
            // TODO: Can we get this stream before reading the input?

            lock (_sync) {
                if (_socket == null)
                {
                    return(null);
                }

                if (_outputStream != null)
                {
                    return(_outputStream);
                }

                var lsnr   = _context.Listener;
                var ignore = lsnr != null ? lsnr.IgnoreWriteExceptions : true;
                _outputStream = new ResponseStream(_stream, _context.Response, ignore);

                return(_outputStream);
            }
        }
 internal void Close(bool force)
 {
     if (!this._disposed)
     {
         this._disposed = true;
         if ((force ? true : !this.flush(true)))
         {
             if (this._sendChunked)
             {
                 byte[] chunkSizeBytes = ResponseStream.getChunkSizeBytes(0, true);
                 this._write(chunkSizeBytes, 0, (int)chunkSizeBytes.Length);
             }
             this._body.Dispose();
             this._body = null;
             this._response.Abort();
         }
         else
         {
             this._response.Close();
         }
         this._response = null;
         this._stream   = null;
     }
 }
示例#9
0
        internal void SendHeaders(bool closing, MemoryStream ms)
        {
            Encoding encoding = content_encoding;

            if (encoding == null)
            {
                encoding = Encoding.Default;
            }

            if (content_type != null)
            {
                if (content_encoding != null && content_type.IndexOf("charset=", StringComparison.Ordinal) == -1)
                {
                    string enc_name = content_encoding.WebName;
                    headers.SetInternal("Content-Type", content_type + "; charset=" + enc_name);
                }
                else
                {
                    headers.SetInternal("Content-Type", content_type);
                }
            }

            if (headers ["Server"] == null)
            {
                headers.SetInternal("Server", "Mono-HTTPAPI/1.0");
            }

            CultureInfo inv = CultureInfo.InvariantCulture;

            if (headers ["Date"] == null)
            {
                headers.SetInternal("Date", DateTime.UtcNow.ToString("r", inv));
            }

            if (!chunked)
            {
                if (!cl_set && closing)
                {
                    cl_set         = true;
                    content_length = 0;
                }

                if (cl_set)
                {
                    headers.SetInternal("Content-Length", content_length.ToString(inv));
                }
            }

            Version v = context.Request.ProtocolVersion;

            if (!cl_set && !chunked && v >= HttpVersion.Version11)
            {
                chunked = true;
            }

            /* Apache forces closing the connection for these status codes:
             *	HttpStatusCode.BadRequest               400
             *	HttpStatusCode.RequestTimeout           408
             *	HttpStatusCode.LengthRequired           411
             *	HttpStatusCode.RequestEntityTooLarge    413
             *	HttpStatusCode.RequestUriTooLong        414
             *	HttpStatusCode.InternalServerError      500
             *	HttpStatusCode.ServiceUnavailable       503
             */
            bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
                               status_code == 413 || status_code == 414 || status_code == 500 ||
                               status_code == 503);

            if (conn_close == false)
            {
                conn_close = !context.Request.KeepAlive;
            }

            // They sent both KeepAlive: true and Connection: close!?
            if (!keep_alive || conn_close)
            {
                headers.SetInternal("Connection", "close");
                conn_close = true;
            }

            if (chunked)
            {
                headers.SetInternal("Transfer-Encoding", "chunked");
            }

            int reuses = context.Connection.Reuses;

            if (reuses >= 100)
            {
                force_close_chunked = true;
                if (!conn_close)
                {
                    headers.SetInternal("Connection", "close");
                    conn_close = true;
                }
            }

            if (!conn_close)
            {
                headers.SetInternal("Keep-Alive", String.Format("timeout=15,max={0}", 100 - reuses));
                if (context.Request.ProtocolVersion <= HttpVersion.Version10)
                {
                    headers.SetInternal("Connection", "keep-alive");
                }
            }

            if (location != null)
            {
                headers.SetInternal("Location", location);
            }

            if (cookies != null)
            {
                foreach (Cookie cookie in cookies)
                {
                    headers.SetInternal("Set-Cookie", cookie.ToClientString());
                }
            }

            StreamWriter writer = new StreamWriter(ms, encoding, 256);

            writer.Write("HTTP/{0} {1} {2}\r\n", version, status_code, status_description);
            string headers_str = headers.ToStringMultiValue();

            writer.Write(headers_str);
            writer.Flush();
            int preamble = (encoding.CodePage == 65001) ? 3 : encoding.GetPreamble().Length;

            if (output_stream == null)
            {
                output_stream = context.Connection.GetResponseStream();
            }

            /* Assumes that the ms was at position 0 */
            ms.Position = preamble;
            HeadersSent = true;
        }
示例#10
0
        internal void Close(bool force_close)
        {
            if (sock != null)
            {
                Stream st = GetResponseStream();
                st.Close();
                o_stream = null;
            }

            if (sock != null)
            {
                force_close |= !context.Request.KeepAlive;
                if (!force_close)
                {
                    force_close = (context.Response.Headers["connection"] == "close");
                }

                /*
                 * if (!force_close) {
                 * //					bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
                 * //							status_code == 413 || status_code == 414 || status_code == 500 ||
                 * //							status_code == 503);
                 *
                 *  force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
                 * }
                 */

                if (!force_close && context.Request.FlushInput())
                {
                    if (chunked && context.Response.ForceCloseChunked == false)
                    {
                        // Don't close. Keep working.
                        reuses++;
                        Unbind();
                        Init();
                        BeginReadRequest();
                        return;
                    }

                    reuses++;
                    Unbind();
                    Init();
                    BeginReadRequest();
                    return;
                }

                Socket s = sock;
                sock = null;
                try
                {
                    if (s != null)
                    {
                        s.Shutdown(SocketShutdown.Both);
                    }
                }
                catch
                {
                }
                finally
                {
                    if (s != null)
                    {
                        s.Close();
                    }
                }
                Unbind();
                RemoveConnection();
                return;
            }
        }
示例#11
0
        internal void SendHeaders(bool closing, MemoryStream stream)
        {
            if (_contentType != null)
            {
                var contentType = _contentEncoding != null &&
                                  _contentType.IndexOf("charset=", StringComparison.Ordinal) == -1
                          ? _contentType + "; charset=" + _contentEncoding.WebName
                          : _contentType;

                _headers.SetInternally("Content-Type", contentType, true);
            }

            if (_headers ["Server"] == null)
            {
                _headers.SetInternally("Server", "websocket-sharp/1.0", true);
            }

            var provider = CultureInfo.InvariantCulture;

            if (_headers ["Date"] == null)
            {
                _headers.SetInternally("Date", DateTime.UtcNow.ToString("r", provider), true);
            }

            if (!_chunked)
            {
                if (!_contentLengthSet && closing)
                {
                    _contentLengthSet = true;
                    _contentLength    = 0;
                }

                if (_contentLengthSet)
                {
                    _headers.SetInternally("Content-Length", _contentLength.ToString(provider), true);
                }
            }

            var version = _context.Request.ProtocolVersion;

            if (!_contentLengthSet && !_chunked && version >= HttpVersion.Version11)
            {
                _chunked = true;
            }

            /* Apache forces closing the connection for these status codes:
             * - HttpStatusCode.BadRequest            400
             * - HttpStatusCode.RequestTimeout        408
             * - HttpStatusCode.LengthRequired        411
             * - HttpStatusCode.RequestEntityTooLarge 413
             * - HttpStatusCode.RequestUriTooLong     414
             * - HttpStatusCode.InternalServerError   500
             * - HttpStatusCode.ServiceUnavailable    503
             */
            var connClose = _statusCode == 400 ||
                            _statusCode == 408 ||
                            _statusCode == 411 ||
                            _statusCode == 413 ||
                            _statusCode == 414 ||
                            _statusCode == 500 ||
                            _statusCode == 503;

            if (!connClose)
            {
                connClose = !_context.Request.KeepAlive;
            }

            // They sent both KeepAlive: true and Connection: close!?
            if (!_keepAlive || connClose)
            {
                _headers.SetInternally("Connection", "close", true);
                connClose = true;
            }

            if (_chunked)
            {
                _headers.SetInternally("Transfer-Encoding", "chunked", true);
            }

            int reuses = _context.Connection.Reuses;

            if (reuses >= 100)
            {
                _forceCloseChunked = true;
                if (!connClose)
                {
                    _headers.SetInternally("Connection", "close", true);
                    connClose = true;
                }
            }

            if (!connClose)
            {
                _headers.SetInternally(
                    "Keep-Alive", String.Format("timeout=15,max={0}", 100 - reuses), true);

                if (_context.Request.ProtocolVersion <= HttpVersion.Version10)
                {
                    _headers.SetInternally("Connection", "keep-alive", true);
                }
            }

            if (_location != null)
            {
                _headers.SetInternally("Location", _location, true);
            }

            if (_cookies != null)
            {
                foreach (Cookie cookie in _cookies)
                {
                    _headers.SetInternally("Set-Cookie", cookie.ToResponseString(), true);
                }
            }

            var encoding = _contentEncoding ?? Encoding.Default;
            var writer   = new StreamWriter(stream, encoding, 256);

            writer.Write("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);

            var headers = _headers.ToStringMultiValue(true);

            writer.Write(headers);
            writer.Flush();

            var preamble = encoding.CodePage == 65001 ? 3 : encoding.GetPreamble().Length;

            if (_outputStream == null)
            {
                _outputStream = _context.Connection.GetResponseStream();
            }

            // Assumes that the stream was at position 0.
            stream.Position = preamble;
            _headersSent    = true;
        }
        internal void SendHeaders(MemoryStream stream, bool closing)
        {
            if (_contentType != null)
            {
                string value = ((_contentType.IndexOf("charset=", StringComparison.Ordinal) != -1 || _contentEncoding == null) ? _contentType : $"{_contentType}; charset={_contentEncoding.WebName}");
                _headers.InternalSet("Content-Type", value, response: true);
            }
            if (_headers["Server"] == null)
            {
                _headers.InternalSet("Server", "websocket-sharp/1.0", response: true);
            }
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;

            if (_headers["Date"] == null)
            {
                _headers.InternalSet("Date", DateTime.UtcNow.ToString("r", invariantCulture), response: true);
            }
            if (!_chunked)
            {
                if (!_contentLengthWasSet && closing)
                {
                    _contentLengthWasSet = true;
                    _contentLength       = 0L;
                }
                if (_contentLengthWasSet)
                {
                    _headers.InternalSet("Content-Length", _contentLength.ToString(invariantCulture), response: true);
                }
            }
            Version protocolVersion = _context.Request.ProtocolVersion;

            if (!_contentLengthWasSet && !_chunked && protocolVersion > HttpVersion.Version10)
            {
                _chunked = true;
            }
            bool flag = _statusCode == 400 || _statusCode == 408 || _statusCode == 411 || _statusCode == 413 || _statusCode == 414 || _statusCode == 500 || _statusCode == 503;

            if (!flag)
            {
                flag = !_context.Request.KeepAlive;
            }
            if (!_keepAlive || flag)
            {
                _headers.InternalSet("Connection", "close", response: true);
                flag = true;
            }
            if (_chunked)
            {
                _headers.InternalSet("Transfer-Encoding", "chunked", response: true);
            }
            int reuses = _context.Connection.Reuses;

            if (reuses >= 100)
            {
                _forceCloseChunked = true;
                if (!flag)
                {
                    _headers.InternalSet("Connection", "close", response: true);
                    flag = true;
                }
            }
            if (!flag)
            {
                _headers.InternalSet("Keep-Alive", $"timeout=15,max={100 - reuses}", response: true);
                if (protocolVersion < HttpVersion.Version11)
                {
                    _headers.InternalSet("Connection", "keep-alive", response: true);
                }
            }
            if (_location != null)
            {
                _headers.InternalSet("Location", _location, response: true);
            }
            if (_cookies != null)
            {
                IEnumerator enumerator = _cookies.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        Cookie cookie = (Cookie)enumerator.Current;
                        _headers.InternalSet("Set-Cookie", cookie.ToResponseString(), response: true);
                    }
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = enumerator as IDisposable) != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            Encoding     encoding     = _contentEncoding ?? Encoding.Default;
            StreamWriter streamWriter = new StreamWriter(stream, encoding, 256);

            streamWriter.Write("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);
            streamWriter.Write(_headers.ToStringMultiValue(response: true));
            streamWriter.Flush();
            stream.Position = ((encoding.CodePage != 65001) ? encoding.GetPreamble().Length : 3);
            if (_outputStream == null)
            {
                _outputStream = _context.Connection.GetResponseStream();
            }
            _headersWereSent = true;
        }
示例#13
0
        internal void FinishInitialization()
        {
            string host = UserHostName;

            if (version > HttpVersion.Version10 && (host == null || host.Length == 0))
            {
                context.ErrorMessage = "Invalid host name";
                return;
            }

            string path;
            Uri    raw_uri = null;

            if (raw_url.MaybeUri() && Uri.TryCreate(raw_url, UriKind.Absolute, out raw_uri))
            {
                path = raw_uri.PathAndQuery;
            }
            else
            {
                path = HttpUtility.UrlDecode(raw_url);
            }

            if ((host == null || host.Length == 0))
            {
                host = UserHostAddress;
            }

            if (raw_uri != null)
            {
                host = raw_uri.Host;
            }

            int colon = host.IndexOf(':');

            if (colon >= 0)
            {
                host = host.Substring(0, colon);
            }

            string base_uri = String.Format("{0}://{1}:{2}",
                                            (IsSecureConnection) ? "https" : "http",
                                            host,
                                            LocalEndPoint.Port);

            if (!Uri.TryCreate(base_uri + path, UriKind.Absolute, out url))
            {
                context.ErrorMessage = "Invalid url: " + base_uri + path;
                return;
            }

            CreateQueryString(url.Query);

            if (version >= HttpVersion.Version11)
            {
                string t_encoding = Headers ["Transfer-Encoding"];
                is_chunked = (t_encoding != null && String.Compare(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
                // 'identity' is not valid!
                if (t_encoding != null && !is_chunked)
                {
                    context.Connection.SendError(null, 501);
                    return;
                }
            }

            if (!is_chunked && !cl_set)
            {
                if (String.Compare(method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
                    String.Compare(method, "PUT", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    context.Connection.SendError(null, 411);
                    return;
                }
            }

            if (String.Compare(Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
            {
                ResponseStream output = context.Connection.GetResponseStream();
                output.InternalWrite(_100continue, 0, _100continue.Length);
            }
        }
        internal void SendHeaders(MemoryStream stream, bool closing)
        {
            if (_contentType != null) {
            var contentType = _contentEncoding != null &&
                          _contentType.IndexOf ("charset=", StringComparison.Ordinal) == -1
                          ? String.Format (
                              "{0}; charset={1}", _contentType, _contentEncoding.WebName)
                          : _contentType;

            _headers.InternalSet ("Content-Type", contentType, true);
              }

              if (_headers["Server"] == null)
            _headers.InternalSet ("Server", "websocket-sharp/1.0", true);

              var provider = CultureInfo.InvariantCulture;
              if (_headers["Date"] == null)
            _headers.InternalSet ("Date", DateTime.UtcNow.ToString ("r", provider), true);

              if (!_chunked) {
            if (!_contentLengthWasSet && closing) {
              _contentLengthWasSet = true;
              _contentLength = 0;
            }

            if (_contentLengthWasSet)
              _headers.InternalSet ("Content-Length", _contentLength.ToString (provider), true);
              }

              var reqVer = _context.Request.ProtocolVersion;
              if (!_contentLengthWasSet && !_chunked && reqVer > HttpVersion.Version10)
            _chunked = true;

              /*
               * Apache forces closing the connection for these status codes:
               * - HttpStatusCode.BadRequest            400
               * - HttpStatusCode.RequestTimeout        408
               * - HttpStatusCode.LengthRequired        411
               * - HttpStatusCode.RequestEntityTooLarge 413
               * - HttpStatusCode.RequestUriTooLong     414
               * - HttpStatusCode.InternalServerError   500
               * - HttpStatusCode.ServiceUnavailable    503
               */
              var connClose = _statusCode == 400 ||
                      _statusCode == 408 ||
                      _statusCode == 411 ||
                      _statusCode == 413 ||
                      _statusCode == 414 ||
                      _statusCode == 500 ||
                      _statusCode == 503;

              if (!connClose)
            connClose = !_context.Request.KeepAlive;

              // They sent both KeepAlive: true and Connection: close!?
              if (!_keepAlive || connClose) {
            _headers.InternalSet ("Connection", "close", true);
            connClose = true;
              }

              if (_chunked)
            _headers.InternalSet ("Transfer-Encoding", "chunked", true);

              var reuses = _context.Connection.Reuses;
              if (reuses >= 100) {
            _forceCloseChunked = true;
            if (!connClose) {
              _headers.InternalSet ("Connection", "close", true);
              connClose = true;
            }
              }

              if (!connClose) {
            _headers.InternalSet (
              "Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true);

            if (reqVer < HttpVersion.Version11)
              _headers.InternalSet ("Connection", "keep-alive", true);
              }

              if (_location != null)
            _headers.InternalSet ("Location", _location, true);

              if (_cookies != null)
            foreach (Cookie cookie in _cookies)
              _headers.InternalSet ("Set-Cookie", cookie.ToResponseString (), true);

              var enc = _contentEncoding ?? Encoding.Default;
              var writer = new StreamWriter (stream, enc, 256);
              writer.Write ("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);
              writer.Write (_headers.ToStringMultiValue (true));
              writer.Flush ();

              // Assumes that the stream was at position 0.
              stream.Position = enc.CodePage == 65001 ? 3 : enc.GetPreamble ().Length;

              if (_outputStream == null)
            _outputStream = _context.Connection.GetResponseStream ();

              _headersWereSent = true;
        }
示例#15
0
        internal void SendHeaders(bool closing, MemoryStream stream)
        {
            if (this._contentType != null)
            {
                if (this._contentEncoding != null && this._contentType.IndexOf("charset=", StringComparison.Ordinal) == -1)
                {
                    string webName = this._contentEncoding.WebName;
                    this._headers.SetInternal("Content-Type", this._contentType + "; charset=" + webName, true);
                }
                else
                {
                    this._headers.SetInternal("Content-Type", this._contentType, true);
                }
            }
            if (this._headers["Server"] == null)
            {
                this._headers.SetInternal("Server", "websocket-sharp/1.0", true);
            }
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;

            if (this._headers["Date"] == null)
            {
                this._headers.SetInternal("Date", DateTime.UtcNow.ToString("r", invariantCulture), true);
            }
            if (!this._chunked)
            {
                if (!this._contentLengthSet && closing)
                {
                    this._contentLengthSet = true;
                    this._contentLength    = 0L;
                }
                if (this._contentLengthSet)
                {
                    this._headers.SetInternal("Content-Length", this._contentLength.ToString(invariantCulture), true);
                }
            }
            Version protocolVersion = this._context.Request.ProtocolVersion;

            if (!this._contentLengthSet && !this._chunked && protocolVersion >= HttpVersion.Version11)
            {
                this._chunked = true;
            }
            bool flag = this._statusCode == 400 || this._statusCode == 408 || this._statusCode == 411 || this._statusCode == 413 || this._statusCode == 414 || this._statusCode == 500 || this._statusCode == 503;

            if (!flag)
            {
                flag = !this._context.Request.KeepAlive;
            }
            if (!this._keepAlive || flag)
            {
                this._headers.SetInternal("Connection", "close", true);
                flag = true;
            }
            if (this._chunked)
            {
                this._headers.SetInternal("Transfer-Encoding", "chunked", true);
            }
            int reuses = this._context.Connection.Reuses;

            if (reuses >= 100)
            {
                this._forceCloseChunked = true;
                if (!flag)
                {
                    this._headers.SetInternal("Connection", "close", true);
                    flag = true;
                }
            }
            if (!flag)
            {
                this._headers.SetInternal("Keep-Alive", string.Format("timeout=15,max={0}", 100 - reuses), true);
                if (this._context.Request.ProtocolVersion <= HttpVersion.Version10)
                {
                    this._headers.SetInternal("Connection", "keep-alive", true);
                }
            }
            if (this._location != null)
            {
                this._headers.SetInternal("Location", this._location, true);
            }
            if (this._cookies != null)
            {
                IEnumerator enumerator = this._cookies.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        object obj    = enumerator.Current;
                        Cookie cookie = (Cookie)obj;
                        this._headers.SetInternal("Set-Cookie", cookie.ToResponseString(), true);
                    }
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = (enumerator as IDisposable)) != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            Encoding     encoding     = this._contentEncoding ?? Encoding.Default;
            StreamWriter streamWriter = new StreamWriter(stream, encoding, 256);

            streamWriter.Write("HTTP/{0} {1} {2}\r\n", this._version, this._statusCode, this._statusDescription);
            string value = this._headers.ToStringMultiValue(true);

            streamWriter.Write(value);
            streamWriter.Flush();
            int num = (encoding.CodePage != 65001) ? encoding.GetPreamble().Length : 3;

            if (this._outputStream == null)
            {
                this._outputStream = this._context.Connection.GetResponseStream();
            }
            stream.Position  = (long)num;
            this.HeadersSent = true;
        }
示例#16
0
        internal void FinishInitialization()
        {
            string text = this._headers["Host"];
            bool   flag = text == null || text.Length == 0;

            if (this._version > HttpVersion.Version10 && flag)
            {
                this._context.ErrorMessage = "Invalid Host header";
                return;
            }
            if (flag)
            {
                text = this.UserHostAddress;
            }
            Uri    uri = this._rawUrl.ToUri();
            string text2;

            if (uri != null && uri.IsAbsoluteUri)
            {
                text  = uri.Host;
                text2 = uri.PathAndQuery;
            }
            else
            {
                text2 = HttpUtility.UrlDecode(this._rawUrl);
            }
            int num = text.IndexOf(':');

            if (num != -1)
            {
                text = text.Substring(0, num);
            }
            string text3 = (!this.IsWebSocketRequest) ? "http" : "ws";
            string text4 = string.Format("{0}://{1}:{2}{3}", new object[]
            {
                (!this.IsSecureConnection) ? text3 : (text3 + "s"),
                text,
                this.LocalEndPoint.Port,
                text2
            });

            if (!Uri.TryCreate(text4, UriKind.Absolute, out this._url))
            {
                this._context.ErrorMessage = "Invalid request url: " + text4;
                return;
            }
            this.createQueryString(this._url.Query);
            string text5 = this.Headers["Transfer-Encoding"];

            if (this._version >= HttpVersion.Version11 && text5 != null && text5.Length > 0)
            {
                this._chunked = (text5.ToLower() == "chunked");
                if (!this._chunked)
                {
                    this._context.ErrorMessage = string.Empty;
                    this._context.ErrorStatus  = 501;
                    return;
                }
            }
            if (!this._chunked && !this._contentLengthWasSet)
            {
                string a = this._method.ToLower();
                if (a == "post" || a == "put")
                {
                    this._context.ErrorMessage = string.Empty;
                    this._context.ErrorStatus  = 411;
                    return;
                }
            }
            string text6 = this.Headers["Expect"];

            if (text6 != null && text6.Length > 0 && text6.ToLower() == "100-continue")
            {
                ResponseStream responseStream = this._context.Connection.GetResponseStream();
                responseStream.InternalWrite(HttpListenerRequest._100continue, 0, HttpListenerRequest._100continue.Length);
            }
        }