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 # This is only compatible with concurrency models that expose a streaming
22 # "rack.input" to the Rack application. Thus it is NOT compatible with
23 # any of the following as they fully buffer the request body before
24 # the application dispatch:
28 # * :CoolioThreadSpawn
37 # However, the global Rainbows::Configurator#client_max_body_size is compatible
38 # with all concurrency models \Rainbows! supports.
39 class Rainbows::MaxBody
41 # This is automatically called when used with Rack::Builder#use
42 def initialize(app, limit = nil)
46 raise ArgumentError, "limit not an Integer"
48 @app, @limit = app, limit
52 RACK_INPUT = "rack.input".freeze
53 CONTENT_LENGTH = "CONTENT_LENGTH"
54 HTTP_TRANSFER_ENCODING = "HTTP_TRANSFER_ENCODING"
56 # our main Rack middleware endpoint
58 @limit = Rainbows.server.client_max_body_size if nil == @limit
59 catch(:rainbows_EFBIG) do
60 len = env[CONTENT_LENGTH]
61 if len && len.to_i > @limit
63 elsif /\Achunked\z/i =~ env[HTTP_TRANSFER_ENCODING]
70 # this is called after forking, so it won't ever affect the master
71 # if it's reconfigured
72 def self.setup # :nodoc:
73 Rainbows.server.client_max_body_size or return
74 case Rainbows.server.use
75 when :Rev, :Coolio, :EventMachine, :NeverBlock,
76 :RevThreadSpawn, :RevThreadPool,
77 :CoolioThreadSpawn, :CoolioThreadPool,
82 # force ourselves to the outermost middleware layer
83 Rainbows.server.app = self.new(Rainbows.server.app)
86 # Rack response returned when there's an error
88 [ 413, { 'Content-Length' => '0', 'Content-Type' => 'text/plain' }, [] ]
92 input = env[RACK_INPUT]
93 klass = input.respond_to?(:rewind) ? RewindableWrapper : Wrapper
94 env[RACK_INPUT] = klass.new(input, @limit)
99 require 'rainbows/max_body/wrapper'
100 require 'rainbows/max_body/rewindable_wrapper'