1 # -*- encoding: binary -*-
5 # middleware used to enforce client_max_body_size for TeeInput users,
6 # there is no need to configure this middleware manually, it will
7 # automatically be configured for you based on the client_max_body_size
9 class MaxBody < Struct.new(:app)
11 # this is meant to be included in Rainbows::TeeInput (and derived
12 # classes) to limit body sizes
16 def initialize(socket, req, parser, buf)
17 self.len = parser.content_length
19 max = Rainbows.max_bytes # never nil, see MaxBody.setup
21 socket.write(Const::ERROR_413_RESPONSE)
23 raise IOError, "Content-Length too big: #{len} > #{max}", []
32 parser.filter_body(buf2, buf) and finalize_input
33 buf2.size > max and raise IOError, "chunked request body too big", []
35 self.tmp = len && len < Const::MAX_BODY ? StringIO.new("") : Util.tmpio
46 if rv && ((@max_body -= rv.size) < 0)
47 # make HttpParser#keepalive? => false to force an immediate disconnect
57 # this is called after forking, so it won't ever affect the master
58 # if it's reconfigured
60 Rainbows.max_bytes or return
62 when :Rev, :EventMachine, :NeverBlock
66 TeeInput.class_eval { include Limit }
68 # force ourselves to the outermost middleware layer
69 G.server.app = MaxBody.new(G.server.app)
72 # Rack response returned when there's an error
74 [ 413, [ %w(Content-Length 0), %w(Content-Type text/plain) ], [] ]
77 # our main Rack middleware endpoint
79 catch(:rainbows_EFBIG) { app.call(env) } || err(env)