rack 2.1.3 → 2.2.1

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 +613 -1
  3. data/CONTRIBUTING.md +136 -0
  4. data/README.rdoc +83 -39
  5. data/Rakefile +14 -7
  6. data/{SPEC → SPEC.rdoc} +26 -1
  7. data/lib/rack.rb +7 -16
  8. data/lib/rack/auth/abstract/request.rb +0 -2
  9. data/lib/rack/auth/basic.rb +3 -3
  10. data/lib/rack/auth/digest/md5.rb +4 -4
  11. data/lib/rack/auth/digest/request.rb +3 -3
  12. data/lib/rack/body_proxy.rb +13 -9
  13. data/lib/rack/builder.rb +77 -8
  14. data/lib/rack/cascade.rb +23 -8
  15. data/lib/rack/chunked.rb +48 -23
  16. data/lib/rack/common_logger.rb +25 -18
  17. data/lib/rack/conditional_get.rb +18 -16
  18. data/lib/rack/content_length.rb +6 -7
  19. data/lib/rack/content_type.rb +3 -4
  20. data/lib/rack/deflater.rb +45 -35
  21. data/lib/rack/directory.rb +77 -59
  22. data/lib/rack/etag.rb +2 -3
  23. data/lib/rack/events.rb +15 -18
  24. data/lib/rack/file.rb +1 -1
  25. data/lib/rack/files.rb +96 -56
  26. data/lib/rack/handler/cgi.rb +1 -4
  27. data/lib/rack/handler/fastcgi.rb +1 -3
  28. data/lib/rack/handler/lsws.rb +1 -3
  29. data/lib/rack/handler/scgi.rb +1 -3
  30. data/lib/rack/handler/thin.rb +15 -11
  31. data/lib/rack/handler/webrick.rb +12 -5
  32. data/lib/rack/head.rb +0 -2
  33. data/lib/rack/lint.rb +57 -14
  34. data/lib/rack/lobster.rb +3 -5
  35. data/lib/rack/lock.rb +0 -1
  36. data/lib/rack/mock.rb +22 -4
  37. data/lib/rack/multipart.rb +1 -1
  38. data/lib/rack/multipart/generator.rb +11 -6
  39. data/lib/rack/multipart/parser.rb +7 -15
  40. data/lib/rack/multipart/uploaded_file.rb +13 -7
  41. data/lib/rack/query_parser.rb +7 -8
  42. data/lib/rack/recursive.rb +1 -1
  43. data/lib/rack/reloader.rb +1 -3
  44. data/lib/rack/request.rb +182 -76
  45. data/lib/rack/response.rb +62 -19
  46. data/lib/rack/rewindable_input.rb +0 -1
  47. data/lib/rack/runtime.rb +3 -3
  48. data/lib/rack/sendfile.rb +0 -3
  49. data/lib/rack/server.rb +9 -8
  50. data/lib/rack/session/abstract/id.rb +20 -18
  51. data/lib/rack/session/cookie.rb +2 -3
  52. data/lib/rack/session/pool.rb +1 -1
  53. data/lib/rack/show_exceptions.rb +2 -4
  54. data/lib/rack/show_status.rb +1 -3
  55. data/lib/rack/static.rb +13 -6
  56. data/lib/rack/tempfile_reaper.rb +0 -2
  57. data/lib/rack/urlmap.rb +1 -4
  58. data/lib/rack/utils.rb +58 -54
  59. data/lib/rack/version.rb +29 -0
  60. data/rack.gemspec +31 -29
  61. metadata +11 -12
@@ -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],
@@ -65,6 +70,8 @@ module Rack
65
70
  end
66
71
  end
67
72
 
73
+ # Attempt to determine the content length for the response to
74
+ # include it in the logged data.
68
75
  def extract_content_length(headers)
69
76
  value = headers[CONTENT_LENGTH]
70
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
@@ -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,99 +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
- 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))
116
132
  next unless stat
117
- basename = ::File.basename(node)
118
- ext = ::File.extname(node)
119
133
 
120
- url = ::File.join(*url_head + [Rack::Utils.escape_path(basename)])
121
- size = stat.size
122
- type = stat.directory? ? 'directory' : Mime.mime_type(ext)
123
- size = stat.directory? ? '-' : filesize_format(size)
134
+ url = ::File.join(*url_head + [Utils.escape_path(basename)])
124
135
  mtime = stat.mtime.httpdate
125
- url << '/' if stat.directory?
126
- basename << '/' if stat.directory?
127
-
128
- files << [ url, basename, size, type, mtime ]
129
- end
130
-
131
- 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 ]
132
154
  end
133
155
 
134
- def stat(node)
135
- ::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)
136
159
  rescue Errno::ENOENT, Errno::ELOOP
137
160
  return nil
138
161
  end
139
162
 
140
- # TODO: add correct response if not readable, not sure if 404 is the best
141
- # 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.
142
165
  def list_path(env, path, path_info, script_name)
143
- stat = ::File.stat(path)
144
-
145
- if stat.readable?
166
+ if (stat = stat(path)) && stat.readable?
146
167
  return @app.call(env) if stat.file?
147
168
  return list_directory(path_info, path, script_name) if stat.directory?
148
- else
149
- raise Errno::ENOENT, 'No such file or directory'
150
169
  end
151
170
 
152
- rescue Errno::ENOENT, Errno::ELOOP
153
- return entity_not_found(path_info)
171
+ entity_not_found(path_info)
154
172
  end
155
173
 
174
+ # Rack response to use for unreadable and non-file, non-directory entries.
156
175
  def entity_not_found(path_info)
157
176
  body = "Entity not found: #{path_info}\n"
158
- size = body.bytesize
159
- return [404, { CONTENT_TYPE => "text/plain",
160
- CONTENT_LENGTH => size.to_s,
177
+ [404, { CONTENT_TYPE => "text/plain",
178
+ CONTENT_LENGTH => body.bytesize.to_s,
161
179
  "X-Cascade" => "pass" }, [body]]
162
180
  end
163
181
 
164
182
  # Stolen from Ramaze
165
-
166
183
  FILESIZE_FORMAT = [
167
184
  ['%.1fT', 1 << 40],
168
185
  ['%.1fG', 1 << 30],
@@ -170,6 +187,7 @@ table { width:100%%; }
170
187
  ['%.1fK', 1 << 10],
171
188
  ]
172
189
 
190
+ # Provide human readable file sizes
173
191
  def filesize_format(int)
174
192
  FILESIZE_FORMAT.each do |format, size|
175
193
  return format % (int.to_f / size) if int >= size