InternalSet() private method

private InternalSet ( string header, bool response ) : void
header string
response bool
return void
        internal void AddHeader(string header)
        {
            int num = header.IndexOf(':');

            if (num == -1)
            {
                _context.ErrorMessage = "Invalid header";
                return;
            }
            string text  = header.Substring(0, num).Trim();
            string text2 = header.Substring(num + 1).Trim();

            _headers.InternalSet(text, text2, response: false);
            switch (text.ToLower(CultureInfo.InvariantCulture))
            {
            case "accept":
                _acceptTypes = new List <string>(text2.SplitHeaderValue(',')).ToArray();
                break;

            case "accept-language":
                _userLanguages = text2.Split(',');
                break;

            case "content-length":
            {
                if (long.TryParse(text2, out var result) && result >= 0)
                {
                    _contentLength       = result;
                    _contentLengthWasSet = true;
                }
                else
                {
                    _context.ErrorMessage = "Invalid Content-Length header";
                }
                break;
            }

            case "content-type":
                try
                {
                    _contentEncoding = HttpUtility.GetEncoding(text2);
                }
                catch
                {
                    _context.ErrorMessage = "Invalid Content-Type header";
                }
                break;

            case "referer":
                _referer = text2.ToUri();
                break;
            }
        }
Esempio n. 2
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);
        }
Esempio n. 3
0
        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 SSHARP
                if (!Int64Ex.TryParse(val, out len))
#else
                if (!Int64.TryParse(val, out len))
#endif
                {
                    _context.ErrorMessage = "Invalid Content-Length header";
                    return;
                }

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

                _contentLength = len;
            }
        }
Esempio n. 4
0
        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();
            }
        }
Esempio n. 5
0
        internal void WriteHeadersTo(MemoryStream destination, 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 (!_contentLengthSet && closing)
                {
                    _contentLengthSet = true;
                    _contentLength    = 0;
                }

                if (_contentLengthSet)
                {
                    _headers.InternalSet("Content-Length", _contentLength.ToString(prov), true);
                }
                else if (_context.Request.ProtocolVersion > HttpVersion.Version10)
                {
                    _chunked = true;
                }
            }

            if (_chunked)
            {
                _headers.InternalSet("Transfer-Encoding", "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 ||
                            !_context.Request.KeepAlive ||
                            !_keepAlive;

            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.CodePage == 65001 ? 3 : enc.GetPreamble().Length;
        }
    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 Version (statusLine[0].Substring (5)), headers);
    }
        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;
        }
Esempio n. 8
0
    internal 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);
    }
Esempio n. 9
0
        internal void AddHeader(string headerField)
        {
            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 == "accept")
            {
                _acceptTypes = val.SplitHeaderValue(',').ToList().ToArray();
                return;
            }

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

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

                _contentLength    = len;
                _contentLengthSet = true;

                return;
            }

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

                return;
            }

            if (lower == "referer")
            {
                var referer = val.ToUri();
                if (referer == null)
                {
                    _context.ErrorMessage = "Invalid Referer header";
                    return;
                }

                _referer = referer;
                return;
            }
        }
    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;
    }