1 # -*- encoding: binary -*-
3 # Middleware used to enforce client_max_body_size for TeeInput users.
5 # There is no need to configure this middleware manually, it will
6 # automatically be configured for you based on the client_max_body_size
9 # For more fine-grained control, you may also define it per-endpoint in
10 # your Rack config.ru like this:
13 # use Rainbows::MaxBody, 1024*1024
17 # use Rainbows::MaxBody, 1024*1024*10
21 class Rainbows::MaxBody
23 # This is automatically called when used with Rack::Builder#use
24 def initialize(app, limit = Rainbows.client_max_body_size)
25 Integer === limit or raise ArgumentError, "limit not an Integer"
26 @app, @limit = app, limit
30 RACK_INPUT = "rack.input".freeze
31 CONTENT_LENGTH = "CONTENT_LENGTH"
32 HTTP_TRANSFER_ENCODING = "HTTP_TRANSFER_ENCODING"
34 # our main Rack middleware endpoint
36 catch(:rainbows_EFBIG) do
37 len = env[CONTENT_LENGTH]
38 if len && len.to_i > @limit
40 elsif /\Achunked\z/i =~ env[HTTP_TRANSFER_ENCODING]
47 # this is called after forking, so it won't ever affect the master
48 # if it's reconfigured
49 def self.setup # :nodoc:
50 Rainbows.client_max_body_size or return
51 case Rainbows.server.use
52 when :Rev, :Coolio, :EventMachine, :NeverBlock,
53 :RevThreadSpawn, :RevThreadPool,
54 :CoolioThreadSpawn, :CoolioThreadPool,
59 # force ourselves to the outermost middleware layer
60 Rainbows.server.app = self.new(Rainbows.server.app)
63 # Rack response returned when there's an error
65 [ 413, { 'Content-Length' => '0', 'Content-Type' => 'text/plain' }, [] ]
69 input = env[RACK_INPUT]
70 klass = input.respond_to?(:rewind) ? RewindableWrapper : Wrapper
71 env[RACK_INPUT] = klass.new(input, @limit)
76 require 'rainbows/max_body/wrapper'
77 require 'rainbows/max_body/rewindable_wrapper'