1 # -*- encoding: binary -*-
3 # base module for evented models like Rev and EventMachine
4 module Rainbows::EvCore
5 include Rainbows::Const
6 include Rainbows::Response
7 NULL_IO = Unicorn::HttpRequest::NULL_IO
8 HttpParser = Rainbows::HttpParser
9 autoload :CapInput, 'rainbows/ev_core/cap_input'
12 HBUFSIZ = Rainbows.client_header_buffer_size
14 # Apps may return this Rack response: AsyncResponse = [ -1, {}, [] ]
15 ASYNC_CALLBACK = "async.callback".freeze
16 ASYNC_CLOSE = "async.close".freeze
18 def write_async_response(response)
19 status, headers, body = response
21 # we can't do HTTP keepalive without Content-Length or
22 # "Transfer-Encoding: chunked", and the async.callback stuff
23 # isn't Rack::Lint-compatible, so we have to enforce it here.
24 headers = Rack::Utils::HeaderHash.new(headers) unless Hash === headers
25 alive = headers.include?(Content_Length) ||
26 !!(%r{\Achunked\z}i =~ headers[Transfer_Encoding])
29 ev_write_response(status, headers, body, alive)
36 @state = :headers # [ :body [ :trailers ] ] :app_call :close
39 # graceful exit, like SIGQUIT
48 msg = Rainbows::Error.response(e) and write(msg)
53 # returns whether to enable response chunking for autochunk models
54 def stream_response_headers(status, headers, alive)
55 headers = Rack::Utils::HeaderHash.new(headers) unless Hash === headers
56 if headers.include?(Content_Length)
59 rv = !!(headers[Transfer_Encoding] =~ %r{\Achunked\z}i)
60 rv = false unless @env["rainbows.autochunk"]
62 write_headers(status, headers, alive)
66 def prepare_request_body
67 # since we don't do streaming input, we have no choice but
68 # to take over 100-continue handling from the Rack application
69 if @env[HTTP_EXPECT] =~ /\A100-continue\z/i
70 write(EXPECT_100_RESPONSE)
71 @env.delete(HTTP_EXPECT)
74 @hp.filter_body(@buf2 = "", @buf)
79 # TeeInput doesn't map too well to this right now...
84 @hp.parse or return want_more
86 if 0 == @hp.content_length
87 app_call NULL_IO # common case
101 @hp.filter_body(@buf2, @buf << data)
108 if @hp.trailers(@env, @buf << data)
119 ERROR_413_RESPONSE = "HTTP/1.1 413 Request Entity Too Large\r\n\r\n"
122 write(ERROR_413_RESPONSE)
124 # zip back up the stack
125 raise IOError, msg, []
128 TmpIO = Unicorn::TmpIO
129 CBB = Unicorn::TeeInput.client_body_buffer_size
132 bytes <= CBB ? StringIO.new("") : TmpIO.new
136 max = Rainbows.client_max_body_size
137 len = @hp.content_length
139 if max && (len > max)
140 err_413("Content-Length too big: #{len} > #{max}")
144 max ? CapInput.new(io_for(max), self, max) : TmpIO.new