internal static HttpResponse Parse (string[] headerParts)
    {
      var statusLine = headerParts[0].Split (new[] { ' ' }, 3);
      if (statusLine.Length != 3)
        throw new ArgumentException ("Invalid status line: " + headerParts[0]);

      var headers = new WebHeaderCollection ();
      for (int i = 1; i < headerParts.Length; i++)
        headers.InternalSet (headerParts[i], true);

      return new HttpResponse (
        statusLine[1], statusLine[2], new System.Version (statusLine[0].Substring (5)), headers);
    }
        internal void AddHeader(string header)
        {
            var colon = header.IndexOf (':');
              if (colon == -1) {
            _context.ErrorMessage = "Invalid header";
            return;
              }

              var name = header.Substring (0, colon).Trim ();
              var val = header.Substring (colon + 1).Trim ();
              _headers.InternalSet (name, val, false);

              var lower = name.ToLower (CultureInfo.InvariantCulture);
              if (lower == "accept") {
            _acceptTypes = new List<string> (val.SplitHeaderValue (',')).ToArray ();
            return;
              }

              if (lower == "accept-language") {
            _userLanguages = val.Split (',');
            return;
              }

              if (lower == "content-length") {
            long len;
            if (Int64.TryParse (val, out len) && len >= 0) {
              _contentLength = len;
              _contentLengthWasSet = true;
            }
            else {
              _context.ErrorMessage = "Invalid Content-Length header";
            }

            return;
              }

              if (lower == "content-type") {
            try {
              _contentEncoding = HttpUtility.GetEncoding (val);
            }
            catch {
              _context.ErrorMessage = "Invalid Content-Type header";
            }

            return;
              }

              if (lower == "referer")
            _referer = val.ToUri ();
        }
Beispiel #3
0
        internal static HttpResponse Parse(string[] headerParts)
        {
            char[]   separator = new char[] { ' ' };
            string[] strArray  = headerParts[0].Split(separator, 3);
            if (strArray.Length != 3)
            {
                throw new ArgumentException("Invalid status line: " + headerParts[0]);
            }
            WebHeaderCollection headers = new WebHeaderCollection();

            for (int i = 1; i < headerParts.Length; i++)
            {
                headers.InternalSet(headerParts[i], true);
            }
            return(new HttpResponse(strArray[1], strArray[2], new Version(strArray[0].Substring(5)), headers));
        }
Beispiel #4
0
        internal static HttpResponse Parse(string[] headerParts)
        {
            string[] array = headerParts[0].Split(new char[1] {
                ' '
            }, 3);
            if (array.Length != 3)
            {
                throw new ArgumentException("Invalid status line: " + headerParts[0]);
            }
            WebHeaderCollection webHeaderCollection = new WebHeaderCollection();

            for (int i = 1; i < headerParts.Length; i++)
            {
                webHeaderCollection.InternalSet(headerParts[i], response: true);
            }
            return(new HttpResponse(array[1], array[2], new Version(array[0].Substring(5)), webHeaderCollection));
        }
        internal static HttpRequest Parse(string[] headerParts)
        {
            string[] strArrays = headerParts[0].Split(new char[] { ' ' }, 3);
            if ((int)strArrays.Length != 3)
            {
                throw new ArgumentException(string.Concat("Invalid request line: ", headerParts[0]));
            }
            WebHeaderCollection webHeaderCollection = new WebHeaderCollection();

            for (int i = 1; i < (int)headerParts.Length; i++)
            {
                webHeaderCollection.InternalSet(headerParts[i], false);
            }
            HttpRequest httpRequest = new HttpRequest(strArrays[0], strArrays[1], new Version(strArrays[2].Substring(5)), webHeaderCollection);

            return(httpRequest);
        }
Beispiel #6
0
        private static HttpRequest Parse(string[] headerParts)
        {
            var requestLine = headerParts[0].Split(new[] { ' ' }, 3);

            if (requestLine.Length != 3)
            {
                throw new ArgumentException("Invalid request line: " + headerParts[0]);
            }

            var headers = new WebHeaderCollection();

            for (int i = 1; i < headerParts.Length; i++)
            {
                headers.InternalSet(headerParts[i], false);
            }

            return(new HttpRequest(requestLine[0], requestLine[1], new Version(requestLine[2].Substring(5)), headers));
        }
Beispiel #7
0
        internal WebHeaderCollection WriteHeadersTo(MemoryStream destination)
        {
            var headers = new WebHeaderCollection(HttpHeaderType.Response, true);

            if (_headers != null)
            {
                headers.Add(_headers);
            }

            if (_contentType != null)
            {
                var type = _contentType.IndexOf("charset=", StringComparison.Ordinal) == -1 &&
                           _contentEncoding != null
                   ? String.Format("{0}; charset={1}", _contentType, _contentEncoding.WebName)
                   : _contentType;

                headers.InternalSet("Content-Type", type, true);
            }

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

            var prov = CultureInfo.InvariantCulture;

            if (headers["Date"] == null)
            {
                headers.InternalSet("Date", DateTime.UtcNow.ToString("r", prov), true);
            }

            if (!_sendChunked)
            {
                headers.InternalSet("Content-Length", _contentLength.ToString(prov), true);
            }
            else
            {
                headers.InternalSet("Transfer-Encoding", "chunked", true);
            }

            /*
             * Apache forces closing the connection for these status codes:
             * - 400 Bad Request
             * - 408 Request Timeout
             * - 411 Length Required
             * - 413 Request Entity Too Large
             * - 414 Request-Uri Too Long
             * - 500 Internal Server Error
             * - 503 Service Unavailable
             */
            var closeConn = !_context.Request.KeepAlive ||
                            !_keepAlive ||
                            _statusCode == 400 ||
                            _statusCode == 408 ||
                            _statusCode == 411 ||
                            _statusCode == 413 ||
                            _statusCode == 414 ||
                            _statusCode == 500 ||
                            _statusCode == 503;

            var reuses = _context.Connection.Reuses;

            if (closeConn || reuses >= 100)
            {
                headers.InternalSet("Connection", "close", true);
            }
            else
            {
                headers.InternalSet(
                    "Keep-Alive", String.Format("timeout=15,max={0}", 100 - reuses), true);

                if (_context.Request.ProtocolVersion < 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(destination, enc, 256);

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

            // Assumes that the destination was at position 0.
            destination.Position = enc.GetPreamble().Length;

            return(headers);
        }
        internal void AddHeader(string headerField)
        {
            var start = headerField[0];

            if (start == ' ' || start == '\t')
            {
                _context.ErrorMessage = "Invalid header field";
                return;
            }

            var colon = headerField.IndexOf(':');

            if (colon < 1)
            {
                _context.ErrorMessage = "Invalid header field";
                return;
            }

            var name = headerField.Substring(0, colon).Trim();

            if (name.Length == 0 || !name.IsToken())
            {
                _context.ErrorMessage = "Invalid header name";
                return;
            }

            var val = colon < headerField.Length - 1
                ? headerField.Substring(colon + 1).Trim()
                : String.Empty;

            _headers.InternalSet(name, val, false);

            var lower = name.ToLower(CultureInfo.InvariantCulture);

            if (lower == "host")
            {
                if (_userHostName != null)
                {
                    _context.ErrorMessage = "Invalid Host header";
                    return;
                }

                if (val.Length == 0)
                {
                    _context.ErrorMessage = "Invalid Host header";
                    return;
                }

                _userHostName = val;
                return;
            }

            if (lower == "content-length")
            {
                if (_contentLength > -1)
                {
                    _context.ErrorMessage = "Invalid Content-Length header";
                    return;
                }

                long len;
                if (!Int64.TryParse(val, out len))
                {
                    _context.ErrorMessage = "Invalid Content-Length header";
                    return;
                }

                if (len < 0)
                {
                    _context.ErrorMessage = "Invalid Content-Length header";
                    return;
                }

                _contentLength = len;
                return;
            }
        }
Beispiel #9
0
        internal void SendHeaders(MemoryStream stream, bool closing)
        {
            if (_contentType != null)
            {
                var type = _contentType.IndexOf("charset=", StringComparison.Ordinal) == -1 &&
                           _contentEncoding != null
                   ? String.Format("{0}; charset={1}", _contentType, _contentEncoding.WebName)
                   : _contentType;

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

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

            var prov = CultureInfo.InvariantCulture;

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

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

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

            var ver = _context.Request.ProtocolVersion;

            if (!_contentLengthWasSet && !_chunked && ver > 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 closeConn = _statusCode == 400 ||
                            _statusCode == 408 ||
                            _statusCode == 411 ||
                            _statusCode == 413 ||
                            _statusCode == 414 ||
                            _statusCode == 500 ||
                            _statusCode == 503;

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

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

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

            var reuses = _context.Connection.Reuses;

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

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

                if (ver < 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;
        }