cgi 0.1.0

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.

@@ -0,0 +1,888 @@
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+)/.match($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 CGI::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.taint)
548
+ ## content type
549
+ /Content-Type: (.*)/i.match(head)
550
+ (content_type = $1 || ''.dup).chomp!
551
+ body.instance_variable_set(:@content_type, content_type.taint)
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 /Mac/i.match(user_agent) && /Mozilla/i.match(user_agent) && !/MSIE/i.match(user_agent)
611
+ end
612
+
613
+ # offline mode. read name=value pairs on standard input.
614
+ def read_from_cmdline
615
+ require "shellwords"
616
+
617
+ string = unless ARGV.empty?
618
+ ARGV.join(' ')
619
+ else
620
+ if STDIN.tty?
621
+ STDERR.print(
622
+ %|(offline mode: enter name=value pairs on standard input)\n|
623
+ )
624
+ end
625
+ array = readlines rescue nil
626
+ if not array.nil?
627
+ array.join(' ').gsub(/\n/n, '')
628
+ else
629
+ ""
630
+ end
631
+ end.gsub(/\\=/n, '%3D').gsub(/\\&/n, '%26')
632
+
633
+ words = Shellwords.shellwords(string)
634
+
635
+ if words.find{|x| /=/n.match(x) }
636
+ words.join('&')
637
+ else
638
+ words.join('+')
639
+ end
640
+ end
641
+ private :read_from_cmdline
642
+
643
+ # A wrapper class to use a StringIO object as the body and switch
644
+ # to a TempFile when the passed threshold is passed.
645
+ # Initialize the data from the query.
646
+ #
647
+ # Handles multipart forms (in particular, forms that involve file uploads).
648
+ # Reads query parameters in the @params field, and cookies into @cookies.
649
+ def initialize_query()
650
+ if ("POST" == env_table['REQUEST_METHOD']) and
651
+ %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|.match(env_table['CONTENT_TYPE'])
652
+ current_max_multipart_length = @max_multipart_length.respond_to?(:call) ? @max_multipart_length.call : @max_multipart_length
653
+ raise StandardError.new("too large multipart data.") if env_table['CONTENT_LENGTH'].to_i > current_max_multipart_length
654
+ boundary = $1.dup
655
+ @multipart = true
656
+ @params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
657
+ else
658
+ @multipart = false
659
+ @params = CGI::parse(
660
+ case env_table['REQUEST_METHOD']
661
+ when "GET", "HEAD"
662
+ if defined?(MOD_RUBY)
663
+ Apache::request.args or ""
664
+ else
665
+ env_table['QUERY_STRING'] or ""
666
+ end
667
+ when "POST"
668
+ stdinput.binmode if defined? stdinput.binmode
669
+ stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or ''
670
+ else
671
+ read_from_cmdline
672
+ end.dup.force_encoding(@accept_charset)
673
+ )
674
+ unless Encoding.find(@accept_charset) == Encoding::ASCII_8BIT
675
+ @params.each do |key,values|
676
+ values.each do |value|
677
+ unless value.valid_encoding?
678
+ if @accept_charset_error_block
679
+ @accept_charset_error_block.call(key,value)
680
+ else
681
+ raise InvalidEncoding,"Accept-Charset encoding error"
682
+ end
683
+ end
684
+ end
685
+ end
686
+ end
687
+ end
688
+
689
+ @cookies = CGI::Cookie::parse((env_table['HTTP_COOKIE'] or env_table['COOKIE']))
690
+ end
691
+ private :initialize_query
692
+
693
+ # Returns whether the form contained multipart/form-data
694
+ def multipart?
695
+ @multipart
696
+ end
697
+
698
+ # Get the value for the parameter with a given key.
699
+ #
700
+ # If the parameter has multiple values, only the first will be
701
+ # retrieved; use #params to get the array of values.
702
+ def [](key)
703
+ params = @params[key]
704
+ return '' unless params
705
+ value = params[0]
706
+ if @multipart
707
+ if value
708
+ return value
709
+ elsif defined? StringIO
710
+ StringIO.new("".b)
711
+ else
712
+ Tempfile.new("CGI",encoding: Encoding::ASCII_8BIT)
713
+ end
714
+ else
715
+ str = if value then value.dup else "" end
716
+ str
717
+ end
718
+ end
719
+
720
+ # Return all query parameter names as an array of String.
721
+ def keys(*args)
722
+ @params.keys(*args)
723
+ end
724
+
725
+ # Returns true if a given query string parameter exists.
726
+ def has_key?(*args)
727
+ @params.has_key?(*args)
728
+ end
729
+ alias key? has_key?
730
+ alias include? has_key?
731
+
732
+ end # QueryExtension
733
+
734
+ # Exception raised when there is an invalid encoding detected
735
+ class InvalidEncoding < Exception; end
736
+
737
+ # @@accept_charset is default accept character set.
738
+ # This default value default is "UTF-8"
739
+ # If you want to change the default accept character set
740
+ # when create a new CGI instance, set this:
741
+ #
742
+ # CGI.accept_charset = "EUC-JP"
743
+ #
744
+ @@accept_charset="UTF-8" if false # needed for rdoc?
745
+
746
+ # Return the accept character set for all new CGI instances.
747
+ def self.accept_charset
748
+ @@accept_charset
749
+ end
750
+
751
+ # Set the accept character set for all new CGI instances.
752
+ def self.accept_charset=(accept_charset)
753
+ @@accept_charset=accept_charset
754
+ end
755
+
756
+ # Return the accept character set for this CGI instance.
757
+ attr_reader :accept_charset
758
+
759
+ # @@max_multipart_length is the maximum length of multipart data.
760
+ # The default value is 128 * 1024 * 1024 bytes
761
+ #
762
+ # The default can be set to something else in the CGI constructor,
763
+ # via the :max_multipart_length key in the option hash.
764
+ #
765
+ # See CGI.new documentation.
766
+ #
767
+ @@max_multipart_length= 128 * 1024 * 1024
768
+
769
+ # Create a new CGI instance.
770
+ #
771
+ # :call-seq:
772
+ # CGI.new(tag_maker) { block }
773
+ # CGI.new(options_hash = {}) { block }
774
+ #
775
+ #
776
+ # <tt>tag_maker</tt>::
777
+ # This is the same as using the +options_hash+ form with the value <tt>{
778
+ # :tag_maker => tag_maker }</tt> Note that it is recommended to use the
779
+ # +options_hash+ form, since it also allows you specify the charset you
780
+ # will accept.
781
+ # <tt>options_hash</tt>::
782
+ # A Hash that recognizes three options:
783
+ #
784
+ # <tt>:accept_charset</tt>::
785
+ # specifies encoding of received query string. If omitted,
786
+ # <tt>@@accept_charset</tt> is used. If the encoding is not valid, a
787
+ # CGI::InvalidEncoding will be raised.
788
+ #
789
+ # Example. Suppose <tt>@@accept_charset</tt> is "UTF-8"
790
+ #
791
+ # when not specified:
792
+ #
793
+ # cgi=CGI.new # @accept_charset # => "UTF-8"
794
+ #
795
+ # when specified as "EUC-JP":
796
+ #
797
+ # cgi=CGI.new(:accept_charset => "EUC-JP") # => "EUC-JP"
798
+ #
799
+ # <tt>:tag_maker</tt>::
800
+ # String that specifies which version of the HTML generation methods to
801
+ # use. If not specified, no HTML generation methods will be loaded.
802
+ #
803
+ # The following values are supported:
804
+ #
805
+ # "html3":: HTML 3.x
806
+ # "html4":: HTML 4.0
807
+ # "html4Tr":: HTML 4.0 Transitional
808
+ # "html4Fr":: HTML 4.0 with Framesets
809
+ # "html5":: HTML 5
810
+ #
811
+ # <tt>:max_multipart_length</tt>::
812
+ # Specifies maximum length of multipart data. Can be an Integer scalar or
813
+ # a lambda, that will be evaluated when the request is parsed. This
814
+ # allows more complex logic to be set when determining whether to accept
815
+ # multipart data (e.g. consult a registered users upload allowance)
816
+ #
817
+ # Default is 128 * 1024 * 1024 bytes
818
+ #
819
+ # cgi=CGI.new(:max_multipart_length => 268435456) # simple scalar
820
+ #
821
+ # cgi=CGI.new(:max_multipart_length => -> {check_filesystem}) # lambda
822
+ #
823
+ # <tt>block</tt>::
824
+ # If provided, the block is called when an invalid encoding is
825
+ # encountered. For example:
826
+ #
827
+ # encoding_errors={}
828
+ # cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value|
829
+ # encoding_errors[name] = value
830
+ # end
831
+ #
832
+ # Finally, if the CGI object is not created in a standard CGI call
833
+ # environment (that is, it can't locate REQUEST_METHOD in its environment),
834
+ # then it will run in "offline" mode. In this mode, it reads its parameters
835
+ # from the command line or (failing that) from standard input. Otherwise,
836
+ # cookies and other parameters are parsed automatically from the standard
837
+ # CGI locations, which varies according to the REQUEST_METHOD.
838
+ def initialize(options = {}, &block) # :yields: name, value
839
+ @accept_charset_error_block = block_given? ? block : nil
840
+ @options={
841
+ :accept_charset=>@@accept_charset,
842
+ :max_multipart_length=>@@max_multipart_length
843
+ }
844
+ case options
845
+ when Hash
846
+ @options.merge!(options)
847
+ when String
848
+ @options[:tag_maker]=options
849
+ end
850
+ @accept_charset=@options[:accept_charset]
851
+ @max_multipart_length=@options[:max_multipart_length]
852
+ if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
853
+ Apache.request.setup_cgi_env
854
+ end
855
+
856
+ extend QueryExtension
857
+ @multipart = false
858
+
859
+ initialize_query() # set @params, @cookies
860
+ @output_cookies = nil
861
+ @output_hidden = nil
862
+
863
+ case @options[:tag_maker]
864
+ when "html3"
865
+ require_relative 'html'
866
+ extend Html3
867
+ extend HtmlExtension
868
+ when "html4"
869
+ require_relative 'html'
870
+ extend Html4
871
+ extend HtmlExtension
872
+ when "html4Tr"
873
+ require_relative 'html'
874
+ extend Html4Tr
875
+ extend HtmlExtension
876
+ when "html4Fr"
877
+ require_relative 'html'
878
+ extend Html4Tr
879
+ extend Html4Fr
880
+ extend HtmlExtension
881
+ when "html5"
882
+ require_relative 'html'
883
+ extend Html5
884
+ extend HtmlExtension
885
+ end
886
+ end
887
+
888
+ end # class CGI