1 # -*- encoding: binary -*-
5 # base module for evented models like Rev and EventMachine
8 include Rainbows::Const
9 include Rainbows::Response
11 NULL_IO = Unicorn::HttpRequest::NULL_IO
13 # Apps may return this Rack response: AsyncResponse = [ -1, {}, [] ]
14 ASYNC_CALLBACK = "async.callback".freeze
16 ASYNC_CLOSE = "async.close".freeze
19 @remote_addr = Rainbows.addr(@_io)
22 @state = :headers # [ :body [ :trailers ] ] :app_call :close
26 # graceful exit, like SIGQUIT
32 msg = Error.response(e) and write(msg)
37 # returns whether to enable response chunking for autochunk models
38 def stream_response_headers(status, headers)
39 if headers['Content-Length']
42 rv = !!(headers['Transfer-Encoding'] =~ %r{\Achunked\z}i)
43 rv = false if headers.delete('X-Rainbows-Autochunk') == 'no'
45 headers[CONNECTION] = CLOSE # TODO: allow keep-alive
46 write(response_header(status, headers))
50 # TeeInput doesn't map too well to this right now...
54 @hp.headers(@env, @buf << data) or return
56 len = @hp.content_length
59 app_call # common case
61 # since we don't do streaming input, we have no choice but
62 # to take over 100-continue handling from the Rack application
63 if @env[HTTP_EXPECT] =~ /\A100-continue\z/i
64 write(EXPECT_100_RESPONSE)
65 @env.delete(HTTP_EXPECT)
67 @input = CapInput.new(len, self)
68 @hp.filter_body(@buf2 = "", @buf)
77 @hp.filter_body(@buf2, @buf << data)
82 if @hp.trailers(@env, @buf << data)
91 class CapInput < Struct.new(:io, :client, :bytes_left)
92 MAX_BODY = Unicorn::Const::MAX_BODY
95 def self.err(client, msg)
96 client.write(Const::ERROR_413_RESPONSE)
99 # zip back up the stack
100 raise IOError, msg, []
103 def self.new(len, client)
104 max = Rainbows.max_bytes
106 if max && (len > max)
107 err(client, "Content-Length too big: #{len} > #{max}")
109 len <= MAX_BODY ? StringIO.new("") : Util.tmpio
111 max ? super(Util.tmpio, client, max) : Util.tmpio
116 if (self.bytes_left -= buf.size) < 0
118 CapInput.err(client, "chunked request body too big")
123 def gets; io.gets; end
124 def each(&block); io.each(&block); end
125 def size; io.size; end
126 def rewind; io.rewind; end
127 def read(*args); io.read(*args); end