rack 2.1.4.4 → 2.2.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rack might be problematic. Click here for more details.

Files changed (61) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +598 -15
  3. data/CONTRIBUTING.md +136 -0
  4. data/README.rdoc +84 -54
  5. data/Rakefile +14 -7
  6. data/{SPEC → SPEC.rdoc} +35 -6
  7. data/lib/rack/auth/abstract/request.rb +0 -2
  8. data/lib/rack/auth/basic.rb +3 -3
  9. data/lib/rack/auth/digest/md5.rb +4 -4
  10. data/lib/rack/auth/digest/request.rb +3 -3
  11. data/lib/rack/body_proxy.rb +13 -9
  12. data/lib/rack/builder.rb +77 -8
  13. data/lib/rack/cascade.rb +23 -8
  14. data/lib/rack/chunked.rb +48 -23
  15. data/lib/rack/common_logger.rb +25 -21
  16. data/lib/rack/conditional_get.rb +18 -16
  17. data/lib/rack/content_length.rb +6 -7
  18. data/lib/rack/content_type.rb +3 -4
  19. data/lib/rack/deflater.rb +45 -35
  20. data/lib/rack/directory.rb +77 -60
  21. data/lib/rack/etag.rb +2 -3
  22. data/lib/rack/events.rb +15 -18
  23. data/lib/rack/file.rb +1 -1
  24. data/lib/rack/files.rb +96 -56
  25. data/lib/rack/handler/cgi.rb +1 -4
  26. data/lib/rack/handler/fastcgi.rb +1 -3
  27. data/lib/rack/handler/lsws.rb +1 -3
  28. data/lib/rack/handler/scgi.rb +1 -3
  29. data/lib/rack/handler/thin.rb +15 -11
  30. data/lib/rack/handler/webrick.rb +12 -5
  31. data/lib/rack/head.rb +0 -2
  32. data/lib/rack/lint.rb +58 -15
  33. data/lib/rack/lobster.rb +3 -5
  34. data/lib/rack/lock.rb +0 -1
  35. data/lib/rack/mock.rb +22 -4
  36. data/lib/rack/multipart/generator.rb +11 -6
  37. data/lib/rack/multipart/parser.rb +12 -32
  38. data/lib/rack/multipart/uploaded_file.rb +13 -7
  39. data/lib/rack/multipart.rb +5 -4
  40. data/lib/rack/query_parser.rb +7 -8
  41. data/lib/rack/recursive.rb +1 -1
  42. data/lib/rack/reloader.rb +1 -3
  43. data/lib/rack/request.rb +172 -76
  44. data/lib/rack/response.rb +62 -19
  45. data/lib/rack/rewindable_input.rb +0 -1
  46. data/lib/rack/runtime.rb +3 -3
  47. data/lib/rack/sendfile.rb +0 -3
  48. data/lib/rack/server.rb +9 -8
  49. data/lib/rack/session/abstract/id.rb +20 -18
  50. data/lib/rack/session/cookie.rb +2 -3
  51. data/lib/rack/session/pool.rb +1 -1
  52. data/lib/rack/show_exceptions.rb +2 -4
  53. data/lib/rack/show_status.rb +1 -3
  54. data/lib/rack/static.rb +13 -6
  55. data/lib/rack/tempfile_reaper.rb +0 -2
  56. data/lib/rack/urlmap.rb +1 -4
  57. data/lib/rack/utils.rb +70 -82
  58. data/lib/rack/version.rb +29 -0
  59. data/lib/rack.rb +7 -16
  60. data/rack.gemspec +31 -29
  61. metadata +14 -15
@@ -1,17 +1,25 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Rack
4
+ # Proxy for response bodies allowing calling a block when
5
+ # the response body is closed (after the response has been fully
6
+ # sent to the client).
4
7
  class BodyProxy
8
+ # Set the response body to wrap, and the block to call when the
9
+ # response has been fully sent.
5
10
  def initialize(body, &block)
6
11
  @body = body
7
12
  @block = block
8
13
  @closed = false
9
14
  end
10
15
 
11
- def respond_to?(method_name, include_all = false)
16
+ # Return whether the wrapped body responds to the method.
17
+ def respond_to_missing?(method_name, include_all = false)
12
18
  super or @body.respond_to?(method_name, include_all)
13
19
  end
14
20
 
21
+ # If not already closed, close the wrapped body and
22
+ # then call the block the proxy was initialized with.
15
23
  def close
16
24
  return if @closed
17
25
  @closed = true
@@ -22,20 +30,16 @@ module Rack
22
30
  end
23
31
  end
24
32
 
33
+ # Whether the proxy is closed. The proxy starts as not closed,
34
+ # and becomes closed on the first call to close.
25
35
  def closed?
26
36
  @closed
27
37
  end
28
38
 
29
- # N.B. This method is a special case to address the bug described by #434.
30
- # We are applying this special case for #each only. Future bugs of this
31
- # class will be handled by requesting users to patch their ruby
32
- # implementation, to save adding too many methods in this class.
33
- def each
34
- @body.each { |body| yield body }
35
- end
36
-
39
+ # Delegate missing methods to the wrapped body.
37
40
  def method_missing(method_name, *args, &block)
38
41
  @body.__send__(method_name, *args, &block)
39
42
  end
43
+ ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
40
44
  end
41
45
  end
data/lib/rack/builder.rb CHANGED
@@ -35,6 +35,32 @@ module Rack
35
35
  # https://stackoverflow.com/questions/2223882/whats-the-difference-between-utf-8-and-utf-8-without-bom
36
36
  UTF_8_BOM = '\xef\xbb\xbf'
37
37
 
38
+ # Parse the given config file to get a Rack application.
39
+ #
40
+ # If the config file ends in +.ru+, it is treated as a
41
+ # rackup file and the contents will be treated as if
42
+ # specified inside a Rack::Builder block, using the given
43
+ # options.
44
+ #
45
+ # If the config file does not end in +.ru+, it is
46
+ # required and Rack will use the basename of the file
47
+ # to guess which constant will be the Rack application to run.
48
+ # The options given will be ignored in this case.
49
+ #
50
+ # Examples:
51
+ #
52
+ # Rack::Builder.parse_file('config.ru')
53
+ # # Rack application built using Rack::Builder.new
54
+ #
55
+ # Rack::Builder.parse_file('app.rb')
56
+ # # requires app.rb, which can be anywhere in Ruby's
57
+ # # load path. After requiring, assumes App constant
58
+ # # contains Rack application
59
+ #
60
+ # Rack::Builder.parse_file('./my_app.rb')
61
+ # # requires ./my_app.rb, which should be in the
62
+ # # process's current directory. After requiring,
63
+ # # assumes MyApp constant contains Rack application
38
64
  def self.parse_file(config, opts = Server::Options.new)
39
65
  if config.end_with?('.ru')
40
66
  return self.load_file(config, opts)
@@ -45,6 +71,25 @@ module Rack
45
71
  end
46
72
  end
47
73
 
74
+ # Load the given file as a rackup file, treating the
75
+ # contents as if specified inside a Rack::Builder block.
76
+ #
77
+ # Treats the first comment at the beginning of a line
78
+ # that starts with a backslash as options similar to
79
+ # options passed on a rackup command line.
80
+ #
81
+ # Ignores content in the file after +__END__+, so that
82
+ # use of +__END__+ will not result in a syntax error.
83
+ #
84
+ # Example config.ru file:
85
+ #
86
+ # $ cat config.ru
87
+ #
88
+ # #\ -p 9393
89
+ #
90
+ # use Rack::ContentLength
91
+ # require './app.rb'
92
+ # run App
48
93
  def self.load_file(path, opts = Server::Options.new)
49
94
  options = {}
50
95
 
@@ -52,6 +97,7 @@ module Rack
52
97
  cfgfile.slice!(/\A#{UTF_8_BOM}/) if cfgfile.encoding == Encoding::UTF_8
53
98
 
54
99
  if cfgfile[/^#\\(.*)/] && opts
100
+ warn "Parsing options from the first comment line is deprecated!"
55
101
  options = opts.parse! $1.split(/\s+/)
56
102
  end
57
103
 
@@ -61,16 +107,26 @@ module Rack
61
107
  return app, options
62
108
  end
63
109
 
110
+ # Evaluate the given +builder_script+ string in the context of
111
+ # a Rack::Builder block, returning a Rack application.
64
112
  def self.new_from_string(builder_script, file = "(rackup)")
65
- eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app",
66
- TOPLEVEL_BINDING, file, 0
113
+ # We want to build a variant of TOPLEVEL_BINDING with self as a Rack::Builder instance.
114
+ # We cannot use instance_eval(String) as that would resolve constants differently.
115
+ binding, builder = TOPLEVEL_BINDING.eval('Rack::Builder.new.instance_eval { [binding, self] }')
116
+ eval builder_script, binding, file
117
+ builder.to_app
67
118
  end
68
119
 
120
+ # Initialize a new Rack::Builder instance. +default_app+ specifies the
121
+ # default application if +run+ is not called later. If a block
122
+ # is given, it is evaluted in the context of the instance.
69
123
  def initialize(default_app = nil, &block)
70
124
  @use, @map, @run, @warmup, @freeze_app = [], nil, default_app, nil, false
71
125
  instance_eval(&block) if block_given?
72
126
  end
73
127
 
128
+ # Create a new Rack::Builder instance and return the Rack application
129
+ # generated from it.
74
130
  def self.app(default_app = nil, &block)
75
131
  self.new(default_app, &block).to_app
76
132
  end
@@ -121,7 +177,8 @@ module Rack
121
177
  @run = app
122
178
  end
123
179
 
124
- # Takes a lambda or block that is used to warm-up the application.
180
+ # Takes a lambda or block that is used to warm-up the application. This block is called
181
+ # before the Rack application is returned by to_app.
125
182
  #
126
183
  # warmup do |app|
127
184
  # client = Rack::MockRequest.new(app)
@@ -134,25 +191,31 @@ module Rack
134
191
  @warmup = prc || block
135
192
  end
136
193
 
137
- # Creates a route within the application.
194
+ # Creates a route within the application. Routes under the mapped path will be sent to
195
+ # the Rack application specified by run inside the block. Other requests will be sent to the
196
+ # default application specified by run outside the block.
138
197
  #
139
198
  # Rack::Builder.app do
140
- # map '/' do
199
+ # map '/heartbeat' do
141
200
  # run Heartbeat
142
201
  # end
202
+ # run App
143
203
  # end
144
204
  #
145
- # The +use+ method can also be used here to specify middleware to run under a specific path:
205
+ # The +use+ method can also be used inside the block to specify middleware to run under a specific path:
146
206
  #
147
207
  # Rack::Builder.app do
148
- # map '/' do
208
+ # map '/heartbeat' do
149
209
  # use Middleware
150
210
  # run Heartbeat
151
211
  # end
212
+ # run App
152
213
  # end
153
214
  #
154
- # This example includes a piece of middleware which will run before requests hit +Heartbeat+.
215
+ # This example includes a piece of middleware which will run before +/heartbeat+ requests hit +Heartbeat+.
155
216
  #
217
+ # Note that providing a +path+ of +/+ will ignore any default application given in a +run+ statement
218
+ # outside the block.
156
219
  def map(path, &block)
157
220
  @map ||= {}
158
221
  @map[path] = block
@@ -164,6 +227,7 @@ module Rack
164
227
  @freeze_app = true
165
228
  end
166
229
 
230
+ # Return the Rack application generated by this instance.
167
231
  def to_app
168
232
  app = @map ? generate_map(@run, @map) : @run
169
233
  fail "missing run or map statement" unless app
@@ -173,12 +237,17 @@ module Rack
173
237
  app
174
238
  end
175
239
 
240
+ # Call the Rack application generated by this builder instance. Note that
241
+ # this rebuilds the Rack application and runs the warmup code (if any)
242
+ # every time it is called, so it should not be used if performance is important.
176
243
  def call(env)
177
244
  to_app.call(env)
178
245
  end
179
246
 
180
247
  private
181
248
 
249
+ # Generate a URLMap instance by generating new Rack applications for each
250
+ # map block in this instance.
182
251
  def generate_map(default_app, mapping)
183
252
  mapped = default_app ? { '/' => default_app } : {}
184
253
  mapping.each { |r, b| mapped[r] = self.class.new(default_app, &b).to_app }
data/lib/rack/cascade.rb CHANGED
@@ -2,25 +2,37 @@
2
2
 
3
3
  module Rack
4
4
  # Rack::Cascade tries a request on several apps, and returns the
5
- # first response that is not 404 or 405 (or in a list of configurable
6
- # status codes).
5
+ # first response that is not 404 or 405 (or in a list of configured
6
+ # status codes). If all applications tried return one of the configured
7
+ # status codes, return the last response.
7
8
 
8
9
  class Cascade
10
+ # deprecated, no longer used
9
11
  NotFound = [404, { CONTENT_TYPE => "text/plain" }, []]
10
12
 
13
+ # An array of applications to try in order.
11
14
  attr_reader :apps
12
15
 
13
- def initialize(apps, catch = [404, 405])
16
+ # Set the apps to send requests to, and what statuses result in
17
+ # cascading. Arguments:
18
+ #
19
+ # apps: An enumerable of rack applications.
20
+ # cascade_for: The statuses to use cascading for. If a response is received
21
+ # from an app, the next app is tried.
22
+ def initialize(apps, cascade_for = [404, 405])
14
23
  @apps = []
15
24
  apps.each { |app| add app }
16
25
 
17
- @catch = {}
18
- [*catch].each { |status| @catch[status] = true }
26
+ @cascade_for = {}
27
+ [*cascade_for].each { |status| @cascade_for[status] = true }
19
28
  end
20
29
 
30
+ # Call each app in order. If the responses uses a status that requires
31
+ # cascading, try the next app. If all responses require cascading,
32
+ # return the response from the last app.
21
33
  def call(env)
22
- result = NotFound
23
-
34
+ return [404, { CONTENT_TYPE => "text/plain" }, []] if @apps.empty?
35
+ result = nil
24
36
  last_body = nil
25
37
 
26
38
  @apps.each do |app|
@@ -33,17 +45,20 @@ module Rack
33
45
  last_body.close if last_body.respond_to? :close
34
46
 
35
47
  result = app.call(env)
48
+ return result unless @cascade_for.include?(result[0].to_i)
36
49
  last_body = result[2]
37
- break unless @catch.include?(result[0].to_i)
38
50
  end
39
51
 
40
52
  result
41
53
  end
42
54
 
55
+ # Append an app to the list of apps to cascade. This app will
56
+ # be tried last.
43
57
  def add(app)
44
58
  @apps << app
45
59
  end
46
60
 
61
+ # Whether the given app is one of the apps to cascade to.
47
62
  def include?(app)
48
63
  @apps.include?(app)
49
64
  end
data/lib/rack/chunked.rb CHANGED
@@ -1,53 +1,74 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rack/utils'
4
-
5
3
  module Rack
6
4
 
7
5
  # Middleware that applies chunked transfer encoding to response bodies
8
6
  # when the response does not include a Content-Length header.
7
+ #
8
+ # This supports the Trailer response header to allow the use of trailing
9
+ # headers in the chunked encoding. However, using this requires you manually
10
+ # specify a response body that supports a +trailers+ method. Example:
11
+ #
12
+ # [200, { 'Trailer' => 'Expires'}, ["Hello", "World"]]
13
+ # # error raised
14
+ #
15
+ # body = ["Hello", "World"]
16
+ # def body.trailers
17
+ # { 'Expires' => Time.now.to_s }
18
+ # end
19
+ # [200, { 'Trailer' => 'Expires'}, body]
20
+ # # No exception raised
9
21
  class Chunked
10
22
  include Rack::Utils
11
23
 
12
- # A body wrapper that emits chunked responses
24
+ # A body wrapper that emits chunked responses.
13
25
  class Body
14
26
  TERM = "\r\n"
15
27
  TAIL = "0#{TERM}"
16
28
 
17
- include Rack::Utils
18
-
29
+ # Store the response body to be chunked.
19
30
  def initialize(body)
20
31
  @body = body
21
32
  end
22
33
 
34
+ # For each element yielded by the response body, yield
35
+ # the element in chunked encoding.
23
36
  def each(&block)
24
37
  term = TERM
25
38
  @body.each do |chunk|
26
39
  size = chunk.bytesize
27
40
  next if size == 0
28
41
 
29
- chunk = chunk.b
30
- yield [size.to_s(16), term, chunk, term].join
42
+ yield [size.to_s(16), term, chunk.b, term].join
31
43
  end
32
44
  yield TAIL
33
- insert_trailers(&block)
34
- yield TERM
45
+ yield_trailers(&block)
46
+ yield term
35
47
  end
36
48
 
49
+ # Close the response body if the response body supports it.
37
50
  def close
38
51
  @body.close if @body.respond_to?(:close)
39
52
  end
40
53
 
41
54
  private
42
55
 
43
- def insert_trailers(&block)
56
+ # Do nothing as this class does not support trailer headers.
57
+ def yield_trailers
44
58
  end
45
59
  end
46
60
 
61
+ # A body wrapper that emits chunked responses and also supports
62
+ # sending Trailer headers. Note that the response body provided to
63
+ # initialize must have a +trailers+ method that returns a hash
64
+ # of trailer headers, and the rack response itself should have a
65
+ # Trailer header listing the headers that the +trailers+ method
66
+ # will return.
47
67
  class TrailerBody < Body
48
68
  private
49
69
 
50
- def insert_trailers(&block)
70
+ # Yield strings for each trailer header.
71
+ def yield_trailers
51
72
  @body.trailers.each_pair do |k, v|
52
73
  yield "#{k}: #{v}\r\n"
53
74
  end
@@ -58,10 +79,11 @@ module Rack
58
79
  @app = app
59
80
  end
60
81
 
61
- # pre-HTTP/1.0 (informally "HTTP/0.9") HTTP requests did not have
62
- # a version (nor response headers)
82
+ # Whether the HTTP version supports chunked encoding (HTTP 1.1 does).
63
83
  def chunkable_version?(ver)
64
84
  case ver
85
+ # pre-HTTP/1.0 (informally "HTTP/0.9") HTTP requests did not have
86
+ # a version (nor response headers)
65
87
  when 'HTTP/1.0', nil, 'HTTP/0.9'
66
88
  false
67
89
  else
@@ -69,24 +91,27 @@ module Rack
69
91
  end
70
92
  end
71
93
 
94
+ # If the rack app returns a response that should have a body,
95
+ # but does not have Content-Length or Transfer-Encoding headers,
96
+ # modify the response to use chunked Transfer-Encoding.
72
97
  def call(env)
73
98
  status, headers, body = @app.call(env)
74
- headers = HeaderHash.new(headers)
99
+ headers = HeaderHash[headers]
100
+
101
+ if chunkable_version?(env[SERVER_PROTOCOL]) &&
102
+ !STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) &&
103
+ !headers[CONTENT_LENGTH] &&
104
+ !headers[TRANSFER_ENCODING]
75
105
 
76
- if ! chunkable_version?(env[SERVER_PROTOCOL]) ||
77
- STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) ||
78
- headers[CONTENT_LENGTH] ||
79
- headers[TRANSFER_ENCODING]
80
- [status, headers, body]
81
- else
82
- headers.delete(CONTENT_LENGTH)
83
106
  headers[TRANSFER_ENCODING] = 'chunked'
84
107
  if headers['Trailer']
85
- [status, headers, TrailerBody.new(body)]
108
+ body = TrailerBody.new(body)
86
109
  else
87
- [status, headers, Body.new(body)]
110
+ body = Body.new(body)
88
111
  end
89
112
  end
113
+
114
+ [status, headers, body]
90
115
  end
91
116
  end
92
117
  end
@@ -1,45 +1,49 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rack/body_proxy'
4
-
5
3
  module Rack
6
4
  # Rack::CommonLogger forwards every request to the given +app+, and
7
5
  # logs a line in the
8
6
  # {Apache common log format}[http://httpd.apache.org/docs/1.3/logs.html#common]
9
- # to the +logger+.
10
- #
11
- # If +logger+ is nil, CommonLogger will fall back +rack.errors+, which is
12
- # an instance of Rack::NullLogger.
13
- #
14
- # +logger+ can be any class, including the standard library Logger, and is
15
- # expected to have either +write+ or +<<+ method, which accepts the CommonLogger::FORMAT.
16
- # According to the SPEC, the error stream must also respond to +puts+
17
- # (which takes a single argument that responds to +to_s+), and +flush+
18
- # (which is called without arguments in order to make the error appear for
19
- # sure)
7
+ # to the configured logger.
20
8
  class CommonLogger
21
9
  # Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common
22
10
  #
23
11
  # lilith.local - - [07/Aug/2006 23:58:02 -0400] "GET / HTTP/1.1" 500 -
24
12
  #
25
13
  # %{%s - %s [%s] "%s %s%s %s" %d %s\n} %
26
- FORMAT = %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f\n}
14
+ #
15
+ # The actual format is slightly different than the above due to the
16
+ # separation of SCRIPT_NAME and PATH_INFO, and because the elapsed
17
+ # time in seconds is included at the end.
18
+ FORMAT = %{%s - %s [%s] "%s %s%s%s %s" %d %s %0.4f\n}
27
19
 
20
+ # +logger+ can be any object that supports the +write+ or +<<+ methods,
21
+ # which includes the standard library Logger. These methods are called
22
+ # with a single string argument, the log message.
23
+ # If +logger+ is nil, CommonLogger will fall back <tt>env['rack.errors']</tt>.
28
24
  def initialize(app, logger = nil)
29
25
  @app = app
30
26
  @logger = logger
31
27
  end
32
28
 
29
+ # Log all requests in common_log format after a response has been
30
+ # returned. Note that if the app raises an exception, the request
31
+ # will not be logged, so if exception handling middleware are used,
32
+ # they should be loaded after this middleware. Additionally, because
33
+ # the logging happens after the request body has been fully sent, any
34
+ # exceptions raised during the sending of the response body will
35
+ # cause the request not to be logged.
33
36
  def call(env)
34
37
  began_at = Utils.clock_time
35
- status, header, body = @app.call(env)
36
- header = Utils::HeaderHash.new(header)
37
- body = BodyProxy.new(body) { log(env, status, header, began_at) }
38
- [status, header, body]
38
+ status, headers, body = @app.call(env)
39
+ headers = Utils::HeaderHash[headers]
40
+ body = BodyProxy.new(body) { log(env, status, headers, began_at) }
41
+ [status, headers, body]
39
42
  end
40
43
 
41
44
  private
42
45
 
46
+ # Log the request to the configured logger.
43
47
  def log(env, status, header, began_at)
44
48
  length = extract_content_length(header)
45
49
 
@@ -48,6 +52,7 @@ module Rack
48
52
  env["REMOTE_USER"] || "-",
49
53
  Time.now.strftime("%d/%b/%Y:%H:%M:%S %z"),
50
54
  env[REQUEST_METHOD],
55
+ env[SCRIPT_NAME],
51
56
  env[PATH_INFO],
52
57
  env[QUERY_STRING].empty? ? "" : "?#{env[QUERY_STRING]}",
53
58
  env[SERVER_PROTOCOL],
@@ -55,10 +60,7 @@ module Rack
55
60
  length,
56
61
  Utils.clock_time - began_at ]
57
62
 
58
- msg.gsub!(/[^[:print:]\n]/) { |c| "\\x#{c.ord}" }
59
-
60
63
  logger = @logger || env[RACK_ERRORS]
61
-
62
64
  # Standard library logger doesn't support write but it supports << which actually
63
65
  # calls to write on the log device without formatting
64
66
  if logger.respond_to?(:write)
@@ -68,6 +70,8 @@ module Rack
68
70
  end
69
71
  end
70
72
 
73
+ # Attempt to determine the content length for the response to
74
+ # include it in the logged data.
71
75
  def extract_content_length(headers)
72
76
  value = headers[CONTENT_LENGTH]
73
77
  !value || value.to_s == '0' ? '-' : value
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rack/utils'
4
-
5
3
  module Rack
6
4
 
7
5
  # Middleware that enables conditional GET using If-None-Match and
@@ -21,11 +19,13 @@ module Rack
21
19
  @app = app
22
20
  end
23
21
 
22
+ # Return empty 304 response if the response has not been
23
+ # modified since the last request.
24
24
  def call(env)
25
25
  case env[REQUEST_METHOD]
26
26
  when "GET", "HEAD"
27
27
  status, headers, body = @app.call(env)
28
- headers = Utils::HeaderHash.new(headers)
28
+ headers = Utils::HeaderHash[headers]
29
29
  if status == 200 && fresh?(env, headers)
30
30
  status = 304
31
31
  headers.delete(CONTENT_TYPE)
@@ -43,28 +43,32 @@ module Rack
43
43
 
44
44
  private
45
45
 
46
+ # Return whether the response has not been modified since the
47
+ # last request.
46
48
  def fresh?(env, headers)
47
- modified_since = env['HTTP_IF_MODIFIED_SINCE']
48
- none_match = env['HTTP_IF_NONE_MATCH']
49
-
50
- return false unless modified_since || none_match
51
-
52
- success = true
53
- success &&= modified_since?(to_rfc2822(modified_since), headers) if modified_since
54
- success &&= etag_matches?(none_match, headers) if none_match
55
- success
49
+ # If-None-Match has priority over If-Modified-Since per RFC 7232
50
+ if none_match = env['HTTP_IF_NONE_MATCH']
51
+ etag_matches?(none_match, headers)
52
+ elsif (modified_since = env['HTTP_IF_MODIFIED_SINCE']) && (modified_since = to_rfc2822(modified_since))
53
+ modified_since?(modified_since, headers)
54
+ end
56
55
  end
57
56
 
57
+ # Whether the ETag response header matches the If-None-Match request header.
58
+ # If so, the request has not been modified.
58
59
  def etag_matches?(none_match, headers)
59
- etag = headers['ETag'] and etag == none_match
60
+ headers['ETag'] == none_match
60
61
  end
61
62
 
63
+ # Whether the Last-Modified response header matches the If-Modified-Since
64
+ # request header. If so, the request has not been modified.
62
65
  def modified_since?(modified_since, headers)
63
66
  last_modified = to_rfc2822(headers['Last-Modified']) and
64
- modified_since and
65
67
  modified_since >= last_modified
66
68
  end
67
69
 
70
+ # Return a Time object for the given string (which should be in RFC2822
71
+ # format), or nil if the string cannot be parsed.
68
72
  def to_rfc2822(since)
69
73
  # shortest possible valid date is the obsolete: 1 Nov 97 09:55 A
70
74
  # anything shorter is invalid, this avoids exceptions for common cases
@@ -73,8 +77,6 @@ module Rack
73
77
  # NOTE: there is no trivial way to write this in a non exception way
74
78
  # _rfc2822 returns a hash but is not that usable
75
79
  Time.rfc2822(since) rescue nil
76
- else
77
- nil
78
80
  end
79
81
  end
80
82
  end
@@ -1,11 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rack/utils'
4
- require 'rack/body_proxy'
5
-
6
3
  module Rack
7
4
 
8
- # Sets the Content-Length header on responses with fixed-length bodies.
5
+ # Sets the Content-Length header on responses that do not specify
6
+ # a Content-Length or Transfer-Encoding header. Note that this
7
+ # does not fix responses that have an invalid Content-Length
8
+ # header specified.
9
9
  class ContentLength
10
10
  include Rack::Utils
11
11
 
@@ -15,12 +15,11 @@ module Rack
15
15
 
16
16
  def call(env)
17
17
  status, headers, body = @app.call(env)
18
- headers = HeaderHash.new(headers)
18
+ headers = HeaderHash[headers]
19
19
 
20
20
  if !STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) &&
21
21
  !headers[CONTENT_LENGTH] &&
22
- !headers[TRANSFER_ENCODING] &&
23
- body.respond_to?(:to_ary)
22
+ !headers[TRANSFER_ENCODING]
24
23
 
25
24
  obody = body
26
25
  body, length = [], 0
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rack/utils'
4
-
5
3
  module Rack
6
4
 
7
5
  # Sets the Content-Type header on responses which don't have one.
@@ -9,7 +7,8 @@ module Rack
9
7
  # Builder Usage:
10
8
  # use Rack::ContentType, "text/plain"
11
9
  #
12
- # When no content type argument is provided, "text/html" is assumed.
10
+ # When no content type argument is provided, "text/html" is the
11
+ # default.
13
12
  class ContentType
14
13
  include Rack::Utils
15
14
 
@@ -19,7 +18,7 @@ module Rack
19
18
 
20
19
  def call(env)
21
20
  status, headers, body = @app.call(env)
22
- headers = Utils::HeaderHash.new(headers)
21
+ headers = Utils::HeaderHash[headers]
23
22
 
24
23
  unless STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i)
25
24
  headers[CONTENT_TYPE] ||= @content_type