require "socket"
require "digest"
require "base64"
module Rack
module Utils
def self.unescape(str)
return "" if str.nil?
out = str.gsub("+", " ")
result = ""
i = 0
len = out.length
while i < len
ch = out[i]
if ch == "%" && i + 2 <= len - 1
hex = out[(i + 1)..(i + 2)]
if hex.length == 2 && hex =~ /\A[0-9a-fA-F]{2}\z/
result << hex.to_i(16).chr
i += 3
next
end
end
result << ch
i += 1
end
result
end
def self.escape(str)
out = ""
str.to_s.each_char do |ch|
if ch =~ /[A-Za-z0-9\-_.~]/
out << ch
elsif ch == " "
out << "+"
else
ch.bytes.each { |b| out << format("%%%02X", b) }
end
end
out
end
def self.parse_query(qs)
params = {}
return params if qs.nil? || qs.empty?
qs.split("&").each do |pair|
next if pair.empty?
key, value = pair.split("=", 2)
params[unescape(key)] = value.nil? ? "" : unescape(value)
end
params
end
def self.parse_nested_query(qs)
params = {}
return params if qs.nil? || qs.empty?
qs.split("&").each do |pair|
next if pair.empty?
key, value = pair.split("=", 2)
normalize_params(params, unescape(key), value.nil? ? "" : unescape(value))
end
params
end
def self.normalize_params(params, name, value)
return unless name =~ /\A([^\[\]]+)(.*)\z/
key = $1
after = $2
if after == ""
params[key] = value
elsif after == "[]"
(params[key] ||= []) << value
elsif after =~ /\A\[([^\[\]]+)\](.*)\z/
params[key] = {} unless params[key].is_a?(Hash)
normalize_params(params[key], $1 + $2, value)
else
params[key] = value
end
end
def self.parse_cookies(header)
cookies = {}
return cookies if header.nil? || header.empty?
header.split(/[;,]\s*/).each do |pair|
next if pair.empty?
key, value = pair.split("=", 2)
next if key.nil?
cookies[unescape(key.strip)] = value.nil? ? "" : unescape(value.strip)
end
cookies
end
def self.set_cookie_header(key, options)
value = options[:value].nil? ? "" : options[:value].to_s
parts = ["#{escape(key)}=#{escape(value)}"]
parts << "path=#{options[:path]}" if options[:path]
parts << "domain=#{options[:domain]}" if options[:domain]
parts << "expires=#{options[:expires]}" if options[:expires]
parts << "max-age=#{options[:max_age]}" unless options[:max_age].nil?
parts << "secure" if options[:secure]
parts << "HttpOnly" if options[:http_only]
parts.join("; ")
end
MIME_TYPES = {
".html" => "text/html",
".htm" => "text/html",
".txt" => "text/plain",
".css" => "text/css",
".js" => "application/javascript",
".json" => "application/json",
".xml" => "application/xml",
".png" => "image/png",
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".gif" => "image/gif",
".svg" => "image/svg+xml",
".ico" => "image/x-icon",
".pdf" => "application/pdf",
}
def self.mime_type(ext, default = "application/octet-stream")
MIME_TYPES[ext.to_s.downcase] || default
end
end
class Request
attr_reader :env
def initialize(env)
@env = env
end
def request_method
@env["REQUEST_METHOD"]
end
def path
@env["PATH_INFO"] || "/"
end
alias_method :path_info, :path
def script_name
@env["SCRIPT_NAME"] || ""
end
def query_string
@env["QUERY_STRING"] || ""
end
def content_type
ct = @env["CONTENT_TYPE"]
(ct.nil? || ct.empty?) ? nil : ct
end
def content_length
@env["CONTENT_LENGTH"]
end
def media_type
ct = content_type
ct.nil? ? nil : ct.split(";").first.strip.downcase
end
def scheme
return @env["rack.url_scheme"] if @env["rack.url_scheme"]
return "https" if @env["HTTPS"] == "on"
"http"
end
def ssl?
scheme == "https"
end
def host
if (h = @env["HTTP_HOST"])
h.split(":").first
else
@env["SERVER_NAME"] || "localhost"
end
end
def port
if (h = @env["HTTP_HOST"]) && h.include?(":")
h.split(":", 2)[1].to_i
elsif @env["SERVER_PORT"]
@env["SERVER_PORT"].to_i
else
scheme == "https" ? 443 : 80
end
end
def host_with_port
p = port
default = scheme == "https" ? 443 : 80
p == default ? host : "#{host}:#{p}"
end
def url
out = "#{scheme}://#{host_with_port}#{script_name}#{path}"
qs = query_string
out += "?#{qs}" unless qs.empty?
out
end
def body
input = @env["rack.input"]
return "" if input.nil?
return input if input.is_a?(String)
input.respond_to?(:read) ? (input.read || "") : input.to_s
end
def cookies
Utils.parse_cookies(@env["HTTP_COOKIE"])
end
def session
@env["rack.session"] || {}
end
def xhr?
@env["HTTP_X_REQUESTED_WITH"].to_s.downcase == "xmlhttprequest"
end
def query_params
Utils.parse_nested_query(query_string)
end
alias_method :GET, :query_params
def form_params
ct = @env["CONTENT_TYPE"] || ""
if !get? && ct.start_with?("application/x-www-form-urlencoded")
Utils.parse_nested_query(body)
else
{}
end
end
alias_method :POST, :form_params
def params
merged = query_params
form_params.each { |k, v| merged[k] = v }
if (pp = @env["rack.path_params"])
pp.each { |k, v| merged[k.to_s] = v }
end
merged
end
def headers
result = {}
@env.each do |key, value|
next unless key.start_with?("HTTP_")
name = key[5..-1].split("_").map { |w| w.capitalize }.join("-")
result[name] = value
end
result
end
def get?; request_method == "GET"; end
def post?; request_method == "POST"; end
def put?; request_method == "PUT"; end
def delete?; request_method == "DELETE"; end
def head?; request_method == "HEAD"; end
def patch?; request_method == "PATCH"; end
def self.parse_query(qs); Utils.parse_query(qs); end
def self.unescape(str); Utils.unescape(str); end
end
class Response
attr_accessor :status
attr_reader :headers
def initialize(body = [], status = 200, headers = {})
@status = status
@headers = {}
headers.each { |k, v| @headers[k] = v }
@body = []
@length = 0
if body.is_a?(String)
write(body) unless body.empty?
else
body.each { |chunk| write(chunk) }
end
end
def write(chunk)
str = chunk.to_s
@body << str
@length += str.bytesize
str
end
def [](key); @headers[key]; end
def []=(key, value); @headers[key] = value; end
def set_header(key, value); @headers[key] = value; end
def get_header(key); @headers[key]; end
def content_type; @headers["Content-Type"]; end
def content_type=(value); @headers["Content-Type"] = value; end
def redirect?; @status >= 300 && @status < 400; end
def ok?; @status == 200; end
def not_found?; @status == 404; end
def redirect(target, status = 302)
@status = status
@headers["Location"] = target
self
end
def set_cookie(key, value)
options = value.is_a?(Hash) ? value : { value: value }
header = Utils.set_cookie_header(key, options)
existing = @headers["Set-Cookie"]
@headers["Set-Cookie"] = existing.nil? || existing.empty? ? header : "#{existing}\n#{header}"
header
end
def delete_cookie(key, options = {})
set_cookie(key, {
value: "",
path: options[:path],
domain: options[:domain],
expires: "Thu, 01 Jan 1970 00:00:00 -0000",
max_age: "0",
})
end
def finish
unless @headers.key?("Content-Length") || no_body_status?
@headers["Content-Length"] = @length.to_s
end
[@status, @headers, @body]
end
alias_method :to_a, :finish
def body; @body; end
def length; @length; end
private
def no_body_status?
@status == 204 || @status == 304 || (@status >= 100 && @status < 200)
end
end
class Builder
def initialize
@middlewares = []
@app = nil
yield self if block_given?
end
def use(middleware, *args)
@middlewares << [middleware, args]
end
def run(app)
@app = app
end
def to_app
raise "missing run: no app given to Rack::Builder" if @app.nil?
app = @app
@middlewares.reverse.each do |middleware, args|
app = middleware.new(app, *args)
end
app
end
def self.app(&block)
new(&block).to_app
end
end
class Logger
def initialize(app, io = nil)
@app = app
@io = io || $stderr
end
def call(env)
method = env["REQUEST_METHOD"]
path = env["PATH_INFO"]
status, headers, body = @app.call(env)
@io.puts("[Rack::Logger] #{method} #{path} -> #{status}")
[status, headers, body]
end
end
class CommonLogger
def initialize(app, logger = nil)
@app = app
@logger = logger || $stderr
end
def call(env)
status, headers, body = @app.call(env)
log(env, status, headers, body)
[status, headers, body]
end
private
def log(env, status, headers, body)
length = extract_length(headers, body)
line = format(
"%s - %s [%s] \"%s %s %s\" %d %s\n",
env["REMOTE_ADDR"] || "-",
env["REMOTE_USER"] || "-",
env["rack.request.time"] || "-", env["REQUEST_METHOD"],
env["PATH_INFO"],
env["SERVER_PROTOCOL"] || "HTTP/1.1",
status,
length.nil? ? "-" : length.to_s
)
write(line)
end
def write(line)
if @logger.respond_to?(:write)
@logger.write(line)
else
@logger << line
end
end
def extract_length(headers, body)
cl = headers["Content-Length"]
return cl.to_i if cl
total = 0
body.each { |c| total += c.to_s.bytesize }
total
end
end
class Static
def initialize(app = nil, options = {})
@app = app
@root = options[:root] || "."
@urls = options[:urls] end
def call(env)
path = env["PATH_INFO"] || "/"
if match?(path) && (file = resolve(path))
serve(file)
elsif @app
@app.call(env)
else
not_found
end
end
private
def match?(path)
return true if @urls.nil?
@urls.any? { |prefix| path.start_with?(prefix) }
end
def resolve(path)
return nil if path.include?("..")
rel = path.sub(/\A\/+/, "")
full = rel.empty? ? @root : File.join(@root, rel)
File.exist?(full) && File.file?(full) ? full : nil
end
def serve(file)
data = File.read(file)
ctype = Utils.mime_type(File.extname(file))
[200,
{ "Content-Type" => ctype, "Content-Length" => data.bytesize.to_s },
[data]]
end
def not_found
body = "File not found"
[404,
{ "Content-Type" => "text/plain", "Content-Length" => body.bytesize.to_s },
[body]]
end
end
module Session
class Cookie
require "json"
def initialize(app, options = {})
@app = app
@secret = options[:secret] || "change_me"
@key = options[:key] || "rack.session"
@path = options[:path] || "/"
end
def call(env)
env["rack.session"] = load_session(env)
status, headers, body = @app.call(env)
commit(env, headers)
[status, headers, body]
end
def encode(session)
payload = Base64.strict_encode64(JSON.generate(session))
"#{payload}--#{sign(payload)}"
end
def decode(cookie)
return {} if cookie.nil? || cookie.empty?
payload, digest = cookie.split("--", 2)
return {} if payload.nil? || digest.nil?
return {} unless secure_equal(sign(payload), digest)
JSON.parse(Base64.strict_decode64(payload))
rescue
{}
end
private
def load_session(env)
cookie = Utils.parse_cookies(env["HTTP_COOKIE"])[@key]
decode(cookie)
end
def commit(env, headers)
session = env["rack.session"] || {}
cookie = "#{@key}=#{Utils.escape(encode(session))}; path=#{@path}; HttpOnly"
existing = headers["Set-Cookie"]
headers["Set-Cookie"] =
existing.nil? || existing.empty? ? cookie : "#{existing}\n#{cookie}"
end
def sign(payload)
Digest::SHA1.hexdigest(@secret + payload)
end
def secure_equal(a, b)
return false unless a.length == b.length
mismatch = 0
i = 0
while i < a.length
mismatch |= (a.bytes[i] ^ b.bytes[i])
i += 1
end
mismatch == 0
end
end
end
class Router
class Route
attr_reader :method, :segments, :block, :wildcard
def initialize(method, path, block)
@method = method
@block = block
@wildcard = false
@segments = path.split("/").map do |seg|
if seg == "*"
@wildcard = true
[:splat, "splat"]
elsif seg.start_with?(":")
[:param, seg[1..-1]]
else
[:literal, seg]
end
end
end
def match(path)
parts = path.split("/")
params = {}
i = 0
while i < @segments.length
kind, name = @segments[i]
if kind == :splat
params["splat"] = parts[i..-1].join("/")
return params
end
return nil if i >= parts.length
case kind
when :literal
return nil unless parts[i] == name
when :param
params[name] = parts[i]
end
i += 1
end
parts.length == @segments.length ? params : nil
end
def specificity
literals = @segments.count { |k, _| k == :literal }
params = @segments.count { |k, _| k == :param }
[@wildcard ? 0 : 1, literals, params]
end
end
def initialize
@routes = { "GET" => [], "POST" => [], "PUT" => [], "DELETE" => [],
"PATCH" => [], "HEAD" => [] }
yield self if block_given?
end
def get(path, &block); add("GET", path, block); end
def post(path, &block); add("POST", path, block); end
def put(path, &block); add("PUT", path, block); end
def delete(path, &block); add("DELETE", path, block); end
def patch(path, &block); add("PATCH", path, block); end
def call(env)
method = env["REQUEST_METHOD"]
path = env["PATH_INFO"] || "/"
list = @routes[method] || []
best = nil
best_params = nil
list.each do |route|
params = route.match(path)
next if params.nil?
if best.nil? || compare_specificity(route, best) > 0
best = route
best_params = params
end
end
return not_found if best.nil?
env["rack.path_params"] = best_params
result = best.block.call(env, best_params)
coerce(result)
end
private
def add(method, path, block)
(@routes[method] ||= []) << Route.new(method, path, block)
end
def compare_specificity(a, b)
sa = a.specificity
sb = b.specificity
i = 0
while i < sa.length
return sa[i] <=> sb[i] unless sa[i] == sb[i]
i += 1
end
0
end
def coerce(result)
if result.is_a?(String)
[200, { "Content-Type" => "text/html" }, [result]]
elsif result.is_a?(Array) && result.length == 3
result
else
[200, { "Content-Type" => "text/html" }, [result.to_s]]
end
end
def not_found
[404, { "Content-Type" => "text/plain" }, ["Not Found"]]
end
end
class MockResponse
attr_reader :status, :headers, :body
def initialize(status, headers, body_enum)
@status = status
@headers = headers
chunks = []
body_enum.each { |c| chunks << c.to_s }
@body = chunks.join
end
def [](key); @headers[key]; end
def ok?; @status == 200; end
def redirect?; @status >= 300 && @status < 400; end
def not_found?; @status == 404; end
def location; @headers["Location"]; end
def content_type; @headers["Content-Type"]; end
def cookies
raw = @headers["Set-Cookie"]
return {} if raw.nil? || raw.empty?
jar = {}
raw.split("\n").each do |line|
pair = line.split(";").first
next if pair.nil?
key, value = pair.split("=", 2)
jar[Utils.unescape(key.strip)] = value.nil? ? "" : Utils.unescape(value.strip)
end
jar
end
end
class MockRequest
def initialize(app)
@app = app
end
def get(path, opts = {}); request("GET", path, opts); end
def post(path, opts = {}); request("POST", path, opts); end
def put(path, opts = {}); request("PUT", path, opts); end
def delete(path, opts = {}); request("DELETE", path, opts); end
def patch(path, opts = {}); request("PATCH", path, opts); end
def head(path, opts = {}); request("HEAD", path, opts); end
def request(method, path, opts = {})
env = self.class.env_for(method, path, opts)
status, headers, body = @app.call(env)
MockResponse.new(status, headers, body)
end
def self.env_for(method, path, opts = {})
uri, query = path.split("?", 2)
env = {
"REQUEST_METHOD" => method,
"PATH_INFO" => uri,
"QUERY_STRING" => (query || ""),
"SERVER_NAME" => "example.org",
"SERVER_PORT" => "80",
"SERVER_PROTOCOL" => "HTTP/1.1",
"rack.url_scheme" => "http",
"rack.input" => "",
}
opts.each do |k, v|
key = k.to_s
if key == "input" || key == "rack.input"
env["rack.input"] = v
env["CONTENT_LENGTH"] = v.to_s.bytesize.to_s
else
env[key] = v
end
end
env
end
end
module Handler
class Simple
def self.run(app, port = 9292, host = "127.0.0.1")
server = TCPServer.new(host, port)
loop do
conn = server.accept
begin
env = parse_request(conn)
if env.nil?
conn.close
next
end
status, headers, body = app.call(env)
write_response(conn, status, headers, body)
rescue => e
$stderr.puts("[Rack::Handler::Simple] error: #{e}")
end
conn.close
end
ensure
server.close if server
end
def self.parse_request(conn)
request_line = conn.gets
return nil if request_line.nil?
method, target, _version = request_line.strip.split(" ")
return nil if method.nil? || target.nil?
path, query = target.split("?", 2)
env = {
"REQUEST_METHOD" => method,
"PATH_INFO" => path,
"QUERY_STRING" => (query || ""),
"SERVER_PROTOCOL" => "HTTP/1.1",
"rack.url_scheme" => "http",
}
content_length = 0
while (line = conn.gets) && line != "\r\n" && line != "\n"
name, value = line.strip.split(": ", 2)
next if name.nil?
value = "" if value.nil?
up = name.upcase.gsub("-", "_")
if up == "CONTENT_LENGTH"
env["CONTENT_LENGTH"] = value
content_length = value.to_i
elsif up == "CONTENT_TYPE"
env["CONTENT_TYPE"] = value
else
env["HTTP_#{up}"] = value
end
end
env["rack.input"] = content_length > 0 ? (conn.read(content_length) || "") : ""
env
end
def self.write_response(conn, status, headers, body)
chunks = []
body.each { |chunk| chunks << chunk.to_s }
payload = chunks.join
reason = REASONS[status] || "OK"
out = "HTTP/1.1 #{status} #{reason}\r\n"
wrote_length = false
headers.each do |key, value|
value.to_s.split("\n").each do |v|
wrote_length = true if key.downcase == "content-length"
out << "#{key}: #{v}\r\n"
end
end
out << "Content-Length: #{payload.bytesize}\r\n" unless wrote_length
out << "Connection: close\r\n"
out << "\r\n"
out << payload
conn.write(out)
end
REASONS = {
200 => "OK",
201 => "Created",
204 => "No Content",
301 => "Moved Permanently",
302 => "Found",
304 => "Not Modified",
400 => "Bad Request",
404 => "Not Found",
405 => "Method Not Allowed",
500 => "Internal Server Error",
}
end
end
end