summaryrefslogtreecommitdiff
path: root/lib/webrick/httpservlet
diff options
context:
space:
mode:
Diffstat (limited to 'lib/webrick/httpservlet')
-rw-r--r--lib/webrick/httpservlet/abstract.rb11
-rw-r--r--lib/webrick/httpservlet/cgi_runner.rb5
-rw-r--r--lib/webrick/httpservlet/cgihandler.rb32
-rw-r--r--lib/webrick/httpservlet/erbhandler.rb7
-rw-r--r--lib/webrick/httpservlet/filehandler.rb201
-rw-r--r--lib/webrick/httpservlet/prochandler.rb16
6 files changed, 185 insertions, 87 deletions
diff --git a/lib/webrick/httpservlet/abstract.rb b/lib/webrick/httpservlet/abstract.rb
index 0d5c5ae48d..bccb091861 100644
--- a/lib/webrick/httpservlet/abstract.rb
+++ b/lib/webrick/httpservlet/abstract.rb
@@ -1,3 +1,4 @@
+# frozen_string_literal: false
#
# httpservlet.rb -- HTTPServlet Module
#
@@ -8,11 +9,9 @@
#
# $IPR: abstract.rb,v 1.24 2003/07/11 11:16:46 gotoyuzo Exp $
-require 'thread'
-
-require 'webrick/htmlutils'
-require 'webrick/httputils'
-require 'webrick/httpstatus'
+require_relative '../htmlutils'
+require_relative '../httputils'
+require_relative '../httpstatus'
module WEBrick
module HTTPServlet
@@ -54,7 +53,7 @@ module WEBrick
# Servlets can be configured via initialize. The first argument is the
# HTTP server the servlet is being initialized for.
#
- # class Configureable < Simple
+ # class Configurable < Simple
# def initialize server, color, size
# super server
# @color = color
diff --git a/lib/webrick/httpservlet/cgi_runner.rb b/lib/webrick/httpservlet/cgi_runner.rb
index 32ecb6fe00..0398c16749 100644
--- a/lib/webrick/httpservlet/cgi_runner.rb
+++ b/lib/webrick/httpservlet/cgi_runner.rb
@@ -1,3 +1,4 @@
+# frozen_string_literal: false
#
# cgi_runner.rb -- CGI launcher.
#
@@ -22,11 +23,11 @@ STDIN.binmode
len = sysread(STDIN, 8).to_i
out = sysread(STDIN, len)
-STDOUT.reopen(open(out, "w"))
+STDOUT.reopen(File.open(out, "w"))
len = sysread(STDIN, 8).to_i
err = sysread(STDIN, len)
-STDERR.reopen(open(err, "w"))
+STDERR.reopen(File.open(err, "w"))
len = sysread(STDIN, 8).to_i
dump = sysread(STDIN, len)
diff --git a/lib/webrick/httpservlet/cgihandler.rb b/lib/webrick/httpservlet/cgihandler.rb
index 1976ae6948..981f649750 100644
--- a/lib/webrick/httpservlet/cgihandler.rb
+++ b/lib/webrick/httpservlet/cgihandler.rb
@@ -1,3 +1,4 @@
+# frozen_string_literal: false
#
# cgihandler.rb -- CGIHandler Class
#
@@ -10,15 +11,26 @@
require 'rbconfig'
require 'tempfile'
-require 'webrick/config'
-require 'webrick/httpservlet/abstract'
+require_relative '../config'
+require_relative 'abstract'
module WEBrick
module HTTPServlet
+ ##
+ # Servlet for handling CGI scripts
+ #
+ # Example:
+ #
+ # server.mount('/cgi/my_script', WEBrick::HTTPServlet::CGIHandler,
+ # '/path/to/my_script')
+
class CGIHandler < AbstractServlet
- Ruby = RbConfig.ruby
- CGIRunner = "\"#{Ruby}\" \"#{WEBrick::Config::LIBDIR}/httpservlet/cgi_runner.rb\""
+ Ruby = RbConfig.ruby # :nodoc:
+ CGIRunner = "\"#{Ruby}\" \"#{WEBrick::Config::LIBDIR}/httpservlet/cgi_runner.rb\"" # :nodoc:
+
+ ##
+ # Creates a new CGI script servlet for the script at +name+
def initialize(server, name)
super(server, name)
@@ -27,10 +39,9 @@ module WEBrick
@cgicmd = "#{CGIRunner} #{server[:CGIInterpreter]}"
end
- def do_GET(req, res)
- data = nil
- status = -1
+ # :stopdoc:
+ def do_GET(req, res)
cgi_in = IO::popen(@cgicmd, "wb")
cgi_out = Tempfile.new("webrick.cgiout.", @tempdir, mode: IO::BINARY)
cgi_out.set_encoding("ASCII-8BIT")
@@ -41,6 +52,7 @@ module WEBrick
meta = req.meta_vars
meta["SCRIPT_FILENAME"] = @script_filename
meta["PATH"] = @config[:CGIPathEnv]
+ meta.delete("HTTP_PROXY")
if /mswin|bccwin|mingw/ =~ RUBY_PLATFORM
meta["SystemRoot"] = ENV["SystemRoot"]
end
@@ -53,9 +65,7 @@ module WEBrick
cgi_in.write("%8d" % dump.bytesize)
cgi_in.write(dump)
- if req.body and req.body.bytesize > 0
- cgi_in.write(req.body)
- end
+ req.body { |chunk| cgi_in.write(chunk) }
ensure
cgi_in.close
status = $?.exitstatus
@@ -102,6 +112,8 @@ module WEBrick
res.body = body
end
alias do_POST do_GET
+
+ # :startdoc:
end
end
diff --git a/lib/webrick/httpservlet/erbhandler.rb b/lib/webrick/httpservlet/erbhandler.rb
index 34b4b9e68b..cd09e5f216 100644
--- a/lib/webrick/httpservlet/erbhandler.rb
+++ b/lib/webrick/httpservlet/erbhandler.rb
@@ -1,3 +1,4 @@
+# frozen_string_literal: false
#
# erbhandler.rb -- ERBHandler Class
#
@@ -8,7 +9,7 @@
#
# $IPR: erbhandler.rb,v 1.25 2003/02/24 19:25:31 gotoyuzo Exp $
-require 'webrick/httpservlet/abstract.rb'
+require_relative 'abstract'
require 'erb'
@@ -52,11 +53,11 @@ module WEBrick
raise HTTPStatus::Forbidden, "ERBHandler cannot work."
end
begin
- data = open(@script_filename){|io| io.read }
+ data = File.open(@script_filename, &:read)
res.body = evaluate(ERB.new(data), req, res)
res['content-type'] ||=
HTTPUtils::mime_type(@script_filename, @config[:MimeTypes])
- rescue StandardError => ex
+ rescue StandardError
raise
rescue Exception => ex
@logger.error(ex)
diff --git a/lib/webrick/httpservlet/filehandler.rb b/lib/webrick/httpservlet/filehandler.rb
index 8736f5773a..601882ef4c 100644
--- a/lib/webrick/httpservlet/filehandler.rb
+++ b/lib/webrick/httpservlet/filehandler.rb
@@ -1,3 +1,4 @@
+# frozen_string_literal: false
#
# filehandler.rb -- FileHandler Module
#
@@ -8,22 +9,38 @@
#
# $IPR: filehandler.rb,v 1.44 2003/06/07 01:34:51 gotoyuzo Exp $
-require 'thread'
require 'time'
-require 'webrick/htmlutils'
-require 'webrick/httputils'
-require 'webrick/httpstatus'
+require_relative '../htmlutils'
+require_relative '../httputils'
+require_relative '../httpstatus'
module WEBrick
module HTTPServlet
+ ##
+ # Servlet for serving a single file. You probably want to use the
+ # FileHandler servlet instead as it handles directories and fancy indexes.
+ #
+ # Example:
+ #
+ # server.mount('/my_page.txt', WEBrick::HTTPServlet::DefaultFileHandler,
+ # '/path/to/my_page.txt')
+ #
+ # This servlet handles If-Modified-Since and Range requests.
+
class DefaultFileHandler < AbstractServlet
+
+ ##
+ # Creates a DefaultFileHandler instance for the file at +local_path+.
+
def initialize(server, local_path)
super(server, local_path)
@local_path = local_path
end
+ # :stopdoc:
+
def do_GET(req, res)
st = File::stat(@local_path)
mtime = st.mtime
@@ -38,9 +55,9 @@ module WEBrick
else
mtype = HTTPUtils::mime_type(@local_path, @config[:MimeTypes])
res['content-type'] = mtype
- res['content-length'] = st.size
+ res['content-length'] = st.size.to_s
res['last-modified'] = mtime.httpdate
- res.body = open(@local_path, "rb")
+ res.body = File.open(@local_path, "rb")
end
end
@@ -69,47 +86,66 @@ module WEBrick
return false
end
+ # returns a lambda for webrick/httpresponse.rb send_body_proc
+ def multipart_body(body, parts, boundary, mtype, filesize)
+ lambda do |socket|
+ begin
+ begin
+ first = parts.shift
+ last = parts.shift
+ socket.write(
+ "--#{boundary}#{CRLF}" \
+ "Content-Type: #{mtype}#{CRLF}" \
+ "Content-Range: bytes #{first}-#{last}/#{filesize}#{CRLF}" \
+ "#{CRLF}"
+ )
+
+ begin
+ IO.copy_stream(body, socket, last - first + 1, first)
+ rescue NotImplementedError
+ body.seek(first, IO::SEEK_SET)
+ IO.copy_stream(body, socket, last - first + 1)
+ end
+ socket.write(CRLF)
+ end while parts[0]
+ socket.write("--#{boundary}--#{CRLF}")
+ ensure
+ body.close
+ end
+ end
+ end
+
def make_partial_content(req, res, filename, filesize)
mtype = HTTPUtils::mime_type(filename, @config[:MimeTypes])
unless ranges = HTTPUtils::parse_range_header(req['range'])
raise HTTPStatus::BadRequest,
"Unrecognized range-spec: \"#{req['range']}\""
end
- open(filename, "rb"){|io|
+ File.open(filename, "rb"){|io|
if ranges.size > 1
time = Time.now
boundary = "#{time.sec}_#{time.usec}_#{Process::pid}"
- body = ''
- ranges.each{|range|
- first, last = prepare_range(range, filesize)
- next if first < 0
- io.pos = first
- content = io.read(last-first+1)
- body << "--" << boundary << CRLF
- body << "Content-Type: #{mtype}" << CRLF
- body << "Content-Range: bytes #{first}-#{last}/#{filesize}" << CRLF
- body << CRLF
- body << content
- body << CRLF
+ parts = []
+ ranges.each {|range|
+ prange = prepare_range(range, filesize)
+ next if prange[0] < 0
+ parts.concat(prange)
}
- raise HTTPStatus::RequestRangeNotSatisfiable if body.empty?
- body << "--" << boundary << "--" << CRLF
+ raise HTTPStatus::RequestRangeNotSatisfiable if parts.empty?
res["content-type"] = "multipart/byteranges; boundary=#{boundary}"
- res.body = body
+ if req.http_version < '1.1'
+ res['connection'] = 'close'
+ else
+ res.chunked = true
+ end
+ res.body = multipart_body(io.dup, parts, boundary, mtype, filesize)
elsif range = ranges[0]
first, last = prepare_range(range, filesize)
raise HTTPStatus::RequestRangeNotSatisfiable if first < 0
- if last == filesize - 1
- content = io.dup
- content.pos = first
- else
- io.pos = first
- content = io.read(last-first+1)
- end
res['content-type'] = mtype
res['content-range'] = "bytes #{first}-#{last}/#{filesize}"
- res['content-length'] = last - first + 1
- res.body = content
+ res['content-length'] = (last - first + 1).to_s
+ res.body = io.dup
else
raise HTTPStatus::BadRequest
end
@@ -123,13 +159,21 @@ module WEBrick
last = filesize - 1 if last >= filesize
return first, last
end
+
+ # :startdoc:
end
##
- # Serves files from a directory
+ # Serves a directory including fancy indexing and a variety of other
+ # options.
+ #
+ # Example:
+ #
+ # server.mount('/assets', WEBrick::HTTPServlet::FileHandler,
+ # '/path/to/assets')
class FileHandler < AbstractServlet
- HandlerTable = Hash.new
+ HandlerTable = Hash.new # :nodoc:
##
# Allow custom handling of requests for files with +suffix+ by class
@@ -150,19 +194,8 @@ module WEBrick
# Creates a FileHandler servlet on +server+ that serves files starting
# at directory +root+
#
- # If +options+ is a Hash the following keys are allowed:
- #
- # :AcceptableLanguages:: Array of languages allowed for accept-language
- # :DirectoryCallback:: Allows preprocessing of directory requests
- # :FancyIndexing:: If true, show an index for directories
- # :FileCallback:: Allows preprocessing of file requests
- # :HandlerCallback:: Allows preprocessing of requests
- # :HandlerTable:: Maps file suffixes to file handlers.
- # DefaultFileHandler is used by default but any servlet
- # can be used.
- # :NondisclosureName:: Do not show files matching this array of globs
- # :UserDir:: Directory inside ~user to serve content from for /~user
- # requests. Only works if mounted on /
+ # +options+ may be a Hash containing keys from
+ # WEBrick::Config::FileHandler or +true+ or +false+.
#
# If +options+ is true or false then +:FancyIndexing+ is enabled or
# disabled respectively.
@@ -177,6 +210,8 @@ module WEBrick
@options = default.dup.update(options)
end
+ # :stopdoc:
+
def service(req, res)
# if this class is mounted on "/" and /~username is requested.
# we're going to override path informations before invoking service.
@@ -409,11 +444,18 @@ module WEBrick
}
list.compact!
- if d0 = req.query["N"]; idx = 0
- elsif d0 = req.query["M"]; idx = 1
- elsif d0 = req.query["S"]; idx = 2
- else d0 = "A" ; idx = 0
+ query = req.query
+
+ d0 = nil
+ idx = nil
+ %w[N M S].each_with_index do |q, i|
+ if d = query.delete(q)
+ idx ||= i
+ d0 ||= d
+ end
end
+ d0 ||= "A"
+ idx ||= 0
d1 = (d0 == "A") ? "D" : "A"
if d0 == "A"
@@ -422,38 +464,66 @@ module WEBrick
list.sort!{|a,b| b[idx] <=> a[idx] }
end
- res['content-type'] = "text/html"
+ namewidth = query["NameWidth"]
+ if namewidth == "*"
+ namewidth = nil
+ elsif !namewidth or (namewidth = namewidth.to_i) < 2
+ namewidth = 25
+ end
+ query = query.inject('') {|s, (k, v)| s << '&' << HTMLUtils::escape("#{k}=#{v}")}
+
+ type = "text/html"
+ case enc = Encoding.find('filesystem')
+ when Encoding::US_ASCII, Encoding::ASCII_8BIT
+ else
+ type << "; charset=\"#{enc.name}\""
+ end
+ res['content-type'] = type
+ title = "Index of #{HTMLUtils::escape(req.path)}"
res.body = <<-_end_of_html_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
- <HEAD><TITLE>Index of #{HTMLUtils::escape(req.path)}</TITLE></HEAD>
+ <HEAD>
+ <TITLE>#{title}</TITLE>
+ <style type="text/css">
+ <!--
+ .name, .mtime { text-align: left; }
+ .size { text-align: right; }
+ td { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; }
+ table { border-collapse: collapse; }
+ tr th { border-bottom: 2px groove; }
+ //-->
+ </style>
+ </HEAD>
<BODY>
- <H1>Index of #{HTMLUtils::escape(req.path)}</H1>
+ <H1>#{title}</H1>
_end_of_html_
- res.body << "<PRE>\n"
- res.body << " <A HREF=\"?N=#{d1}\">Name</A> "
- res.body << "<A HREF=\"?M=#{d1}\">Last modified</A> "
- res.body << "<A HREF=\"?S=#{d1}\">Size</A>\n"
- res.body << "<HR>\n"
+ res.body << "<TABLE width=\"100%\"><THEAD><TR>\n"
+ res.body << "<TH class=\"name\"><A HREF=\"?N=#{d1}#{query}\">Name</A></TH>"
+ res.body << "<TH class=\"mtime\"><A HREF=\"?M=#{d1}#{query}\">Last modified</A></TH>"
+ res.body << "<TH class=\"size\"><A HREF=\"?S=#{d1}#{query}\">Size</A></TH>\n"
+ res.body << "</TR></THEAD>\n"
+ res.body << "<TBODY>\n"
+ query.sub!(/\A&/, '?')
list.unshift [ "..", File::mtime(local_path+"/.."), -1 ]
list.each{ |name, time, size|
if name == ".."
dname = "Parent Directory"
- elsif name.bytesize > 25
- dname = name.sub(/^(.{23})(?:.*)/, '\1..')
+ elsif namewidth and name.size > namewidth
+ dname = name[0...(namewidth - 2)] << '..'
else
dname = name
end
- s = " <A HREF=\"#{HTTPUtils::escape(name)}\">#{HTMLUtils::escape(dname)}</A>"
- s << " " * (30 - dname.bytesize)
- s << (time ? time.strftime("%Y/%m/%d %H:%M ") : " " * 22)
- s << (size >= 0 ? size.to_s : "-") << "\n"
+ s = "<TR><TD class=\"name\"><A HREF=\"#{HTTPUtils::escape(name)}#{query if name.end_with?('/')}\">#{HTMLUtils::escape(dname)}</A></TD>"
+ s << "<TD class=\"mtime\">" << (time ? time.strftime("%Y/%m/%d %H:%M") : "") << "</TD>"
+ s << "<TD class=\"size\">" << (size >= 0 ? size.to_s : "-") << "</TD></TR>\n"
res.body << s
}
- res.body << "</PRE><HR>"
+ res.body << "</TBODY></TABLE>"
+ res.body << "<HR>"
res.body << <<-_end_of_html_
<ADDRESS>
@@ -465,6 +535,7 @@ module WEBrick
_end_of_html_
end
+ # :startdoc:
end
end
end
diff --git a/lib/webrick/httpservlet/prochandler.rb b/lib/webrick/httpservlet/prochandler.rb
index 2be3c854c1..599ffc4340 100644
--- a/lib/webrick/httpservlet/prochandler.rb
+++ b/lib/webrick/httpservlet/prochandler.rb
@@ -1,3 +1,4 @@
+# frozen_string_literal: false
#
# prochandler.rb -- ProcHandler Class
#
@@ -8,12 +9,24 @@
#
# $IPR: prochandler.rb,v 1.7 2002/09/21 12:23:42 gotoyuzo Exp $
-require 'webrick/httpservlet/abstract.rb'
+require_relative 'abstract'
module WEBrick
module HTTPServlet
+ ##
+ # Mounts a proc at a path that accepts a request and response.
+ #
+ # Instead of mounting this servlet with WEBrick::HTTPServer#mount use
+ # WEBrick::HTTPServer#mount_proc:
+ #
+ # server.mount_proc '/' do |req, res|
+ # res.body = 'it worked!'
+ # res.status = 200
+ # end
+
class ProcHandler < AbstractServlet
+ # :stopdoc:
def get_instance(server, *options)
self
end
@@ -27,6 +40,7 @@ module WEBrick
end
alias do_POST do_GET
+ # :startdoc:
end
end