1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
#
# Get CGI String
#
# EXAMPLE:
# require "cgi-lib.rb"
# foo = CGI.new
# foo['field'] <== value of 'field'
# foo.keys <== array of fields
# and foo has Hash class methods
# if running on Windows(IIS or PWS) then change cwd.
if ENV['SERVER_SOFTWARE'] =~ /^Microsoft-/ then
Dir.chdir ENV['PATH_TRANSLATED'].sub(/[^\\]+$/, '')
end
require "delegate"
class CGI < SimpleDelegator
attr("inputs")
# original is CGI.pm
def read_from_cmdline
require "shellwords.rb"
words = Shellwords.shellwords(if not ARGV.empty? then
ARGV.join(' ')
else
STDERR.print "(offline mode: enter name=value pairs on standard input)\n" if STDIN.tty?
readlines.join(' ').gsub(/\n/, '')
end.gsub(/\\=/, '%3D').gsub(/\\&/, '%26'))
if words.find{|x| x =~ /=/} then words.join('&') else words.join('+') end
end
# escape url encode
def escape(str)
str.gsub!(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
str
end
# unescape url encoded
def unescape(str)
str.gsub! /\+/, ' '
str.gsub!(/%([0-9a-fA-F]{2})/){ [$1.hex].pack("c") }
str
end
module_function :escape, :unescape
def initialize(input = $stdin)
@inputs = {}
case ENV['REQUEST_METHOD']
when "GET"
# exception messages should be printed to stdout.
STDERR.reopen(STDOUT)
ENV['QUERY_STRING'] or ""
when "POST"
# exception messages should be printed to stdout.
STDERR.reopen(STDOUT)
input.read Integer(ENV['CONTENT_LENGTH'])
else
read_from_cmdline
end.split(/&/).each do |x|
key, val = x.split(/=/,2).collect{|x|unescape(x)}
if @inputs.include?(key)
@inputs[key] += "\0" + (val or "")
else
@inputs[key] = (val or "")
end
end
super(@inputs)
end
def CGI.message(msg, title = "")
print "Content-type: text/html\n\n"
print "<html><head><title>"
print title
print "</title></head><body>\n"
print msg
print "</body></html>\n"
TRUE
end
def CGI.error
m = $!.to_s.dup
m.gsub!(/&/, '&')
m.gsub!(/</, '<')
m.gsub!(/>/, '>')
msgs = ["<pre>ERROR: <strong>#{m}</strong>"]
msgs << $@
msgs << "</pre>"
CGI.message(msgs.join("\n"), "ERROR")
exit
end
end
|