示例#1
0
文件: web.cs 项目: swax/Tornado.Net
        public RequestHandler(Application application_, HTTPRequest request_, Dictionary<string, object> kwargs)
        {
            //def __init__(self, application, request, **kwargs):
            //super(RequestHandler, self).__init__()

            application = application_;
            request = request_;
            _headers_written = false;
            _finished = false;
            _auto_finish = true;

            _transforms = null;  // will be set in _execute
            //todo implement 
            /*self.ui = ObjectDict((n, self._ui_method(m)) for n, m in
                         application.ui_methods.iteritems())*/
            // UIModules are available as both `modules` and `_modules` in the
            // template namespace.  Historically only `modules` was available
            // but could be clobbered by user additions to the namespace.
            // The template {% module %} directive looks in `_modules` to avoid
            // possible conflicts.
            /*self.ui["_modules"] = ObjectDict((n, self._ui_module(n, m)) for n, m in
                                     application.ui_modules.iteritems())
            self.ui["modules"] = self.ui["_modules"]*/
            clear();
            // Check since connection is not available in WSGI
            if (request.connection != null)
                request.connection.stream.set_close_callback(on_connection_close);
            initialize(kwargs);
        }
示例#2
0
文件: web.cs 项目: swax/Tornado.Net
        private List<URLSpec> _get_host_handlers(HTTPRequest request)
        {
            var host = request.host.ToLowerInvariant().Split(':')[0];
            foreach (var handler in handlers)
            {
                var pattern = handler.Item1;
                var handlers_ = handler.Item2;

                if (pattern.IsMatch(host))
                    return handlers_;
            }
            // Look for default host if not behind load balancer (for debugging)
            if (!request.headers.ContainsKey("X-Real-Ip"))
                foreach (var handler in handlers)
                {
                    var pattern = handler.Item1;
                    var handlers_ = handler.Item2;
                    if (pattern.IsMatch(default_host))
                        return handlers_;
                }
            return null;
        }
示例#3
0
文件: web.cs 项目: swax/Tornado.Net
 public ChunkedTransferEncoding(HTTPRequest request)
     : base(request)
 {
     _chunking = request.supports_http_1_1();
 }
示例#4
0
文件: web.cs 项目: swax/Tornado.Net
        /*A transform modifies the result of an HTTP request (e.g., GZip encoding)

        A new transform instance is created for every request. See the
        ChunkedTransferEncoding example below if you want to implement a
        new Transform.
        */
        public OutputTransform(HTTPRequest request)
        {

        }
示例#5
0
文件: web.cs 项目: swax/Tornado.Net
 public GZipContentEncoding(HTTPRequest request)
     : base(request)
 {
     _gzipping = request.supports_http_1_1() &&
         request.headers.get("Accept-Encoding", "").Contains("gzip");
 }
示例#6
0
文件: web.cs 项目: swax/Tornado.Net
 public StaticFileHandler(Application application_, HTTPRequest request_, Dictionary<string, object> kwargs)
     : base(application_, request_, kwargs)
 {
 }
示例#7
0
文件: web.cs 项目: swax/Tornado.Net
        public RequestHandler Call(HTTPRequest request)
        {
            // Called by HTTPServer to execute the request.
            var transforms_ = transforms.Select(t => t(request)).ToList();
            RequestHandler handler = null;
            var args = new List<string>();
            var kwargs = new Dictionary<string, string>();
            var handlers_ = _get_host_handlers(request);
            if (handlers == null || !handlers.Any())
                handler = new RedirectHandler(this, 
                    request, new Dictionary<string, object>(){{"url", "http://" + default_host + "/"}});
            else
            {
                foreach (var spec in handlers_)
                {
                    var match = spec.regex.IsMatch(request.path);
                    if (match)
                    {
                        handler = spec.handler_class(this, request, spec.kwargs);
                        // todo implement args
                        /*if spec.regex.groups:
                            // None-safe wrapper around url_unescape to handle
                            // unmatched optional groups correctly
                            def unquote(s):
                                if s is None:
                                    return s
                                return escape.url_unescape(s, encoding=None)
                            // Pass matched groups to the handler.  Since
                            // match.groups() includes both named and unnamed groups,
                            // we want to use either groups or groupdict but not both.
                            // Note that args are passed as bytes so the handler can
                            // decide what encoding to use.

                            if spec.regex.groupindex:
                                kwargs = dict(
                                    (str(k), unquote(v))
                                    for (k, v) in match.groupdict().iteritems())
                            else:
                                args = [unquote(s) for s in match.groups()]*/
                        break;
                    }
                }
                if (handler == null)
                    handler = new ErrorHandler(this, request, new Dictionary<string, object>{{"status_code", 404}});
            }
            // In debug mode, re-compile templates and reload static files on every
            // request so you don't need to restart to see changes
            /*if self.settings.get("debug"):
                with RequestHandler._template_loader_lock:
                    for loader in RequestHandler._template_loaders.values():
                        loader.reset()
                StaticFileHandler.reset()*/

            handler._execute(transforms_, args, kwargs);
            return handler;
        }
示例#8
0
        private void _on_headers(byte[] data_)
        {
            try
            {
                string data = UTF8Encoding.UTF8.GetString(data_);
                var eol = data.IndexOf("\r\n");
                var start_line = data.Substring(0, eol);
                string method, uri, version;
                try
                {
                    // method, uri, version = start_line.Split(' ');
                    var split = start_line.Split(' ');
                    method = split[0]; uri = split[1]; version = split[2];
                }
                catch(Exception ex) // except ValueError:
                {
                    throw new _BadRequestException("Malformed HTTP request line");
                }
                if (!version.StartsWith("HTTP/"))
                    throw new _BadRequestException("Malformed HTTP version in HTTP Request-Line");
                var headers = HTTPHeaders.parse(data.Substring(eol));
                    
                // HTTPRequest wants an IP, not a full socket address
                var remote_ip = "";
                if (stream.socket.AddressFamily == AddressFamily.InterNetwork ||
                   stream.socket.AddressFamily == AddressFamily.InterNetworkV6)
                    // Jython 2.5.2 doesn't have the socket.family attribute,
                    // so just assume IP in that case.
                    remote_ip = address.Address.ToString();
                else
                    // Unix (or other) socket; fake the remote address
                    remote_ip = "0.0.0.0";

                _request = new HTTPRequest(
                    connection_: this, method_: method, uri_: uri, version_: version,
                    headers_: headers, remote_ip_: remote_ip);

                var content_length_ = headers.get("Content-Length");
                if (content_length_ != null)
                {
                    var content_length = int.Parse(content_length_);
                    if (content_length > stream.max_buffer_size)
                        throw new _BadRequestException("Content-Length too long");
                    if (headers.get("Expect") == "100-continue")
                        stream.write(UTF8Encoding.UTF8.GetBytes("HTTP/1.1 100 (Continue)\r\n\r\n"));
                    stream.read_bytes(content_length, _on_request_body);
                    return;
                }

                request_callback(_request);
            }
            catch(Exception ex)
            {
                logging.info(string.Format("Malformed HTTP request from {0}: {1}", address, ex));
                close();
                return;
            }
        }
示例#9
0
        public void _finish_request()
        {
            bool disconnect = false;

            if (no_keep_alive)
                disconnect = true;
            else
            {
                var connection_header = _request.headers.get("Connection");
                if (connection_header != null)
                    connection_header = connection_header.ToLowerInvariant();
                if (_request.supports_http_1_1())
                    disconnect = (connection_header == "close");
                else if (_request.headers.ContainsKey("Content-Length") ||
                         (_request.method == "HEAD" || _request.method == "GET"))
                    disconnect = (connection_header != "keep-alive");
                else
                    disconnect = true;
            }
            _request = null;
            _request_finished = false;
            if (disconnect)
            {
                close();
                return;
            }
            stream.read_until(Encoding.UTF8.GetBytes("\r\n\r\n"), _header_callback);
        }
示例#10
0
 public HTTPConnection(IOStream stream_, IPEndPoint address_, Func<HTTPRequest, RequestHandler> request_callback_, bool no_keep_alive_ = false, bool xheaders_ = false)
 {
     stream = stream_;
     address = address_;
     request_callback = request_callback_;
     no_keep_alive = no_keep_alive_;
     xheaders = xheaders_;
     _request = null;
     _request_finished = false;
     // Save stack context here, outside of any request.  This keeps
     // contexts from one request from leaking into the next.
     _header_callback = _on_headers; //stack_context.wrap(self._on_headers);
     stream.read_until(Encoding.UTF8.GetBytes("\r\n\r\n"), _header_callback);
     _write_callback = null;
 }