Get() static private method

static private Get ( HttpStatusCode code ) : string
code HttpStatusCode
return string
Esempio n. 1
0
        public void SendError(string msg, int status)
        {
            try
            {
                HttpListenerResponse response = _context.Response;
                response.StatusCode  = status;
                response.ContentType = "text/html";
                string description = HttpStatusDescription.Get(status);
                string str;
                if (msg != null)
                {
                    str = string.Format("<h1>{0} ({1})</h1>", description, msg);
                }
                else
                {
                    str = string.Format("<h1>{0}</h1>", description);
                }

                byte[] error = _context.Response.ContentEncoding.GetBytes(str);
                response.Close(error, false);
            }
            catch
            {
                // response was already closed
            }
        }
Esempio n. 2
0
        internal HttpWebResponse(Uri uri, string method, WebResponseStream stream, CookieContainer container)
        {
            this.uri    = uri;
            this.method = method;
            this.stream = stream;

            webHeaders        = stream.Headers ?? new WebHeaderCollection();
            version           = stream.Version;
            statusCode        = stream.StatusCode;
            statusDescription = stream.StatusDescription ?? HttpStatusDescription.Get(statusCode);
            contentLength     = -1;

            try {
                string cl = webHeaders ["Content-Length"];
                if (String.IsNullOrEmpty(cl) || !Int64.TryParse(cl, out contentLength))
                {
                    contentLength = -1;
                }
            } catch (Exception) {
                contentLength = -1;
            }

            if (container != null)
            {
                this.cookie_container = container;
                FillCookies();
            }
        }
        internal void SetRequestLine(string req)
        {
            string[] parts = req.Split(s_separators, 3);
            if (parts.Length != 3)
            {
                _context.ErrorMessage = "Invalid request line (parts).";
                return;
            }

            _method = parts[0];
            foreach (char c in _method)
            {
                int ic = (int)c;

                if ((ic >= 'A' && ic <= 'Z') ||
                    (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
                     c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
                     c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
                     c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
                {
                    continue;
                }

                _context.ErrorMessage = "(Invalid verb)";
                return;
            }

            _rawUrl = parts[1];
            if (parts[2].Length != 8 || !parts[2].StartsWith("HTTP/"))
            {
                _context.ErrorMessage = "Invalid request line (version).";
                return;
            }

            try
            {
                _version = new Version(parts[2].Substring(5));
            }
            catch
            {
                _context.ErrorMessage = "Invalid request line (version).";
                return;
            }

            if (_version.Major < 1)
            {
                _context.ErrorMessage = "Invalid request line (version).";
                return;
            }
            if (_version.Major > 1)
            {
                _context.ErrorStatus  = (int)HttpStatusCode.HttpVersionNotSupported;
                _context.ErrorMessage = HttpStatusDescription.Get(HttpStatusCode.HttpVersionNotSupported);
                return;
            }
        }
Esempio n. 4
0
        // Constructors

        internal HttpWebResponse(Uri uri, string method, HttpStatusCode status, WebHeaderCollection headers)
        {
            this.uri               = uri;
            this.method            = method;
            this.statusCode        = status;
            this.statusDescription = HttpStatusDescription.Get(status);
            this.webHeaders        = headers;
            version       = HttpVersion.Version10;
            contentLength = -1;
        }
 public void Redirect(string url)
 {
     if (NetEventSource.IsEnabled)
     {
         NetEventSource.Info(this, $"url={url}");
     }
     Headers[HttpResponseHeader.Location] = url;
     StatusCode        = (int)HttpStatusCode.Redirect;
     StatusDescription = HttpStatusDescription.Get(StatusCode);
 }
Esempio n. 6
0
 public /* override */ void Redirect(string url)
 {
     if (Logging.On)
     {
         Logging.PrintInfo(Logging.HttpListener, this, "Redirect", " url=" + url);
     }
     Headers.SetInternal(HttpResponseHeader.Location, url);
     StatusCode        = (int)HttpStatusCode.Redirect;
     StatusDescription = HttpStatusDescription.Get(StatusCode);
 }
        internal void AddHeader(string header)
        {
            int colon = header.IndexOf(':');

            if (colon == -1 || colon == 0)
            {
                _context.ErrorMessage = HttpStatusDescription.Get(400);
                _context.ErrorStatus  = 400;
                return;
            }

            string name = header.Substring(0, colon).Trim();
            string val  = header.Substring(colon + 1).Trim();

            if (name.Equals("content-length", StringComparison.OrdinalIgnoreCase))
            {
                // To match Windows behavior:
                // Content lengths >= 0 and <= long.MaxValue are accepted as is.
                // Content lengths > long.MaxValue and <= ulong.MaxValue are treated as 0.
                // Content lengths < 0 cause the requests to fail.
                // Other input is a failure, too.
                long parsedContentLength =
                    ulong.TryParse(val, out ulong parsedUlongContentLength) ? (parsedUlongContentLength <= long.MaxValue ? (long)parsedUlongContentLength : 0) :
                    long.Parse(val);
                if (parsedContentLength < 0 || (_clSet && parsedContentLength != _contentLength))
                {
                    _context.ErrorMessage = "Invalid Content-Length.";
                }
                else
                {
                    _contentLength = parsedContentLength;
                    _clSet         = true;
                }
            }
            else if (name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase))
            {
                if (Headers[HttpKnownHeaderNames.TransferEncoding] != null)
                {
                    _context.ErrorStatus  = (int)HttpStatusCode.NotImplemented;
                    _context.ErrorMessage = HttpStatusDescription.Get(HttpStatusCode.NotImplemented);
                }
            }

            if (_context.ErrorMessage == null)
            {
                _headers.Set(name, val);
            }
        }
Esempio n. 8
0
        public void SendError(string?msg, int status)
        {
            try
            {
                HttpListenerResponse response = _context.Response;
                response.StatusCode  = status;
                response.ContentType = "text/html";
                string?description = HttpStatusDescription.Get(status);
                string str         = msg != null ?
                                     $"<h1>{description} ({msg})</h1>" :
                                     $"<h1>{description}</h1>";

                byte[] error = Encoding.Default.GetBytes(str);
                response.Close(error, false);
            }
            catch
            {
                // response was already closed
            }
        }
        internal HttpWebResponse(Uri uri, string method, WebResponseStream stream, CookieContainer container)
        {
            this.uri    = uri;
            this.method = method;
            this.stream = stream;

            webHeaders        = stream.Headers ?? new WebHeaderCollection();
            version           = stream.Version;
            statusCode        = stream.StatusCode;
            statusDescription = stream.StatusDescription ?? HttpStatusDescription.Get(statusCode);
            contentLength     = -1;

            try {
                string cl = webHeaders ["Content-Length"];
                if (String.IsNullOrEmpty(cl) || !Int64.TryParse(cl, out contentLength))
                {
                    contentLength = -1;
                }
            } catch (Exception) {
                contentLength = -1;
            }

            if (container != null)
            {
                this.cookie_container = container;
                FillCookies();
            }

            string content_encoding = webHeaders ["Content-Encoding"];

            if (content_encoding == "gzip" && (stream.Request.AutomaticDecompression & DecompressionMethods.GZip) != 0)
            {
                this.stream = new GZipStream(stream, CompressionMode.Decompress);
                webHeaders.Remove(HttpRequestHeader.ContentEncoding);
            }
            else if (content_encoding == "deflate" && (stream.Request.AutomaticDecompression & DecompressionMethods.Deflate) != 0)
            {
                this.stream = new DeflateStream(stream, CompressionMode.Decompress);
                webHeaders.Remove(HttpRequestHeader.ContentEncoding);
            }
        }
Esempio n. 10
0
        internal void AddHeader(string header)
        {
            int colon = header.IndexOf(':');

            if (colon == -1 || colon == 0)
            {
                _context.ErrorMessage = HttpStatusDescription.Get(400);
                _context.ErrorStatus  = 400;
                return;
            }

            string name  = header.Substring(0, colon).Trim();
            string val   = header.Substring(colon + 1).Trim();
            string lower = name.ToLower(CultureInfo.InvariantCulture);

            _headers.Set(name, val);
            switch (lower)
            {
            case "content-length":
                try
                {
                    _contentLength = long.Parse(val.Trim());
                    if (_contentLength < 0)
                    {
                        _context.ErrorMessage = "Invalid Content-Length.";
                    }
                    _clSet = true;
                }
                catch
                {
                    _context.ErrorMessage = "Invalid Content-Length.";
                }

                break;
            }
        }
Esempio n. 11
0
        // true -> done processing
        // false -> need more input
        private bool ProcessInput(MemoryStream ms)
        {
            byte[] buffer = ms.GetBuffer();
            int    len    = (int)ms.Length;
            int    used   = 0;
            string?line;

            while (true)
            {
                if (_context.HaveError)
                {
                    return(true);
                }

                if (_position >= len)
                {
                    break;
                }

                try
                {
                    line       = ReadLine(buffer, _position, len - _position, ref used);
                    _position += used;
                }
                catch
                {
                    _context.ErrorMessage = HttpStatusDescription.Get(400) !;
                    _context.ErrorStatus  = 400;
                    return(true);
                }

                if (line == null)
                {
                    break;
                }

                if (line == "")
                {
                    if (_inputState == InputState.RequestLine)
                    {
                        continue;
                    }
                    _currentLine = null;
                    return(true);
                }

                if (_inputState == InputState.RequestLine)
                {
                    _context.Request.SetRequestLine(line);
                    _inputState = InputState.Headers;
                }
                else
                {
                    try
                    {
                        _context.Request.AddHeader(line);
                    }
                    catch (Exception e)
                    {
                        _context.ErrorMessage = e.Message;
                        _context.ErrorStatus  = 400;
                        return(true);
                    }
                }
            }

            if (used == len)
            {
                ms.SetLength(0);
                _position = 0;
            }
            return(false);
        }
Esempio n. 12
0
        private void OnReadInternal(IAsyncResult ares)
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
            int nread;

            try
            {
                nread = _stream.EndRead(ares);
                _memoryStream !.Write(_buffer !, 0, nread);
                if (_memoryStream.Length > 32768)
                {
                    SendError(HttpStatusDescription.Get(400), 400);
                    Close(true);
                    return;
                }
            }
            catch
            {
                if (_memoryStream != null && _memoryStream.Length > 0)
                {
                    SendError();
                }
                if (_socket != null)
                {
                    CloseSocket();
                    Unbind();
                }
                return;
            }

            if (nread == 0)
            {
                CloseSocket();
                Unbind();
                return;
            }

            if (ProcessInput(_memoryStream))
            {
                if (!_context.HaveError)
                {
                    _context.Request.FinishInitialization();
                }

                if (_context.HaveError)
                {
                    SendError();
                    Close(true);
                    return;
                }

                if (!_epl.BindContext(_context))
                {
                    const int NotFoundErrorCode = 404;
                    SendError(HttpStatusDescription.Get(NotFoundErrorCode), NotFoundErrorCode);
                    Close(true);
                    return;
                }
                HttpListener listener = _context._listener !;
                if (_lastListener != listener)
                {
                    RemoveConnection();
                    listener.AddConnection(this);
                    _lastListener = listener;
                }

                _contextBound = true;
                listener.RegisterContext(_context);
                return;
            }
            _stream.BeginRead(_buffer !, 0, BufferSize, s_onreadCallback, this);
        }
        internal void AddHeader(string header)
        {
            int colon = header.IndexOf(':');

            if (colon == -1 || colon == 0)
            {
                _context.ErrorMessage = HttpStatusDescription.Get(400);
                _context.ErrorStatus  = 400;
                return;
            }

            string name  = header.Substring(0, colon).Trim();
            string val   = header.Substring(colon + 1).Trim();
            string lower = name.ToLower(CultureInfo.InvariantCulture);

            _headers.Set(name, val);
            switch (lower)
            {
            case "accept-language":
                _userLanguages = val.Split(',');     // yes, only split with a ','
                break;

            case "accept":
                _acceptTypes = val.Split(',');     // yes, only split with a ','
                break;

            case "content-length":
                try
                {
                    _contentLength = long.Parse(val.Trim());
                    if (_contentLength < 0)
                    {
                        _context.ErrorMessage = "Invalid Content-Length.";
                    }
                    _clSet = true;
                }
                catch
                {
                    _context.ErrorMessage = "Invalid Content-Length.";
                }

                break;

            case "referer":
                try
                {
                    _referrer = new Uri(val);
                }
                catch
                {
                    _referrer = null;
                }

                break;

            case "cookie":
                if (_cookies == null)
                {
                    _cookies = new CookieCollection();
                }

                string[] cookieStrings = val.Split(new char[] { ',', ';' });
                Cookie   current       = null;
                int      version       = 0;
                foreach (string cookieString in cookieStrings)
                {
                    string str = cookieString.Trim();
                    if (str.Length == 0)
                    {
                        continue;
                    }
                    if (str.StartsWith("$Version"))
                    {
                        version = Int32.Parse(Unquote(str.Substring(str.IndexOf('=') + 1)));
                    }
                    else if (str.StartsWith("$Path"))
                    {
                        if (current != null)
                        {
                            current.Path = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else if (str.StartsWith("$Domain"))
                    {
                        if (current != null)
                        {
                            current.Domain = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else if (str.StartsWith("$Port"))
                    {
                        if (current != null)
                        {
                            current.Port = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else
                    {
                        if (current != null)
                        {
                            _cookies.Add(current);
                        }
                        current = new Cookie();
                        int idx = str.IndexOf('=');
                        if (idx > 0)
                        {
                            current.Name  = str.Substring(0, idx).Trim();
                            current.Value = str.Substring(idx + 1).Trim();
                        }
                        else
                        {
                            current.Name  = str.Trim();
                            current.Value = String.Empty;
                        }
                        current.Version = version;
                    }
                }
                if (current != null)
                {
                    _cookies.Add(current);
                }
                break;
            }
        }