rack 2.1.4.3 → 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 +68 -80
  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
data/lib/rack/deflater.rb CHANGED
@@ -2,48 +2,47 @@
2
2
 
3
3
  require "zlib"
4
4
  require "time" # for Time.httpdate
5
- require 'rack/utils'
6
-
7
- require_relative 'core_ext/regexp'
8
5
 
9
6
  module Rack
10
- # This middleware enables compression of http responses.
7
+ # This middleware enables content encoding of http responses,
8
+ # usually for purposes of compression.
9
+ #
10
+ # Currently supported encodings:
11
11
  #
12
- # Currently supported compression algorithms:
12
+ # * gzip
13
+ # * identity (no transformation)
13
14
  #
14
- # * gzip
15
- # * identity (no transformation)
15
+ # This middleware automatically detects when encoding is supported
16
+ # and allowed. For example no encoding is made when a cache
17
+ # directive of 'no-transform' is present, when the response status
18
+ # code is one that doesn't allow an entity body, or when the body
19
+ # is empty.
16
20
  #
17
- # The middleware automatically detects when compression is supported
18
- # and allowed. For example no transformation is made when a cache
19
- # directive of 'no-transform' is present, or when the response status
20
- # code is one that doesn't allow an entity body.
21
+ # Note that despite the name, Deflater does not support the +deflate+
22
+ # encoding.
21
23
  class Deflater
22
- using ::Rack::RegexpExtensions
24
+ (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4'
23
25
 
24
- ##
25
- # Creates Rack::Deflater middleware.
26
+ # Creates Rack::Deflater middleware. Options:
26
27
  #
27
- # [app] rack app instance
28
- # [options] hash of deflater options, i.e.
29
- # 'if' - a lambda enabling / disabling deflation based on returned boolean value
30
- # e.g use Rack::Deflater, :if => lambda { |*, body| sum=0; body.each { |i| sum += i.length }; sum > 512 }
31
- # 'include' - a list of content types that should be compressed
32
- # 'sync' - determines if the stream is going to be flushed after every chunk.
33
- # Flushing after every chunk reduces latency for
34
- # time-sensitive streaming applications, but hurts
35
- # compression and throughput. Defaults to `true'.
28
+ # :if :: a lambda enabling / disabling deflation based on returned boolean value
29
+ # (e.g <tt>use Rack::Deflater, :if => lambda { |*, body| sum=0; body.each { |i| sum += i.length }; sum > 512 }</tt>).
30
+ # However, be aware that calling `body.each` inside the block will break cases where `body.each` is not idempotent,
31
+ # such as when it is an +IO+ instance.
32
+ # :include :: a list of content types that should be compressed. By default, all content types are compressed.
33
+ # :sync :: determines if the stream is going to be flushed after every chunk. Flushing after every chunk reduces
34
+ # latency for time-sensitive streaming applications, but hurts compression and throughput.
35
+ # Defaults to +true+.
36
36
  def initialize(app, options = {})
37
37
  @app = app
38
-
39
38
  @condition = options[:if]
40
39
  @compressible_types = options[:include]
41
- @sync = options[:sync] == false ? false : true
40
+ @sync = options.fetch(:sync, true)
42
41
  end
43
42
 
44
43
  def call(env)
45
44
  status, headers, body = @app.call(env)
46
- headers = Utils::HeaderHash.new(headers)
45
+ headers = Utils::HeaderHash[headers]
47
46
 
48
47
  unless should_deflate?(env, status, headers, body)
49
48
  return [status, headers, body]
@@ -63,7 +62,7 @@ module Rack
63
62
  case encoding
64
63
  when "gzip"
65
64
  headers['Content-Encoding'] = "gzip"
66
- headers.delete('Content-Length')
65
+ headers.delete(CONTENT_LENGTH)
67
66
  mtime = headers["Last-Modified"]
68
67
  mtime = Time.httpdate(mtime).to_i if mtime
69
68
  [status, headers, GzipStream.new(body, mtime, @sync)]
@@ -72,49 +71,60 @@ module Rack
72
71
  when nil
73
72
  message = "An acceptable encoding for the requested resource #{request.fullpath} could not be found."
74
73
  bp = Rack::BodyProxy.new([message]) { body.close if body.respond_to?(:close) }
75
- [406, { 'Content-Type' => "text/plain", 'Content-Length' => message.length.to_s }, bp]
74
+ [406, { CONTENT_TYPE => "text/plain", CONTENT_LENGTH => message.length.to_s }, bp]
76
75
  end
77
76
  end
78
77
 
78
+ # Body class used for gzip encoded responses.
79
79
  class GzipStream
80
+ # Initialize the gzip stream. Arguments:
81
+ # body :: Response body to compress with gzip
82
+ # mtime :: The modification time of the body, used to set the
83
+ # modification time in the gzip header.
84
+ # sync :: Whether to flush each gzip chunk as soon as it is ready.
80
85
  def initialize(body, mtime, sync)
81
- @sync = sync
82
86
  @body = body
83
87
  @mtime = mtime
88
+ @sync = sync
84
89
  end
85
90
 
91
+ # Yield gzip compressed strings to the given block.
86
92
  def each(&block)
87
93
  @writer = block
88
94
  gzip = ::Zlib::GzipWriter.new(self)
89
95
  gzip.mtime = @mtime if @mtime
90
96
  @body.each { |part|
91
- len = gzip.write(part)
92
- # Flushing empty parts would raise Zlib::BufError.
93
- gzip.flush if @sync && len > 0
97
+ # Skip empty strings, as they would result in no output,
98
+ # and flushing empty parts would raise Zlib::BufError.
99
+ next if part.empty?
100
+
101
+ gzip.write(part)
102
+ gzip.flush if @sync
94
103
  }
95
104
  ensure
96
105
  gzip.close
97
- @writer = nil
98
106
  end
99
107
 
108
+ # Call the block passed to #each with the the gzipped data.
100
109
  def write(data)
101
110
  @writer.call(data)
102
111
  end
103
112
 
113
+ # Close the original body if possible.
104
114
  def close
105
115
  @body.close if @body.respond_to?(:close)
106
- @body = nil
107
116
  end
108
117
  end
109
118
 
110
119
  private
111
120
 
121
+ # Whether the body should be compressed.
112
122
  def should_deflate?(env, status, headers, body)
113
123
  # Skip compressing empty entity body responses and responses with
114
124
  # no-transform set.
115
125
  if Utils::STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) ||
116
126
  /\bno-transform\b/.match?(headers['Cache-Control'].to_s) ||
117
- (headers['Content-Encoding'] && headers['Content-Encoding'] !~ /\bidentity\b/)
127
+ headers['Content-Encoding']&.!~(/\bidentity\b/)
118
128
  return false
119
129
  end
120
130
 
@@ -1,9 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'time'
4
- require 'rack/utils'
5
- require 'rack/mime'
6
- require 'rack/files'
7
4
 
8
5
  module Rack
9
6
  # Rack::Directory serves entries below the +root+ given, according to the
@@ -14,8 +11,8 @@ module Rack
14
11
  # If +app+ is not specified, a Rack::Files of the same +root+ will be used.
15
12
 
16
13
  class Directory
17
- DIR_FILE = "<tr><td class='name'><a href='%s'>%s</a></td><td class='size'>%s</td><td class='type'>%s</td><td class='mtime'>%s</td></tr>"
18
- DIR_PAGE = <<-PAGE
14
+ DIR_FILE = "<tr><td class='name'><a href='%s'>%s</a></td><td class='size'>%s</td><td class='type'>%s</td><td class='mtime'>%s</td></tr>\n"
15
+ DIR_PAGE_HEADER = <<-PAGE
19
16
  <html><head>
20
17
  <title>%s</title>
21
18
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
@@ -36,33 +33,51 @@ table { width:100%%; }
36
33
  <th class='type'>Type</th>
37
34
  <th class='mtime'>Last Modified</th>
38
35
  </tr>
39
- %s
36
+ PAGE
37
+ DIR_PAGE_FOOTER = <<-PAGE
40
38
  </table>
41
39
  <hr />
42
40
  </body></html>
43
41
  PAGE
44
42
 
43
+ # Body class for directory entries, showing an index page with links
44
+ # to each file.
45
45
  class DirectoryBody < Struct.new(:root, :path, :files)
46
+ # Yield strings for each part of the directory entry
46
47
  def each
47
- show_path = Rack::Utils.escape_html(path.sub(/^#{root}/, ''))
48
- listings = files.map{|f| DIR_FILE % DIR_FILE_escape(*f) } * "\n"
49
- page = DIR_PAGE % [ show_path, show_path, listings ]
50
- page.each_line{|l| yield l }
48
+ show_path = Utils.escape_html(path.sub(/^#{root}/, ''))
49
+ yield(DIR_PAGE_HEADER % [ show_path, show_path ])
50
+
51
+ unless path.chomp('/') == root
52
+ yield(DIR_FILE % DIR_FILE_escape(files.call('..')))
53
+ end
54
+
55
+ Dir.foreach(path) do |basename|
56
+ next if basename.start_with?('.')
57
+ next unless f = files.call(basename)
58
+ yield(DIR_FILE % DIR_FILE_escape(f))
59
+ end
60
+
61
+ yield(DIR_PAGE_FOOTER)
51
62
  end
52
63
 
53
64
  private
54
- # Assumes url is already escaped.
55
- def DIR_FILE_escape url, *html
56
- [url, *html.map { |e| Utils.escape_html(e) }]
65
+
66
+ # Escape each element in the array of html strings.
67
+ def DIR_FILE_escape(htmls)
68
+ htmls.map { |e| Utils.escape_html(e) }
57
69
  end
58
70
  end
59
71
 
60
- attr_reader :root, :path
72
+ # The root of the directory hierarchy. Only requests for files and
73
+ # directories inside of the root directory are supported.
74
+ attr_reader :root
61
75
 
76
+ # Set the root directory and application for serving files.
62
77
  def initialize(root, app = nil)
63
78
  @root = ::File.expand_path(root)
64
- @app = app || Rack::Files.new(@root)
65
- @head = Rack::Head.new(lambda { |env| get env })
79
+ @app = app || Files.new(@root)
80
+ @head = Head.new(method(:get))
66
81
  end
67
82
 
68
83
  def call(env)
@@ -70,100 +85,101 @@ table { width:100%%; }
70
85
  @head.call env
71
86
  end
72
87
 
88
+ # Internals of request handling. Similar to call but does
89
+ # not remove body for HEAD requests.
73
90
  def get(env)
74
91
  script_name = env[SCRIPT_NAME]
75
92
  path_info = Utils.unescape_path(env[PATH_INFO])
76
93
 
77
- if bad_request = check_bad_request(path_info)
78
- bad_request
79
- elsif forbidden = check_forbidden(path_info)
80
- forbidden
94
+ if client_error_response = check_bad_request(path_info) || check_forbidden(path_info)
95
+ client_error_response
81
96
  else
82
97
  path = ::File.join(@root, path_info)
83
98
  list_path(env, path, path_info, script_name)
84
99
  end
85
100
  end
86
101
 
102
+ # Rack response to use for requests with invalid paths, or nil if path is valid.
87
103
  def check_bad_request(path_info)
88
104
  return if Utils.valid_path?(path_info)
89
105
 
90
106
  body = "Bad Request\n"
91
- size = body.bytesize
92
- return [400, { CONTENT_TYPE => "text/plain",
93
- CONTENT_LENGTH => size.to_s,
107
+ [400, { CONTENT_TYPE => "text/plain",
108
+ CONTENT_LENGTH => body.bytesize.to_s,
94
109
  "X-Cascade" => "pass" }, [body]]
95
110
  end
96
111
 
112
+ # Rack response to use for requests with paths outside the root, or nil if path is inside the root.
97
113
  def check_forbidden(path_info)
98
114
  return unless path_info.include? ".."
115
+ return if ::File.expand_path(::File.join(@root, path_info)).start_with?(@root)
99
116
 
100
117
  body = "Forbidden\n"
101
- size = body.bytesize
102
- return [403, { CONTENT_TYPE => "text/plain",
103
- CONTENT_LENGTH => size.to_s,
118
+ [403, { CONTENT_TYPE => "text/plain",
119
+ CONTENT_LENGTH => body.bytesize.to_s,
104
120
  "X-Cascade" => "pass" }, [body]]
105
121
  end
106
122
 
123
+ # Rack response to use for directories under the root.
107
124
  def list_directory(path_info, path, script_name)
108
- files = [['../', 'Parent Directory', '', '', '']]
109
-
110
125
  url_head = (script_name.split('/') + path_info.split('/')).map do |part|
111
- Rack::Utils.escape_path part
126
+ Utils.escape_path part
112
127
  end
113
128
 
114
- Dir.entries(path).reject { |e| e.start_with?('.') }.sort.each do |node|
115
- node = ::File.join path, node
116
- stat = stat(node)
129
+ # Globbing not safe as path could contain glob metacharacters
130
+ body = DirectoryBody.new(@root, path, ->(basename) do
131
+ stat = stat(::File.join(path, basename))
117
132
  next unless stat
118
- basename = ::File.basename(node)
119
- ext = ::File.extname(node)
120
133
 
121
- url = ::File.join(*url_head + [Rack::Utils.escape_path(basename)])
122
- size = stat.size
123
- type = stat.directory? ? 'directory' : Mime.mime_type(ext)
124
- size = stat.directory? ? '-' : filesize_format(size)
134
+ url = ::File.join(*url_head + [Utils.escape_path(basename)])
125
135
  mtime = stat.mtime.httpdate
126
- url << '/' if stat.directory?
127
- basename << '/' if stat.directory?
128
-
129
- files << [ url, basename, size, type, mtime ]
130
- end
131
-
132
- return [ 200, { CONTENT_TYPE => 'text/html; charset=utf-8' }, DirectoryBody.new(@root, path, files) ]
136
+ if stat.directory?
137
+ type = 'directory'
138
+ size = '-'
139
+ url << '/'
140
+ if basename == '..'
141
+ basename = 'Parent Directory'
142
+ else
143
+ basename << '/'
144
+ end
145
+ else
146
+ type = Mime.mime_type(::File.extname(basename))
147
+ size = filesize_format(stat.size)
148
+ end
149
+
150
+ [ url, basename, size, type, mtime ]
151
+ end)
152
+
153
+ [ 200, { CONTENT_TYPE => 'text/html; charset=utf-8' }, body ]
133
154
  end
134
155
 
135
- def stat(node)
136
- ::File.stat(node)
156
+ # File::Stat for the given path, but return nil for missing/bad entries.
157
+ def stat(path)
158
+ ::File.stat(path)
137
159
  rescue Errno::ENOENT, Errno::ELOOP
138
160
  return nil
139
161
  end
140
162
 
141
- # TODO: add correct response if not readable, not sure if 404 is the best
142
- # option
163
+ # Rack response to use for files and directories under the root.
164
+ # Unreadable and non-file, non-directory entries will get a 404 response.
143
165
  def list_path(env, path, path_info, script_name)
144
- stat = ::File.stat(path)
145
-
146
- if stat.readable?
166
+ if (stat = stat(path)) && stat.readable?
147
167
  return @app.call(env) if stat.file?
148
168
  return list_directory(path_info, path, script_name) if stat.directory?
149
- else
150
- raise Errno::ENOENT, 'No such file or directory'
151
169
  end
152
170
 
153
- rescue Errno::ENOENT, Errno::ELOOP
154
- return entity_not_found(path_info)
171
+ entity_not_found(path_info)
155
172
  end
156
173
 
174
+ # Rack response to use for unreadable and non-file, non-directory entries.
157
175
  def entity_not_found(path_info)
158
176
  body = "Entity not found: #{path_info}\n"
159
- size = body.bytesize
160
- return [404, { CONTENT_TYPE => "text/plain",
161
- CONTENT_LENGTH => size.to_s,
177
+ [404, { CONTENT_TYPE => "text/plain",
178
+ CONTENT_LENGTH => body.bytesize.to_s,
162
179
  "X-Cascade" => "pass" }, [body]]
163
180
  end
164
181
 
165
182
  # Stolen from Ramaze
166
-
167
183
  FILESIZE_FORMAT = [
168
184
  ['%.1fT', 1 << 40],
169
185
  ['%.1fG', 1 << 30],
@@ -171,6 +187,7 @@ table { width:100%%; }
171
187
  ['%.1fK', 1 << 10],
172
188
  ]
173
189
 
190
+ # Provide human readable file sizes
174
191
  def filesize_format(int)
175
192
  FILESIZE_FORMAT.each do |format, size|
176
193
  return format % (int.to_f / size) if int >= size
data/lib/rack/etag.rb CHANGED
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rack'
3
+ require_relative '../rack'
4
4
  require 'digest/sha2'
5
5
 
6
6
  module Rack
@@ -57,8 +57,7 @@ module Rack
57
57
  end
58
58
 
59
59
  def skip_caching?(headers)
60
- (headers[CACHE_CONTROL] && headers[CACHE_CONTROL].include?('no-cache')) ||
61
- headers.key?(ETAG_STRING) || headers.key?('Last-Modified')
60
+ headers.key?(ETAG_STRING) || headers.key?('Last-Modified')
62
61
  end
63
62
 
64
63
  def digest_body(body)
data/lib/rack/events.rb CHANGED
@@ -1,8 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rack/response'
4
- require 'rack/body_proxy'
5
-
6
3
  module Rack
7
4
  ### This middleware provides hooks to certain places in the request /
8
5
  # response lifecycle. This is so that middleware that don't need to filter
@@ -59,26 +56,26 @@ module Rack
59
56
 
60
57
  class Events
61
58
  module Abstract
62
- def on_start req, res
59
+ def on_start(req, res)
63
60
  end
64
61
 
65
- def on_commit req, res
62
+ def on_commit(req, res)
66
63
  end
67
64
 
68
- def on_send req, res
65
+ def on_send(req, res)
69
66
  end
70
67
 
71
- def on_finish req, res
68
+ def on_finish(req, res)
72
69
  end
73
70
 
74
- def on_error req, res, e
71
+ def on_error(req, res, e)
75
72
  end
76
73
  end
77
74
 
78
75
  class EventedBodyProxy < Rack::BodyProxy # :nodoc:
79
76
  attr_reader :request, :response
80
77
 
81
- def initialize body, request, response, handlers, &block
78
+ def initialize(body, request, response, handlers, &block)
82
79
  super(body, &block)
83
80
  @request = request
84
81
  @response = response
@@ -94,7 +91,7 @@ module Rack
94
91
  class BufferedResponse < Rack::Response::Raw # :nodoc:
95
92
  attr_reader :body
96
93
 
97
- def initialize status, headers, body
94
+ def initialize(status, headers, body)
98
95
  super(status, headers)
99
96
  @body = body
100
97
  end
@@ -102,12 +99,12 @@ module Rack
102
99
  def to_a; [status, headers, body]; end
103
100
  end
104
101
 
105
- def initialize app, handlers
102
+ def initialize(app, handlers)
106
103
  @app = app
107
104
  @handlers = handlers
108
105
  end
109
106
 
110
- def call env
107
+ def call(env)
111
108
  request = make_request env
112
109
  on_start request, nil
113
110
 
@@ -129,27 +126,27 @@ module Rack
129
126
 
130
127
  private
131
128
 
132
- def on_error request, response, e
129
+ def on_error(request, response, e)
133
130
  @handlers.reverse_each { |handler| handler.on_error request, response, e }
134
131
  end
135
132
 
136
- def on_commit request, response
133
+ def on_commit(request, response)
137
134
  @handlers.reverse_each { |handler| handler.on_commit request, response }
138
135
  end
139
136
 
140
- def on_start request, response
137
+ def on_start(request, response)
141
138
  @handlers.each { |handler| handler.on_start request, nil }
142
139
  end
143
140
 
144
- def on_finish request, response
141
+ def on_finish(request, response)
145
142
  @handlers.reverse_each { |handler| handler.on_finish request, response }
146
143
  end
147
144
 
148
- def make_request env
145
+ def make_request(env)
149
146
  Rack::Request.new env
150
147
  end
151
148
 
152
- def make_response status, headers, body
149
+ def make_response(status, headers, body)
153
150
  BufferedResponse.new status, headers, body
154
151
  end
155
152
  end
data/lib/rack/file.rb CHANGED
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rack/files'
3
+ require_relative 'files'
4
4
 
5
5
  module Rack
6
6
  File = Files