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'
13 # Apps may return this Rack response: AsyncResponse = [ -1, {}, [] ]
14 ASYNC_CALLBACK = "async.callback".freeze
15 ASYNC_CLOSE = "async.close".freeze
17 def write_async_response(response)
18 status, headers, body = response
20 # we can't do HTTP keepalive without Content-Length or
21 # "Transfer-Encoding: chunked", and the async.callback stuff
22 # isn't Rack::Lint-compatible, so we have to enforce it here.
23 headers = Rack::Utils::HeaderHash.new(headers) unless Hash === headers
24 alive = headers.include?(Content_Length) ||
25 !!(%r{\Achunked\z}i =~ headers[Transfer_Encoding])
28 ev_write_response(status, headers, body, alive)
35 @state = :headers # [ :body [ :trailers ] ] :app_call :close
38 # graceful exit, like SIGQUIT
47 msg = Rainbows::Error.response(e) and write(msg)
52 # returns whether to enable response chunking for autochunk models
53 def stream_response_headers(status, headers, alive)
54 headers = Rack::Utils::HeaderHash.new(headers) unless Hash === headers
55 if headers.include?(Content_Length)
58 rv = !!(headers[Transfer_Encoding] =~ %r{\Achunked\z}i)
59 rv = false unless @env["rainbows.autochunk"]
61 write_headers(status, headers, alive)
65 def prepare_request_body
66 # since we don't do streaming input, we have no choice but
67 # to take over 100-continue handling from the Rack application
68 if @env[HTTP_EXPECT] =~ /\A100-continue\z/i
69 write(EXPECT_100_RESPONSE)
70 @env.delete(HTTP_EXPECT)
73 @hp.filter_body(@buf2 = "", @buf)
78 # TeeInput doesn't map too well to this right now...
83 @hp.parse or return want_more
85 if 0 == @hp.content_length
86 app_call NULL_IO # 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