cgi 0.3.3-java
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of cgi might be problematic. Click here for more details.
- checksums.yaml +7 -0
- data/LICENSE.txt +22 -0
- data/README.md +97 -0
- data/ext/java/org/jruby/ext/cgi/escape/lib/cgi/escape.rb +5 -0
- data/lib/cgi/cookie.rb +181 -0
- data/lib/cgi/core.rb +889 -0
- data/lib/cgi/escape.jar +0 -0
- data/lib/cgi/html.rb +1035 -0
- data/lib/cgi/session/pstore.rb +88 -0
- data/lib/cgi/session.rb +562 -0
- data/lib/cgi/util.rb +252 -0
- data/lib/cgi.rb +297 -0
- metadata +58 -0
data/lib/cgi/core.rb
ADDED
@@ -0,0 +1,889 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
#--
|
3
|
+
# Methods for generating HTML, parsing CGI-related parameters, and
|
4
|
+
# generating HTTP responses.
|
5
|
+
#++
|
6
|
+
class CGI
|
7
|
+
unless const_defined?(:Util)
|
8
|
+
module Util
|
9
|
+
@@accept_charset = "UTF-8" # :nodoc:
|
10
|
+
end
|
11
|
+
include Util
|
12
|
+
extend Util
|
13
|
+
end
|
14
|
+
|
15
|
+
$CGI_ENV = ENV # for FCGI support
|
16
|
+
|
17
|
+
# String for carriage return
|
18
|
+
CR = "\015"
|
19
|
+
|
20
|
+
# String for linefeed
|
21
|
+
LF = "\012"
|
22
|
+
|
23
|
+
# Standard internet newline sequence
|
24
|
+
EOL = CR + LF
|
25
|
+
|
26
|
+
REVISION = '$Id$' #:nodoc:
|
27
|
+
|
28
|
+
# Whether processing will be required in binary vs text
|
29
|
+
NEEDS_BINMODE = File::BINARY != 0
|
30
|
+
|
31
|
+
# Path separators in different environments.
|
32
|
+
PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'}
|
33
|
+
|
34
|
+
# HTTP status codes.
|
35
|
+
HTTP_STATUS = {
|
36
|
+
"OK" => "200 OK",
|
37
|
+
"PARTIAL_CONTENT" => "206 Partial Content",
|
38
|
+
"MULTIPLE_CHOICES" => "300 Multiple Choices",
|
39
|
+
"MOVED" => "301 Moved Permanently",
|
40
|
+
"REDIRECT" => "302 Found",
|
41
|
+
"NOT_MODIFIED" => "304 Not Modified",
|
42
|
+
"BAD_REQUEST" => "400 Bad Request",
|
43
|
+
"AUTH_REQUIRED" => "401 Authorization Required",
|
44
|
+
"FORBIDDEN" => "403 Forbidden",
|
45
|
+
"NOT_FOUND" => "404 Not Found",
|
46
|
+
"METHOD_NOT_ALLOWED" => "405 Method Not Allowed",
|
47
|
+
"NOT_ACCEPTABLE" => "406 Not Acceptable",
|
48
|
+
"LENGTH_REQUIRED" => "411 Length Required",
|
49
|
+
"PRECONDITION_FAILED" => "412 Precondition Failed",
|
50
|
+
"SERVER_ERROR" => "500 Internal Server Error",
|
51
|
+
"NOT_IMPLEMENTED" => "501 Method Not Implemented",
|
52
|
+
"BAD_GATEWAY" => "502 Bad Gateway",
|
53
|
+
"VARIANT_ALSO_VARIES" => "506 Variant Also Negotiates"
|
54
|
+
}
|
55
|
+
|
56
|
+
# :startdoc:
|
57
|
+
|
58
|
+
# Synonym for ENV.
|
59
|
+
def env_table
|
60
|
+
ENV
|
61
|
+
end
|
62
|
+
|
63
|
+
# Synonym for $stdin.
|
64
|
+
def stdinput
|
65
|
+
$stdin
|
66
|
+
end
|
67
|
+
|
68
|
+
# Synonym for $stdout.
|
69
|
+
def stdoutput
|
70
|
+
$stdout
|
71
|
+
end
|
72
|
+
|
73
|
+
private :env_table, :stdinput, :stdoutput
|
74
|
+
|
75
|
+
# Create an HTTP header block as a string.
|
76
|
+
#
|
77
|
+
# :call-seq:
|
78
|
+
# http_header(content_type_string="text/html")
|
79
|
+
# http_header(headers_hash)
|
80
|
+
#
|
81
|
+
# Includes the empty line that ends the header block.
|
82
|
+
#
|
83
|
+
# +content_type_string+::
|
84
|
+
# If this form is used, this string is the <tt>Content-Type</tt>
|
85
|
+
# +headers_hash+::
|
86
|
+
# A Hash of header values. The following header keys are recognized:
|
87
|
+
#
|
88
|
+
# type:: The Content-Type header. Defaults to "text/html"
|
89
|
+
# charset:: The charset of the body, appended to the Content-Type header.
|
90
|
+
# nph:: A boolean value. If true, prepend protocol string and status
|
91
|
+
# code, and date; and sets default values for "server" and
|
92
|
+
# "connection" if not explicitly set.
|
93
|
+
# status::
|
94
|
+
# The HTTP status code as a String, returned as the Status header. The
|
95
|
+
# values are:
|
96
|
+
#
|
97
|
+
# OK:: 200 OK
|
98
|
+
# PARTIAL_CONTENT:: 206 Partial Content
|
99
|
+
# MULTIPLE_CHOICES:: 300 Multiple Choices
|
100
|
+
# MOVED:: 301 Moved Permanently
|
101
|
+
# REDIRECT:: 302 Found
|
102
|
+
# NOT_MODIFIED:: 304 Not Modified
|
103
|
+
# BAD_REQUEST:: 400 Bad Request
|
104
|
+
# AUTH_REQUIRED:: 401 Authorization Required
|
105
|
+
# FORBIDDEN:: 403 Forbidden
|
106
|
+
# NOT_FOUND:: 404 Not Found
|
107
|
+
# METHOD_NOT_ALLOWED:: 405 Method Not Allowed
|
108
|
+
# NOT_ACCEPTABLE:: 406 Not Acceptable
|
109
|
+
# LENGTH_REQUIRED:: 411 Length Required
|
110
|
+
# PRECONDITION_FAILED:: 412 Precondition Failed
|
111
|
+
# SERVER_ERROR:: 500 Internal Server Error
|
112
|
+
# NOT_IMPLEMENTED:: 501 Method Not Implemented
|
113
|
+
# BAD_GATEWAY:: 502 Bad Gateway
|
114
|
+
# VARIANT_ALSO_VARIES:: 506 Variant Also Negotiates
|
115
|
+
#
|
116
|
+
# server:: The server software, returned as the Server header.
|
117
|
+
# connection:: The connection type, returned as the Connection header (for
|
118
|
+
# instance, "close".
|
119
|
+
# length:: The length of the content that will be sent, returned as the
|
120
|
+
# Content-Length header.
|
121
|
+
# language:: The language of the content, returned as the Content-Language
|
122
|
+
# header.
|
123
|
+
# expires:: The time on which the current content expires, as a +Time+
|
124
|
+
# object, returned as the Expires header.
|
125
|
+
# cookie::
|
126
|
+
# A cookie or cookies, returned as one or more Set-Cookie headers. The
|
127
|
+
# value can be the literal string of the cookie; a CGI::Cookie object;
|
128
|
+
# an Array of literal cookie strings or Cookie objects; or a hash all of
|
129
|
+
# whose values are literal cookie strings or Cookie objects.
|
130
|
+
#
|
131
|
+
# These cookies are in addition to the cookies held in the
|
132
|
+
# @output_cookies field.
|
133
|
+
#
|
134
|
+
# Other headers can also be set; they are appended as key: value.
|
135
|
+
#
|
136
|
+
# Examples:
|
137
|
+
#
|
138
|
+
# http_header
|
139
|
+
# # Content-Type: text/html
|
140
|
+
#
|
141
|
+
# http_header("text/plain")
|
142
|
+
# # Content-Type: text/plain
|
143
|
+
#
|
144
|
+
# http_header("nph" => true,
|
145
|
+
# "status" => "OK", # == "200 OK"
|
146
|
+
# # "status" => "200 GOOD",
|
147
|
+
# "server" => ENV['SERVER_SOFTWARE'],
|
148
|
+
# "connection" => "close",
|
149
|
+
# "type" => "text/html",
|
150
|
+
# "charset" => "iso-2022-jp",
|
151
|
+
# # Content-Type: text/html; charset=iso-2022-jp
|
152
|
+
# "length" => 103,
|
153
|
+
# "language" => "ja",
|
154
|
+
# "expires" => Time.now + 30,
|
155
|
+
# "cookie" => [cookie1, cookie2],
|
156
|
+
# "my_header1" => "my_value",
|
157
|
+
# "my_header2" => "my_value")
|
158
|
+
#
|
159
|
+
# This method does not perform charset conversion.
|
160
|
+
def http_header(options='text/html')
|
161
|
+
if options.is_a?(String)
|
162
|
+
content_type = options
|
163
|
+
buf = _header_for_string(content_type)
|
164
|
+
elsif options.is_a?(Hash)
|
165
|
+
if options.size == 1 && options.has_key?('type')
|
166
|
+
content_type = options['type']
|
167
|
+
buf = _header_for_string(content_type)
|
168
|
+
else
|
169
|
+
buf = _header_for_hash(options.dup)
|
170
|
+
end
|
171
|
+
else
|
172
|
+
raise ArgumentError.new("expected String or Hash but got #{options.class}")
|
173
|
+
end
|
174
|
+
if defined?(MOD_RUBY)
|
175
|
+
_header_for_modruby(buf)
|
176
|
+
return ''
|
177
|
+
else
|
178
|
+
buf << EOL # empty line of separator
|
179
|
+
return buf
|
180
|
+
end
|
181
|
+
end # http_header()
|
182
|
+
|
183
|
+
# This method is an alias for #http_header, when HTML5 tag maker is inactive.
|
184
|
+
#
|
185
|
+
# NOTE: use #http_header to create HTTP header blocks, this alias is only
|
186
|
+
# provided for backwards compatibility.
|
187
|
+
#
|
188
|
+
# Using #header with the HTML5 tag maker will create a <header> element.
|
189
|
+
alias :header :http_header
|
190
|
+
|
191
|
+
def _header_for_string(content_type) #:nodoc:
|
192
|
+
buf = ''.dup
|
193
|
+
if nph?()
|
194
|
+
buf << "#{$CGI_ENV['SERVER_PROTOCOL'] || 'HTTP/1.0'} 200 OK#{EOL}"
|
195
|
+
buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}"
|
196
|
+
buf << "Server: #{$CGI_ENV['SERVER_SOFTWARE']}#{EOL}"
|
197
|
+
buf << "Connection: close#{EOL}"
|
198
|
+
end
|
199
|
+
buf << "Content-Type: #{content_type}#{EOL}"
|
200
|
+
if @output_cookies
|
201
|
+
@output_cookies.each {|cookie| buf << "Set-Cookie: #{cookie}#{EOL}" }
|
202
|
+
end
|
203
|
+
return buf
|
204
|
+
end # _header_for_string
|
205
|
+
private :_header_for_string
|
206
|
+
|
207
|
+
def _header_for_hash(options) #:nodoc:
|
208
|
+
buf = ''.dup
|
209
|
+
## add charset to option['type']
|
210
|
+
options['type'] ||= 'text/html'
|
211
|
+
charset = options.delete('charset')
|
212
|
+
options['type'] += "; charset=#{charset}" if charset
|
213
|
+
## NPH
|
214
|
+
options.delete('nph') if defined?(MOD_RUBY)
|
215
|
+
if options.delete('nph') || nph?()
|
216
|
+
protocol = $CGI_ENV['SERVER_PROTOCOL'] || 'HTTP/1.0'
|
217
|
+
status = options.delete('status')
|
218
|
+
status = HTTP_STATUS[status] || status || '200 OK'
|
219
|
+
buf << "#{protocol} #{status}#{EOL}"
|
220
|
+
buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}"
|
221
|
+
options['server'] ||= $CGI_ENV['SERVER_SOFTWARE'] || ''
|
222
|
+
options['connection'] ||= 'close'
|
223
|
+
end
|
224
|
+
## common headers
|
225
|
+
status = options.delete('status')
|
226
|
+
buf << "Status: #{HTTP_STATUS[status] || status}#{EOL}" if status
|
227
|
+
server = options.delete('server')
|
228
|
+
buf << "Server: #{server}#{EOL}" if server
|
229
|
+
connection = options.delete('connection')
|
230
|
+
buf << "Connection: #{connection}#{EOL}" if connection
|
231
|
+
type = options.delete('type')
|
232
|
+
buf << "Content-Type: #{type}#{EOL}" #if type
|
233
|
+
length = options.delete('length')
|
234
|
+
buf << "Content-Length: #{length}#{EOL}" if length
|
235
|
+
language = options.delete('language')
|
236
|
+
buf << "Content-Language: #{language}#{EOL}" if language
|
237
|
+
expires = options.delete('expires')
|
238
|
+
buf << "Expires: #{CGI.rfc1123_date(expires)}#{EOL}" if expires
|
239
|
+
## cookie
|
240
|
+
if cookie = options.delete('cookie')
|
241
|
+
case cookie
|
242
|
+
when String, Cookie
|
243
|
+
buf << "Set-Cookie: #{cookie}#{EOL}"
|
244
|
+
when Array
|
245
|
+
arr = cookie
|
246
|
+
arr.each {|c| buf << "Set-Cookie: #{c}#{EOL}" }
|
247
|
+
when Hash
|
248
|
+
hash = cookie
|
249
|
+
hash.each_value {|c| buf << "Set-Cookie: #{c}#{EOL}" }
|
250
|
+
end
|
251
|
+
end
|
252
|
+
if @output_cookies
|
253
|
+
@output_cookies.each {|c| buf << "Set-Cookie: #{c}#{EOL}" }
|
254
|
+
end
|
255
|
+
## other headers
|
256
|
+
options.each do |key, value|
|
257
|
+
buf << "#{key}: #{value}#{EOL}"
|
258
|
+
end
|
259
|
+
return buf
|
260
|
+
end # _header_for_hash
|
261
|
+
private :_header_for_hash
|
262
|
+
|
263
|
+
def nph? #:nodoc:
|
264
|
+
return /IIS\/(\d+)/ =~ $CGI_ENV['SERVER_SOFTWARE'] && $1.to_i < 5
|
265
|
+
end
|
266
|
+
|
267
|
+
def _header_for_modruby(buf) #:nodoc:
|
268
|
+
request = Apache::request
|
269
|
+
buf.scan(/([^:]+): (.+)#{EOL}/o) do |name, value|
|
270
|
+
$stderr.printf("name:%s value:%s\n", name, value) if $DEBUG
|
271
|
+
case name
|
272
|
+
when 'Set-Cookie'
|
273
|
+
request.headers_out.add(name, value)
|
274
|
+
when /^status$/i
|
275
|
+
request.status_line = value
|
276
|
+
request.status = value.to_i
|
277
|
+
when /^content-type$/i
|
278
|
+
request.content_type = value
|
279
|
+
when /^content-encoding$/i
|
280
|
+
request.content_encoding = value
|
281
|
+
when /^location$/i
|
282
|
+
request.status = 302 if request.status == 200
|
283
|
+
request.headers_out[name] = value
|
284
|
+
else
|
285
|
+
request.headers_out[name] = value
|
286
|
+
end
|
287
|
+
end
|
288
|
+
request.send_http_header
|
289
|
+
return ''
|
290
|
+
end
|
291
|
+
private :_header_for_modruby
|
292
|
+
|
293
|
+
# Print an HTTP header and body to $DEFAULT_OUTPUT ($>)
|
294
|
+
#
|
295
|
+
# :call-seq:
|
296
|
+
# cgi.out(content_type_string='text/html')
|
297
|
+
# cgi.out(headers_hash)
|
298
|
+
#
|
299
|
+
# +content_type_string+::
|
300
|
+
# If a string is passed, it is assumed to be the content type.
|
301
|
+
# +headers_hash+::
|
302
|
+
# This is a Hash of headers, similar to that used by #http_header.
|
303
|
+
# +block+::
|
304
|
+
# A block is required and should evaluate to the body of the response.
|
305
|
+
#
|
306
|
+
# <tt>Content-Length</tt> is automatically calculated from the size of
|
307
|
+
# the String returned by the content block.
|
308
|
+
#
|
309
|
+
# If <tt>ENV['REQUEST_METHOD'] == "HEAD"</tt>, then only the header
|
310
|
+
# is output (the content block is still required, but it is ignored).
|
311
|
+
#
|
312
|
+
# If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then the
|
313
|
+
# content is converted to this charset, and the language is set to "ja".
|
314
|
+
#
|
315
|
+
# Example:
|
316
|
+
#
|
317
|
+
# cgi = CGI.new
|
318
|
+
# cgi.out{ "string" }
|
319
|
+
# # Content-Type: text/html
|
320
|
+
# # Content-Length: 6
|
321
|
+
# #
|
322
|
+
# # string
|
323
|
+
#
|
324
|
+
# cgi.out("text/plain") { "string" }
|
325
|
+
# # Content-Type: text/plain
|
326
|
+
# # Content-Length: 6
|
327
|
+
# #
|
328
|
+
# # string
|
329
|
+
#
|
330
|
+
# cgi.out("nph" => true,
|
331
|
+
# "status" => "OK", # == "200 OK"
|
332
|
+
# "server" => ENV['SERVER_SOFTWARE'],
|
333
|
+
# "connection" => "close",
|
334
|
+
# "type" => "text/html",
|
335
|
+
# "charset" => "iso-2022-jp",
|
336
|
+
# # Content-Type: text/html; charset=iso-2022-jp
|
337
|
+
# "language" => "ja",
|
338
|
+
# "expires" => Time.now + (3600 * 24 * 30),
|
339
|
+
# "cookie" => [cookie1, cookie2],
|
340
|
+
# "my_header1" => "my_value",
|
341
|
+
# "my_header2" => "my_value") { "string" }
|
342
|
+
# # HTTP/1.1 200 OK
|
343
|
+
# # Date: Sun, 15 May 2011 17:35:54 GMT
|
344
|
+
# # Server: Apache 2.2.0
|
345
|
+
# # Connection: close
|
346
|
+
# # Content-Type: text/html; charset=iso-2022-jp
|
347
|
+
# # Content-Length: 6
|
348
|
+
# # Content-Language: ja
|
349
|
+
# # Expires: Tue, 14 Jun 2011 17:35:54 GMT
|
350
|
+
# # Set-Cookie: foo
|
351
|
+
# # Set-Cookie: bar
|
352
|
+
# # my_header1: my_value
|
353
|
+
# # my_header2: my_value
|
354
|
+
# #
|
355
|
+
# # string
|
356
|
+
def out(options = "text/html") # :yield:
|
357
|
+
|
358
|
+
options = { "type" => options } if options.kind_of?(String)
|
359
|
+
content = yield
|
360
|
+
options["length"] = content.bytesize.to_s
|
361
|
+
output = stdoutput
|
362
|
+
output.binmode if defined? output.binmode
|
363
|
+
output.print http_header(options)
|
364
|
+
output.print content unless "HEAD" == env_table['REQUEST_METHOD']
|
365
|
+
end
|
366
|
+
|
367
|
+
|
368
|
+
# Print an argument or list of arguments to the default output stream
|
369
|
+
#
|
370
|
+
# cgi = CGI.new
|
371
|
+
# cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print
|
372
|
+
def print(*options)
|
373
|
+
stdoutput.print(*options)
|
374
|
+
end
|
375
|
+
|
376
|
+
# Parse an HTTP query string into a hash of key=>value pairs.
|
377
|
+
#
|
378
|
+
# params = CGI.parse("query_string")
|
379
|
+
# # {"name1" => ["value1", "value2", ...],
|
380
|
+
# # "name2" => ["value1", "value2", ...], ... }
|
381
|
+
#
|
382
|
+
def self.parse(query)
|
383
|
+
params = {}
|
384
|
+
query.split(/[&;]/).each do |pairs|
|
385
|
+
key, value = pairs.split('=',2).collect{|v| CGI.unescape(v) }
|
386
|
+
|
387
|
+
next unless key
|
388
|
+
|
389
|
+
params[key] ||= []
|
390
|
+
params[key].push(value) if value
|
391
|
+
end
|
392
|
+
|
393
|
+
params.default=[].freeze
|
394
|
+
params
|
395
|
+
end
|
396
|
+
|
397
|
+
# Maximum content length of post data
|
398
|
+
##MAX_CONTENT_LENGTH = 2 * 1024 * 1024
|
399
|
+
|
400
|
+
# Maximum number of request parameters when multipart
|
401
|
+
MAX_MULTIPART_COUNT = 128
|
402
|
+
|
403
|
+
# Mixin module that provides the following:
|
404
|
+
#
|
405
|
+
# 1. Access to the CGI environment variables as methods. See
|
406
|
+
# documentation to the CGI class for a list of these variables. The
|
407
|
+
# methods are exposed by removing the leading +HTTP_+ (if it exists) and
|
408
|
+
# downcasing the name. For example, +auth_type+ will return the
|
409
|
+
# environment variable +AUTH_TYPE+, and +accept+ will return the value
|
410
|
+
# for +HTTP_ACCEPT+.
|
411
|
+
#
|
412
|
+
# 2. Access to cookies, including the cookies attribute.
|
413
|
+
#
|
414
|
+
# 3. Access to parameters, including the params attribute, and overloading
|
415
|
+
# #[] to perform parameter value lookup by key.
|
416
|
+
#
|
417
|
+
# 4. The initialize_query method, for initializing the above
|
418
|
+
# mechanisms, handling multipart forms, and allowing the
|
419
|
+
# class to be used in "offline" mode.
|
420
|
+
#
|
421
|
+
module QueryExtension
|
422
|
+
|
423
|
+
%w[ CONTENT_LENGTH SERVER_PORT ].each do |env|
|
424
|
+
define_method(env.delete_prefix('HTTP_').downcase) do
|
425
|
+
(val = env_table[env]) && Integer(val)
|
426
|
+
end
|
427
|
+
end
|
428
|
+
|
429
|
+
%w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
|
430
|
+
PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST
|
431
|
+
REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME
|
432
|
+
SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE
|
433
|
+
|
434
|
+
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
|
435
|
+
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST
|
436
|
+
HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env|
|
437
|
+
define_method(env.delete_prefix('HTTP_').downcase) do
|
438
|
+
env_table[env]
|
439
|
+
end
|
440
|
+
end
|
441
|
+
|
442
|
+
# Get the raw cookies as a string.
|
443
|
+
def raw_cookie
|
444
|
+
env_table["HTTP_COOKIE"]
|
445
|
+
end
|
446
|
+
|
447
|
+
# Get the raw RFC2965 cookies as a string.
|
448
|
+
def raw_cookie2
|
449
|
+
env_table["HTTP_COOKIE2"]
|
450
|
+
end
|
451
|
+
|
452
|
+
# Get the cookies as a hash of cookie-name=>Cookie pairs.
|
453
|
+
attr_accessor :cookies
|
454
|
+
|
455
|
+
# Get the parameters as a hash of name=>values pairs, where
|
456
|
+
# values is an Array.
|
457
|
+
attr_reader :params
|
458
|
+
|
459
|
+
# Get the uploaded files as a hash of name=>values pairs
|
460
|
+
attr_reader :files
|
461
|
+
|
462
|
+
# Set all the parameters.
|
463
|
+
def params=(hash)
|
464
|
+
@params.clear
|
465
|
+
@params.update(hash)
|
466
|
+
end
|
467
|
+
|
468
|
+
##
|
469
|
+
# Parses multipart form elements according to
|
470
|
+
# http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
|
471
|
+
#
|
472
|
+
# Returns a hash of multipart form parameters with bodies of type StringIO or
|
473
|
+
# Tempfile depending on whether the multipart form element exceeds 10 KB
|
474
|
+
#
|
475
|
+
# params[name => body]
|
476
|
+
#
|
477
|
+
def read_multipart(boundary, content_length)
|
478
|
+
## read first boundary
|
479
|
+
stdin = stdinput
|
480
|
+
first_line = "--#{boundary}#{EOL}"
|
481
|
+
content_length -= first_line.bytesize
|
482
|
+
status = stdin.read(first_line.bytesize)
|
483
|
+
raise EOFError.new("no content body") unless status
|
484
|
+
raise EOFError.new("bad content body") unless first_line == status
|
485
|
+
## parse and set params
|
486
|
+
params = {}
|
487
|
+
@files = {}
|
488
|
+
boundary_rexp = /--#{Regexp.quote(boundary)}(#{EOL}|--)/
|
489
|
+
boundary_size = "#{EOL}--#{boundary}#{EOL}".bytesize
|
490
|
+
buf = ''.dup
|
491
|
+
bufsize = 10 * 1024
|
492
|
+
max_count = MAX_MULTIPART_COUNT
|
493
|
+
n = 0
|
494
|
+
tempfiles = []
|
495
|
+
while true
|
496
|
+
(n += 1) < max_count or raise StandardError.new("too many parameters.")
|
497
|
+
## create body (StringIO or Tempfile)
|
498
|
+
body = create_body(bufsize < content_length)
|
499
|
+
tempfiles << body if defined?(Tempfile) && body.kind_of?(Tempfile)
|
500
|
+
class << body
|
501
|
+
if method_defined?(:path)
|
502
|
+
alias local_path path
|
503
|
+
else
|
504
|
+
def local_path
|
505
|
+
nil
|
506
|
+
end
|
507
|
+
end
|
508
|
+
attr_reader :original_filename, :content_type
|
509
|
+
end
|
510
|
+
## find head and boundary
|
511
|
+
head = nil
|
512
|
+
separator = EOL * 2
|
513
|
+
until head && matched = boundary_rexp.match(buf)
|
514
|
+
if !head && pos = buf.index(separator)
|
515
|
+
len = pos + EOL.bytesize
|
516
|
+
head = buf[0, len]
|
517
|
+
buf = buf[(pos+separator.bytesize)..-1]
|
518
|
+
else
|
519
|
+
if head && buf.size > boundary_size
|
520
|
+
len = buf.size - boundary_size
|
521
|
+
body.print(buf[0, len])
|
522
|
+
buf[0, len] = ''
|
523
|
+
end
|
524
|
+
c = stdin.read(bufsize < content_length ? bufsize : content_length)
|
525
|
+
raise EOFError.new("bad content body") if c.nil? || c.empty?
|
526
|
+
buf << c
|
527
|
+
content_length -= c.bytesize
|
528
|
+
end
|
529
|
+
end
|
530
|
+
## read to end of boundary
|
531
|
+
m = matched
|
532
|
+
len = m.begin(0)
|
533
|
+
s = buf[0, len]
|
534
|
+
if s =~ /(\r?\n)\z/
|
535
|
+
s = buf[0, len - $1.bytesize]
|
536
|
+
end
|
537
|
+
body.print(s)
|
538
|
+
buf = buf[m.end(0)..-1]
|
539
|
+
boundary_end = m[1]
|
540
|
+
content_length = -1 if boundary_end == '--'
|
541
|
+
## reset file cursor position
|
542
|
+
body.rewind
|
543
|
+
## original filename
|
544
|
+
/Content-Disposition:.* filename=(?:"(.*?)"|([^;\r\n]*))/i.match(head)
|
545
|
+
filename = $1 || $2 || ''.dup
|
546
|
+
filename = CGI.unescape(filename) if unescape_filename?()
|
547
|
+
body.instance_variable_set(:@original_filename, filename)
|
548
|
+
## content type
|
549
|
+
/Content-Type: (.*)/i.match(head)
|
550
|
+
(content_type = $1 || ''.dup).chomp!
|
551
|
+
body.instance_variable_set(:@content_type, content_type)
|
552
|
+
## query parameter name
|
553
|
+
/Content-Disposition:.* name=(?:"(.*?)"|([^;\r\n]*))/i.match(head)
|
554
|
+
name = $1 || $2 || ''
|
555
|
+
if body.original_filename.empty?
|
556
|
+
value=body.read.dup.force_encoding(@accept_charset)
|
557
|
+
body.close! if defined?(Tempfile) && body.kind_of?(Tempfile)
|
558
|
+
(params[name] ||= []) << value
|
559
|
+
unless value.valid_encoding?
|
560
|
+
if @accept_charset_error_block
|
561
|
+
@accept_charset_error_block.call(name,value)
|
562
|
+
else
|
563
|
+
raise InvalidEncoding,"Accept-Charset encoding error"
|
564
|
+
end
|
565
|
+
end
|
566
|
+
class << params[name].last;self;end.class_eval do
|
567
|
+
define_method(:read){self}
|
568
|
+
define_method(:original_filename){""}
|
569
|
+
define_method(:content_type){""}
|
570
|
+
end
|
571
|
+
else
|
572
|
+
(params[name] ||= []) << body
|
573
|
+
@files[name]=body
|
574
|
+
end
|
575
|
+
## break loop
|
576
|
+
break if content_length == -1
|
577
|
+
end
|
578
|
+
raise EOFError, "bad boundary end of body part" unless boundary_end =~ /--/
|
579
|
+
params.default = []
|
580
|
+
params
|
581
|
+
rescue Exception
|
582
|
+
if tempfiles
|
583
|
+
tempfiles.each {|t|
|
584
|
+
if t.path
|
585
|
+
t.close!
|
586
|
+
end
|
587
|
+
}
|
588
|
+
end
|
589
|
+
raise
|
590
|
+
end # read_multipart
|
591
|
+
private :read_multipart
|
592
|
+
def create_body(is_large) #:nodoc:
|
593
|
+
if is_large
|
594
|
+
require 'tempfile'
|
595
|
+
body = Tempfile.new('CGI', encoding: Encoding::ASCII_8BIT)
|
596
|
+
else
|
597
|
+
begin
|
598
|
+
require 'stringio'
|
599
|
+
body = StringIO.new("".b)
|
600
|
+
rescue LoadError
|
601
|
+
require 'tempfile'
|
602
|
+
body = Tempfile.new('CGI', encoding: Encoding::ASCII_8BIT)
|
603
|
+
end
|
604
|
+
end
|
605
|
+
body.binmode if defined? body.binmode
|
606
|
+
return body
|
607
|
+
end
|
608
|
+
def unescape_filename? #:nodoc:
|
609
|
+
user_agent = $CGI_ENV['HTTP_USER_AGENT']
|
610
|
+
return false unless user_agent
|
611
|
+
return /Mac/i.match(user_agent) && /Mozilla/i.match(user_agent) && !/MSIE/i.match(user_agent)
|
612
|
+
end
|
613
|
+
|
614
|
+
# offline mode. read name=value pairs on standard input.
|
615
|
+
def read_from_cmdline
|
616
|
+
require "shellwords"
|
617
|
+
|
618
|
+
string = unless ARGV.empty?
|
619
|
+
ARGV.join(' ')
|
620
|
+
else
|
621
|
+
if STDIN.tty?
|
622
|
+
STDERR.print(
|
623
|
+
%|(offline mode: enter name=value pairs on standard input)\n|
|
624
|
+
)
|
625
|
+
end
|
626
|
+
array = readlines rescue nil
|
627
|
+
if not array.nil?
|
628
|
+
array.join(' ').gsub(/\n/n, '')
|
629
|
+
else
|
630
|
+
""
|
631
|
+
end
|
632
|
+
end.gsub(/\\=/n, '%3D').gsub(/\\&/n, '%26')
|
633
|
+
|
634
|
+
words = Shellwords.shellwords(string)
|
635
|
+
|
636
|
+
if words.find{|x| /=/n.match(x) }
|
637
|
+
words.join('&')
|
638
|
+
else
|
639
|
+
words.join('+')
|
640
|
+
end
|
641
|
+
end
|
642
|
+
private :read_from_cmdline
|
643
|
+
|
644
|
+
# A wrapper class to use a StringIO object as the body and switch
|
645
|
+
# to a TempFile when the passed threshold is passed.
|
646
|
+
# Initialize the data from the query.
|
647
|
+
#
|
648
|
+
# Handles multipart forms (in particular, forms that involve file uploads).
|
649
|
+
# Reads query parameters in the @params field, and cookies into @cookies.
|
650
|
+
def initialize_query()
|
651
|
+
if ("POST" == env_table['REQUEST_METHOD']) and
|
652
|
+
%r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?| =~ env_table['CONTENT_TYPE']
|
653
|
+
current_max_multipart_length = @max_multipart_length.respond_to?(:call) ? @max_multipart_length.call : @max_multipart_length
|
654
|
+
raise StandardError.new("too large multipart data.") if env_table['CONTENT_LENGTH'].to_i > current_max_multipart_length
|
655
|
+
boundary = $1.dup
|
656
|
+
@multipart = true
|
657
|
+
@params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
|
658
|
+
else
|
659
|
+
@multipart = false
|
660
|
+
@params = CGI.parse(
|
661
|
+
case env_table['REQUEST_METHOD']
|
662
|
+
when "GET", "HEAD"
|
663
|
+
if defined?(MOD_RUBY)
|
664
|
+
Apache::request.args or ""
|
665
|
+
else
|
666
|
+
env_table['QUERY_STRING'] or ""
|
667
|
+
end
|
668
|
+
when "POST"
|
669
|
+
stdinput.binmode if defined? stdinput.binmode
|
670
|
+
stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or ''
|
671
|
+
else
|
672
|
+
read_from_cmdline
|
673
|
+
end.dup.force_encoding(@accept_charset)
|
674
|
+
)
|
675
|
+
unless Encoding.find(@accept_charset) == Encoding::ASCII_8BIT
|
676
|
+
@params.each do |key,values|
|
677
|
+
values.each do |value|
|
678
|
+
unless value.valid_encoding?
|
679
|
+
if @accept_charset_error_block
|
680
|
+
@accept_charset_error_block.call(key,value)
|
681
|
+
else
|
682
|
+
raise InvalidEncoding,"Accept-Charset encoding error"
|
683
|
+
end
|
684
|
+
end
|
685
|
+
end
|
686
|
+
end
|
687
|
+
end
|
688
|
+
end
|
689
|
+
|
690
|
+
@cookies = CGI::Cookie.parse((env_table['HTTP_COOKIE'] or env_table['COOKIE']))
|
691
|
+
end
|
692
|
+
private :initialize_query
|
693
|
+
|
694
|
+
# Returns whether the form contained multipart/form-data
|
695
|
+
def multipart?
|
696
|
+
@multipart
|
697
|
+
end
|
698
|
+
|
699
|
+
# Get the value for the parameter with a given key.
|
700
|
+
#
|
701
|
+
# If the parameter has multiple values, only the first will be
|
702
|
+
# retrieved; use #params to get the array of values.
|
703
|
+
def [](key)
|
704
|
+
params = @params[key]
|
705
|
+
return '' unless params
|
706
|
+
value = params[0]
|
707
|
+
if @multipart
|
708
|
+
if value
|
709
|
+
return value
|
710
|
+
elsif defined? StringIO
|
711
|
+
StringIO.new("".b)
|
712
|
+
else
|
713
|
+
Tempfile.new("CGI",encoding: Encoding::ASCII_8BIT)
|
714
|
+
end
|
715
|
+
else
|
716
|
+
str = if value then value.dup else "" end
|
717
|
+
str
|
718
|
+
end
|
719
|
+
end
|
720
|
+
|
721
|
+
# Return all query parameter names as an array of String.
|
722
|
+
def keys(*args)
|
723
|
+
@params.keys(*args)
|
724
|
+
end
|
725
|
+
|
726
|
+
# Returns true if a given query string parameter exists.
|
727
|
+
def has_key?(*args)
|
728
|
+
@params.has_key?(*args)
|
729
|
+
end
|
730
|
+
alias key? has_key?
|
731
|
+
alias include? has_key?
|
732
|
+
|
733
|
+
end # QueryExtension
|
734
|
+
|
735
|
+
# Exception raised when there is an invalid encoding detected
|
736
|
+
class InvalidEncoding < Exception; end
|
737
|
+
|
738
|
+
# @@accept_charset is default accept character set.
|
739
|
+
# This default value default is "UTF-8"
|
740
|
+
# If you want to change the default accept character set
|
741
|
+
# when create a new CGI instance, set this:
|
742
|
+
#
|
743
|
+
# CGI.accept_charset = "EUC-JP"
|
744
|
+
#
|
745
|
+
@@accept_charset="UTF-8" if false # needed for rdoc?
|
746
|
+
|
747
|
+
# Return the accept character set for all new CGI instances.
|
748
|
+
def self.accept_charset
|
749
|
+
@@accept_charset
|
750
|
+
end
|
751
|
+
|
752
|
+
# Set the accept character set for all new CGI instances.
|
753
|
+
def self.accept_charset=(accept_charset)
|
754
|
+
@@accept_charset=accept_charset
|
755
|
+
end
|
756
|
+
|
757
|
+
# Return the accept character set for this CGI instance.
|
758
|
+
attr_reader :accept_charset
|
759
|
+
|
760
|
+
# @@max_multipart_length is the maximum length of multipart data.
|
761
|
+
# The default value is 128 * 1024 * 1024 bytes
|
762
|
+
#
|
763
|
+
# The default can be set to something else in the CGI constructor,
|
764
|
+
# via the :max_multipart_length key in the option hash.
|
765
|
+
#
|
766
|
+
# See CGI.new documentation.
|
767
|
+
#
|
768
|
+
@@max_multipart_length= 128 * 1024 * 1024
|
769
|
+
|
770
|
+
# Create a new CGI instance.
|
771
|
+
#
|
772
|
+
# :call-seq:
|
773
|
+
# CGI.new(tag_maker) { block }
|
774
|
+
# CGI.new(options_hash = {}) { block }
|
775
|
+
#
|
776
|
+
#
|
777
|
+
# <tt>tag_maker</tt>::
|
778
|
+
# This is the same as using the +options_hash+ form with the value <tt>{
|
779
|
+
# :tag_maker => tag_maker }</tt> Note that it is recommended to use the
|
780
|
+
# +options_hash+ form, since it also allows you specify the charset you
|
781
|
+
# will accept.
|
782
|
+
# <tt>options_hash</tt>::
|
783
|
+
# A Hash that recognizes three options:
|
784
|
+
#
|
785
|
+
# <tt>:accept_charset</tt>::
|
786
|
+
# specifies encoding of received query string. If omitted,
|
787
|
+
# <tt>@@accept_charset</tt> is used. If the encoding is not valid, a
|
788
|
+
# CGI::InvalidEncoding will be raised.
|
789
|
+
#
|
790
|
+
# Example. Suppose <tt>@@accept_charset</tt> is "UTF-8"
|
791
|
+
#
|
792
|
+
# when not specified:
|
793
|
+
#
|
794
|
+
# cgi=CGI.new # @accept_charset # => "UTF-8"
|
795
|
+
#
|
796
|
+
# when specified as "EUC-JP":
|
797
|
+
#
|
798
|
+
# cgi=CGI.new(:accept_charset => "EUC-JP") # => "EUC-JP"
|
799
|
+
#
|
800
|
+
# <tt>:tag_maker</tt>::
|
801
|
+
# String that specifies which version of the HTML generation methods to
|
802
|
+
# use. If not specified, no HTML generation methods will be loaded.
|
803
|
+
#
|
804
|
+
# The following values are supported:
|
805
|
+
#
|
806
|
+
# "html3":: HTML 3.x
|
807
|
+
# "html4":: HTML 4.0
|
808
|
+
# "html4Tr":: HTML 4.0 Transitional
|
809
|
+
# "html4Fr":: HTML 4.0 with Framesets
|
810
|
+
# "html5":: HTML 5
|
811
|
+
#
|
812
|
+
# <tt>:max_multipart_length</tt>::
|
813
|
+
# Specifies maximum length of multipart data. Can be an Integer scalar or
|
814
|
+
# a lambda, that will be evaluated when the request is parsed. This
|
815
|
+
# allows more complex logic to be set when determining whether to accept
|
816
|
+
# multipart data (e.g. consult a registered users upload allowance)
|
817
|
+
#
|
818
|
+
# Default is 128 * 1024 * 1024 bytes
|
819
|
+
#
|
820
|
+
# cgi=CGI.new(:max_multipart_length => 268435456) # simple scalar
|
821
|
+
#
|
822
|
+
# cgi=CGI.new(:max_multipart_length => -> {check_filesystem}) # lambda
|
823
|
+
#
|
824
|
+
# <tt>block</tt>::
|
825
|
+
# If provided, the block is called when an invalid encoding is
|
826
|
+
# encountered. For example:
|
827
|
+
#
|
828
|
+
# encoding_errors={}
|
829
|
+
# cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value|
|
830
|
+
# encoding_errors[name] = value
|
831
|
+
# end
|
832
|
+
#
|
833
|
+
# Finally, if the CGI object is not created in a standard CGI call
|
834
|
+
# environment (that is, it can't locate REQUEST_METHOD in its environment),
|
835
|
+
# then it will run in "offline" mode. In this mode, it reads its parameters
|
836
|
+
# from the command line or (failing that) from standard input. Otherwise,
|
837
|
+
# cookies and other parameters are parsed automatically from the standard
|
838
|
+
# CGI locations, which varies according to the REQUEST_METHOD.
|
839
|
+
def initialize(options = {}, &block) # :yields: name, value
|
840
|
+
@accept_charset_error_block = block_given? ? block : nil
|
841
|
+
@options={
|
842
|
+
:accept_charset=>@@accept_charset,
|
843
|
+
:max_multipart_length=>@@max_multipart_length
|
844
|
+
}
|
845
|
+
case options
|
846
|
+
when Hash
|
847
|
+
@options.merge!(options)
|
848
|
+
when String
|
849
|
+
@options[:tag_maker]=options
|
850
|
+
end
|
851
|
+
@accept_charset=@options[:accept_charset]
|
852
|
+
@max_multipart_length=@options[:max_multipart_length]
|
853
|
+
if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
|
854
|
+
Apache.request.setup_cgi_env
|
855
|
+
end
|
856
|
+
|
857
|
+
extend QueryExtension
|
858
|
+
@multipart = false
|
859
|
+
|
860
|
+
initialize_query() # set @params, @cookies
|
861
|
+
@output_cookies = nil
|
862
|
+
@output_hidden = nil
|
863
|
+
|
864
|
+
case @options[:tag_maker]
|
865
|
+
when "html3"
|
866
|
+
require_relative 'html'
|
867
|
+
extend Html3
|
868
|
+
extend HtmlExtension
|
869
|
+
when "html4"
|
870
|
+
require_relative 'html'
|
871
|
+
extend Html4
|
872
|
+
extend HtmlExtension
|
873
|
+
when "html4Tr"
|
874
|
+
require_relative 'html'
|
875
|
+
extend Html4Tr
|
876
|
+
extend HtmlExtension
|
877
|
+
when "html4Fr"
|
878
|
+
require_relative 'html'
|
879
|
+
extend Html4Tr
|
880
|
+
extend Html4Fr
|
881
|
+
extend HtmlExtension
|
882
|
+
when "html5"
|
883
|
+
require_relative 'html'
|
884
|
+
extend Html5
|
885
|
+
extend HtmlExtension
|
886
|
+
end
|
887
|
+
end
|
888
|
+
|
889
|
+
end # class CGI
|