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 # Apps may return this Rack response: AsyncResponse = [ -1, {}, [] ]
13 ASYNC_CALLBACK = "async.callback".freeze
14 ASYNC_CLOSE = "async.close".freeze
16 def write_async_response(response)
17 status, headers, body = response
19 # we can't do HTTP keepalive without Content-Length or
20 # "Transfer-Encoding: chunked", and the async.callback stuff
21 # isn't Rack::Lint-compatible, so we have to enforce it here.
22 headers = Rack::Utils::HeaderHash.new(headers) unless Hash === headers
23 alive = headers.include?(Content_Length) ||
24 !!(%r{\Achunked\z}i =~ headers[Transfer_Encoding])
27 ev_write_response(status, headers, body, alive)
34 @state = :headers # [ :body [ :trailers ] ] :app_call :close
37 # graceful exit, like SIGQUIT
46 msg = Rainbows::Error.response(e) and write(msg)
51 # returns whether to enable response chunking for autochunk models
52 def stream_response_headers(status, headers, alive)
53 headers = Rack::Utils::HeaderHash.new(headers) unless Hash === headers
54 if headers.include?(Content_Length)
57 rv = !!(headers[Transfer_Encoding] =~ %r{\Achunked\z}i)
58 rv = false unless @env["rainbows.autochunk"]
60 write_headers(status, headers, alive)
64 def prepare_request_body
65 # since we don't do streaming input, we have no choice but
66 # to take over 100-continue handling from the Rack application
67 if @env[HTTP_EXPECT] =~ /\A100-continue\z/i
68 write(EXPECT_100_RESPONSE)
69 @env.delete(HTTP_EXPECT)
72 @hp.filter_body(@buf2 = "", @buf)
77 # TeeInput doesn't map too well to this right now...
82 @hp.parse or return want_more
84 if 0 == @hp.content_length
86 app_call # common case
100 @hp.filter_body(@buf2, @buf << data)
107 if @hp.trailers(@env, @buf << data)
118 ERROR_413_RESPONSE = "HTTP/1.1 413 Request Entity Too Large\r\n\r\n"
121 write(ERROR_413_RESPONSE)
123 # zip back up the stack
124 raise IOError, msg, []
127 TmpIO = Unicorn::TmpIO
128 CBB = Unicorn::TeeInput.client_body_buffer_size
131 bytes <= CBB ? StringIO.new("") : TmpIO.new
135 max = Rainbows.max_bytes
136 len = @hp.content_length
138 if max && (len > max)
139 err_413("Content-Length too big: #{len} > #{max}")
143 max ? CapInput.new(io_for(max), self, max) : TmpIO.new