Permalink
Browse files

Merge commit 'core/master'

  • Loading branch information...
2 parents 835cfd6 + f58c3a4 commit 90c0938c76c77353e480960bdcfeefc26ac24dbe @scytrin scytrin committed Aug 7, 2008
View
@@ -30,6 +30,7 @@ def self.release
autoload :Cascade, "rack/cascade"
autoload :CommonLogger, "rack/commonlogger"
autoload :File, "rack/file"
+ autoload :Deflater, "rack/deflater"
autoload :Directory, "rack/directory"
autoload :ForwardRequest, "rack/recursive"
autoload :Handler, "rack/handler"
@@ -17,8 +17,8 @@ def self.dequote(str) # From WEBrick::HTTPUtils
ret
end
- def self.split_header_value(str) # From WEBrick::HTTPUtils
- str.scan(/((?:"(?:\\.|[^"])+?"|[^",]+)+)(?:,\s*|\Z)/n).collect{ |v| v[0] }
+ def self.split_header_value(str)
+ str.scan( /(\w+\=(?:"[^\"]+"|[^,]+))/n ).collect{ |v| v[0] }
end
def initialize
View
@@ -0,0 +1,63 @@
+require "zlib"
+require "stringio"
+
+module Rack
+
+class Deflater
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+
+ request = Request.new(env)
+
+ encoding = Utils.select_best_encoding(%w(gzip deflate identity), request.accept_encoding)
+
+ case encoding
+ when "gzip"
+ mtime = headers["Last-Modified"] || Time.now
+ [status, headers.merge("Content-Encoding" => "gzip"), self.class.gzip(body, mtime)]
+ when "deflate"
+ [status, headers.merge("Content-Encoding" => "deflate"), self.class.deflate(body)]
+ when "identity"
+ [status, headers, body]
+ when nil
+ message = "An acceptable encoding for the requested resource #{request.fullpath} could not be found."
+ [406, {"Content-Type" => "text/plain"}, message]
+ end
+ end
+
+ def self.gzip(body, mtime)
+ io = StringIO.new
+ gzip = Zlib::GzipWriter.new(io)
+ gzip.mtime = mtime
+
+ # TODO: Add streaming
+ body.each { |part| gzip << part }
+
+ gzip.close
+ return io.string
+ end
+
+ DEFLATE_ARGS = [
+ Zlib::DEFAULT_COMPRESSION,
+ # drop the zlib header which causes both Safari and IE to choke
+ -Zlib::MAX_WBITS,
+ Zlib::DEF_MEM_LEVEL,
+ Zlib::DEFAULT_STRATEGY
+ ]
+
+ # Loosely based on Mongrel's Deflate handler
+ def self.deflate(body)
+ deflater = Zlib::Deflate.new(*DEFLATE_ARGS)
+
+ # TODO: Add streaming
+ body.each { |part| deflater << part }
+
+ return deflater.finish
+ end
+end
+
+end
View
@@ -1,3 +1,5 @@
+require 'time'
+
module Rack
# Rack::Directory serves entries below the +root+ given, according to the
# path info of the Rack request. If a directory is found, the file's contents
@@ -51,7 +53,9 @@ def call(env)
def _call(env)
if env["PATH_INFO"].include? ".."
- return [403, {"Content-Type" => "text/plain"}, ["Forbidden\n"]]
+ body = "Forbidden\n"
+ size = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ return [403, {"Content-Type" => "text/plain","Content-Length" => size.to_s}, [body]]
end
@path = F.join(@root, Utils.unescape(env['PATH_INFO']))
@@ -77,8 +81,9 @@ def _call(env)
end
end
- return [404, {"Content-Type" => "text/plain"},
- ["Entity not found: #{env["PATH_INFO"]}\n"]]
+ body = "Entity not found: #{env["PATH_INFO"]}\n"
+ size = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ return [404, {"Content-Type" => "text/plain", "Content-Length" => size.to_s}, [body]]
end
def each
View
@@ -23,7 +23,9 @@ def call(env)
def _call(env)
if env["PATH_INFO"].include? ".."
- return [403, {"Content-Type" => "text/plain"}, ["Forbidden\n"]]
+ body = "Forbidden\n"
+ size = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ return [403, {"Content-Type" => "text/plain","Content-Length" => size.to_s}, [body]]
end
@path = F.join(@root, Utils.unescape(env["PATH_INFO"]))
@@ -36,8 +38,9 @@ def _call(env)
"Content-Length" => F.size(@path).to_s
}, self]
else
- return [404, {"Content-Type" => "text/plain"},
- ["File not found: #{env["PATH_INFO"]}\n"]]
+ body = "File not found: #{env["PATH_INFO"]}\n"
+ size = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ [404, {"Content-Type" => "text/plain", "Content-Length" => size.to_s}, [body]]
end
end
View
@@ -3,6 +3,8 @@ module Rack
# responses according to the Rack spec.
class Lint
+ STATUS_WITH_NO_ENTITY_BODY = (100..199).to_a << 204 << 304
+
def initialize(app)
@app = app
end
@@ -29,7 +31,11 @@ def assert(message, &block)
## A Rack application is an Ruby object (not a class) that
## responds to +call+.
- def call(env=nil)
+ def call(env=nil)
+ dup._call(env)
+ end
+
+ def _call(env)
## It takes exactly one argument, the *environment*
assert("No env given") { env }
check_env env
@@ -45,6 +51,7 @@ def call(env=nil)
check_headers headers
## and the *body*.
check_content_type status, headers
+ check_content_length status, headers
[status, headers, self]
end
@@ -57,7 +64,7 @@ def check_env(env)
env.instance_of? Hash
}
- ##
+ ##
## The environment is required to include these variables
## (adopted from PEP333), except when they'd be empty, but see
## below.
@@ -115,7 +122,7 @@ def check_env(env)
## and should be prefixed uniquely. The prefix <tt>rack.</tt>
## is reserved for use with the Rack core distribution and must
## not be used otherwise.
- ##
+ ##
%w[REQUEST_METHOD SERVER_NAME SERVER_PORT
QUERY_STRING
@@ -141,7 +148,7 @@ def check_env(env)
}
}
- ##
+ ##
## There are the following restrictions:
## * <tt>rack.version</tt> must be an array of Integers.
@@ -301,14 +308,16 @@ def close(*args)
## === The Status
def check_status(status)
- ## The status, if parsed as integer (+to_i+), must be bigger than 100.
- assert("Status must be >100 seen as integer") { status.to_i > 100 }
+ ## The status, if parsed as integer (+to_i+), must be greater than or equal to 100.
+ assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
end
## === The Headers
def check_headers(header)
## The header must respond to each, and yield values of key and value.
- assert("header should respond to #each") { header.respond_to? :each }
+ assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
+ header.respond_to? :each
+ }
header.each { |key, value|
## The header keys must be Strings.
assert("header key must be a string, was #{key.class}") {
@@ -323,12 +332,13 @@ def check_headers(header)
## but only contain keys that consist of
## letters, digits, <tt>_</tt> or <tt>-</tt> and start with a letter.
assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
- ##
+ ##
## The values of the header must respond to #each.
- assert("header values must respond to #each") { value.respond_to? :each }
+ assert("header values must respond to #each, but the value of " +
+ "'#{key}' doesn't (is #{value.class})") { value.respond_to? :each }
value.each { |item|
## The values passed on #each must be Strings
- assert("header values must consist of Strings") {
+ assert("header values must consist of Strings, but '#{key}' also contains a #{item.class}") {
item.instance_of?(String)
}
## and not contain characters below 037.
@@ -343,18 +353,69 @@ def check_headers(header)
def check_content_type(status, headers)
headers.each { |key, value|
## There must be a <tt>Content-Type</tt>, except when the
- ## +Status+ is 204 or 304, in which case there must be none
+ ## +Status+ is 1xx, 204 or 304, in which case there must be none
## given.
if key.downcase == "content-type"
- assert("Content-Type header found in #{status} response, not allowed"){
- not [204, 304].include? status.to_i
+ assert("Content-Type header found in #{status} response, not allowed") {
+ not STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
}
return
end
}
assert("No Content-Type header found") {
- [201, 204, 304].include? status.to_i
+ STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+ end
+
+ ## === The Content-Length
+ def check_content_length(status, headers)
+ chunked_response = false
+ headers.each { |key, value|
+ if key.downcase == 'transfer-encoding'
+ chunked_response = value.downcase != 'identity'
+ end
+ }
+
+ headers.each { |key, value|
+ if key.downcase == 'content-length'
+ ## There must be a <tt>Content-Length</tt>, except when the
+ ## +Status+ is 1xx, 204 or 304, in which case there must be none
+ ## given.
+ assert("Content-Length header found in #{status} response, not allowed") {
+ not STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+
+ assert('Content-Length header should not be used if body is chunked') {
+ not chunked_response
+ }
+
+ bytes = 0
+ string_body = true
+
+ @body.each { |part|
+ unless part.kind_of?(String)
+ string_body = false
+ break
+ end
+
+ bytes += (part.respond_to?(:bytesize) ? part.bytesize : part.size)
+ }
+
+ if string_body
+ assert("Content-Length header was #{value}, but should be #{bytes}") {
+ value == bytes.to_s
+ }
+ end
+
+ return
+ end
}
+
+ if [ String, Array ].include?(@body.class) && !chunked_response
+ assert('No Content-Length header found') {
+ STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
+ }
+ end
end
## === The Body
@@ -368,11 +429,11 @@ def each
}
yield part
}
- ##
+ ##
## If the Body responds to #close, it will be called after iteration.
# XXX howto: assert("Body has not been closed") { @closed }
- ##
+ ##
## The Body commonly is an Array of Strings, the application
## instance itself, or a File-like object.
end
View
@@ -193,5 +193,17 @@ def fullpath
path << "?" << query_string unless query_string.empty?
path
end
+
+ def accept_encoding
+ @env["HTTP_ACCEPT_ENCODING"].to_s.split(/,\s*/).map do |part|
+ m = /^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$/.match(part) # From WEBrick
+
+ if m
+ [m[1], (m[2] || 1.0).to_f]
+ else
+ raise "Invalid value for Accept-Encoding: #{part.inspect}"
+ end
+ end
+ end
end
end
View
@@ -25,7 +25,9 @@ def call(env)
req = Rack::Request.new(env)
message = Rack::Utils::HTTP_STATUS_CODES[status.to_i] || status.to_s
detail = env["rack.showstatus.detail"] || message
- [status, headers.merge("Content-Type" => "text/html"), [@template.result(binding)]]
+ body = @template.result(binding)
+ size = body.respond_to?(:bytesize) ? body.bytesize : body.size
+ [status, headers.merge("Content-Type" => "text/html", "Content-Length" => size.to_s), [body]]
else
[status, headers, body]
end
View
@@ -71,6 +71,36 @@ def escape_html(string)
end
module_function :escape_html
+ def select_best_encoding(available_encodings, accept_encoding)
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
+
+ expanded_accept_encoding =
+ accept_encoding.map { |m, q|
+ if m == "*"
+ (available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] }
+ else
+ [[m, q]]
+ end
+ }.inject([]) { |mem, list|
+ mem + list
+ }
+
+ encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m }
+
+ unless encoding_candidates.include?("identity")
+ encoding_candidates.push("identity")
+ end
+
+ expanded_accept_encoding.find_all { |m, q|
+ q == 0.0
+ }.each { |m, _|
+ encoding_candidates.delete(m)
+ }
+
+ return (encoding_candidates & available_encodings)[0]
+ end
+ module_function :select_best_encoding
+
# The recommended manner in which to implement a contexting application
# is to define a method #context in which a new Context is instantiated.
#
Oops, something went wrong.

0 comments on commit 90c0938

Please sign in to comment.