PageRenderTime 51ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/uri/common.rb

https://github.com/EarthJem/ruby
Ruby | 1239 lines | 638 code | 87 blank | 514 comment | 33 complexity | d0af633c24d6919ebfcb808bb7c86937 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause
  1. #--
  2. # = uri/common.rb
  3. #
  4. # Author:: Akira Yamada <akira@ruby-lang.org>
  5. # Revision:: $Id$
  6. # License::
  7. # You can redistribute it and/or modify it under the same term as Ruby.
  8. #
  9. # See URI for general documentation
  10. #
  11. module URI
  12. #
  13. # Includes URI::REGEXP::PATTERN
  14. #
  15. module REGEXP
  16. #
  17. # Patterns used to parse URI's
  18. #
  19. module PATTERN
  20. # :stopdoc:
  21. # RFC 2396 (URI Generic Syntax)
  22. # RFC 2732 (IPv6 Literal Addresses in URL's)
  23. # RFC 2373 (IPv6 Addressing Architecture)
  24. # alpha = lowalpha | upalpha
  25. ALPHA = "a-zA-Z"
  26. # alphanum = alpha | digit
  27. ALNUM = "#{ALPHA}\\d"
  28. # hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
  29. # "a" | "b" | "c" | "d" | "e" | "f"
  30. HEX = "a-fA-F\\d"
  31. # escaped = "%" hex hex
  32. ESCAPED = "%[#{HEX}]{2}"
  33. # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" |
  34. # "(" | ")"
  35. # unreserved = alphanum | mark
  36. UNRESERVED = "\\-_.!~*'()#{ALNUM}"
  37. # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  38. # "$" | ","
  39. # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  40. # "$" | "," | "[" | "]" (RFC 2732)
  41. RESERVED = ";/?:@&=+$,\\[\\]"
  42. # domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
  43. DOMLABEL = "(?:[#{ALNUM}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
  44. # toplabel = alpha | alpha *( alphanum | "-" ) alphanum
  45. TOPLABEL = "(?:[#{ALPHA}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
  46. # hostname = *( domainlabel "." ) toplabel [ "." ]
  47. HOSTNAME = "(?:#{DOMLABEL}\\.)*#{TOPLABEL}\\.?"
  48. # :startdoc:
  49. end # PATTERN
  50. # :startdoc:
  51. end # REGEXP
  52. # class that Parses String's into URI's
  53. #
  54. # It contains a Hash set of patterns and Regexp's that match and validate.
  55. #
  56. class Parser
  57. include REGEXP
  58. #
  59. # == Synopsis
  60. #
  61. # URI::Parser.new([opts])
  62. #
  63. # == Args
  64. #
  65. # The constructor accepts a hash as options for parser.
  66. # Keys of options are pattern names of URI components
  67. # and values of options are pattern strings.
  68. # The constructor generetes set of regexps for parsing URIs.
  69. #
  70. # You can use the following keys:
  71. #
  72. # * :ESCAPED (URI::PATTERN::ESCAPED in default)
  73. # * :UNRESERVED (URI::PATTERN::UNRESERVED in default)
  74. # * :DOMLABEL (URI::PATTERN::DOMLABEL in default)
  75. # * :TOPLABEL (URI::PATTERN::TOPLABEL in default)
  76. # * :HOSTNAME (URI::PATTERN::HOSTNAME in default)
  77. #
  78. # == Examples
  79. #
  80. # p = URI::Parser.new(:ESCAPED => "(?:%[a-fA-F0-9]{2}|%u[a-fA-F0-9]{4})")
  81. # u = p.parse("http://example.jp/%uABCD") #=> #<URI::HTTP:0xb78cf4f8 URL:http://example.jp/%uABCD>
  82. # URI.parse(u.to_s) #=> raises URI::InvalidURIError
  83. #
  84. # s = "http://examle.com/ABCD"
  85. # u1 = p.parse(s) #=> #<URI::HTTP:0xb78c3220 URL:http://example.com/ABCD>
  86. # u2 = URI.parse(s) #=> #<URI::HTTP:0xb78b6d54 URL:http://example.com/ABCD>
  87. # u1 == u2 #=> true
  88. # u1.eql?(u2) #=> false
  89. #
  90. def initialize(opts = {})
  91. @pattern = initialize_pattern(opts)
  92. @pattern.each_value {|v| v.freeze}
  93. @pattern.freeze
  94. @regexp = initialize_regexp(@pattern)
  95. @regexp.each_value {|v| v.freeze}
  96. @regexp.freeze
  97. end
  98. # The Hash of patterns.
  99. #
  100. # see also URI::Parser.initialize_pattern
  101. attr_reader :pattern
  102. # The Hash of Regexp
  103. #
  104. # see also URI::Parser.initialize_regexp
  105. attr_reader :regexp
  106. # Returns a split URI against regexp[:ABS_URI]
  107. def split(uri)
  108. case uri
  109. when ''
  110. # null uri
  111. when @regexp[:ABS_URI]
  112. scheme, opaque, userinfo, host, port,
  113. registry, path, query, fragment = $~[1..-1]
  114. # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
  115. # absoluteURI = scheme ":" ( hier_part | opaque_part )
  116. # hier_part = ( net_path | abs_path ) [ "?" query ]
  117. # opaque_part = uric_no_slash *uric
  118. # abs_path = "/" path_segments
  119. # net_path = "//" authority [ abs_path ]
  120. # authority = server | reg_name
  121. # server = [ [ userinfo "@" ] hostport ]
  122. if !scheme
  123. raise InvalidURIError,
  124. "bad URI(absolute but no scheme): #{uri}"
  125. end
  126. if !opaque && (!path && (!host && !registry))
  127. raise InvalidURIError,
  128. "bad URI(absolute but no path): #{uri}"
  129. end
  130. when @regexp[:REL_URI]
  131. scheme = nil
  132. opaque = nil
  133. userinfo, host, port, registry,
  134. rel_segment, abs_path, query, fragment = $~[1..-1]
  135. if rel_segment && abs_path
  136. path = rel_segment + abs_path
  137. elsif rel_segment
  138. path = rel_segment
  139. elsif abs_path
  140. path = abs_path
  141. end
  142. # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
  143. # relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
  144. # net_path = "//" authority [ abs_path ]
  145. # abs_path = "/" path_segments
  146. # rel_path = rel_segment [ abs_path ]
  147. # authority = server | reg_name
  148. # server = [ [ userinfo "@" ] hostport ]
  149. else
  150. raise InvalidURIError, "bad URI(is not URI?): #{uri}"
  151. end
  152. path = '' if !path && !opaque # (see RFC2396 Section 5.2)
  153. ret = [
  154. scheme,
  155. userinfo, host, port, # X
  156. registry, # X
  157. path, # Y
  158. opaque, # Y
  159. query,
  160. fragment
  161. ]
  162. return ret
  163. end
  164. #
  165. # == Args
  166. #
  167. # +uri+::
  168. # String
  169. #
  170. # == Description
  171. #
  172. # parses +uri+ and constructs either matching URI scheme object
  173. # (FTP, HTTP, HTTPS, LDAP, LDAPS, or MailTo) or URI::Generic
  174. #
  175. # == Usage
  176. #
  177. # p = URI::Parser.new
  178. # p.parse("ldap://ldap.example.com/dc=example?user=john")
  179. # #=> #<URI::LDAP:0x00000000b9e7e8 URL:ldap://ldap.example.com/dc=example?user=john>
  180. #
  181. def parse(uri)
  182. scheme, userinfo, host, port,
  183. registry, path, opaque, query, fragment = self.split(uri)
  184. if scheme && URI.scheme_list.include?(scheme.upcase)
  185. URI.scheme_list[scheme.upcase].new(scheme, userinfo, host, port,
  186. registry, path, opaque, query,
  187. fragment, self)
  188. else
  189. Generic.new(scheme, userinfo, host, port,
  190. registry, path, opaque, query,
  191. fragment, self)
  192. end
  193. end
  194. #
  195. # == Args
  196. #
  197. # +uris+::
  198. # an Array of Strings
  199. #
  200. # == Description
  201. #
  202. # Attempts to parse and merge a set of URIs
  203. #
  204. def join(*uris)
  205. uris[0] = convert_to_uri(uris[0])
  206. uris.inject :merge
  207. end
  208. #
  209. # :call-seq:
  210. # extract( str )
  211. # extract( str, schemes )
  212. # extract( str, schemes ) {|item| block }
  213. #
  214. # == Args
  215. #
  216. # +str+::
  217. # String to search
  218. # +schemes+::
  219. # Patterns to apply to +str+
  220. #
  221. # == Description
  222. #
  223. # Attempts to parse and merge a set of URIs
  224. # If no +block+ given , then returns the result,
  225. # else it calls +block+ for each element in result.
  226. #
  227. # see also URI::Parser.make_regexp
  228. #
  229. def extract(str, schemes = nil)
  230. if block_given?
  231. str.scan(make_regexp(schemes)) { yield $& }
  232. nil
  233. else
  234. result = []
  235. str.scan(make_regexp(schemes)) { result.push $& }
  236. result
  237. end
  238. end
  239. # returns Regexp that is default self.regexp[:ABS_URI_REF],
  240. # unless +schemes+ is provided. Then it is a Regexp.union with self.pattern[:X_ABS_URI]
  241. def make_regexp(schemes = nil)
  242. unless schemes
  243. @regexp[:ABS_URI_REF]
  244. else
  245. /(?=#{Regexp.union(*schemes)}:)#{@pattern[:X_ABS_URI]}/x
  246. end
  247. end
  248. #
  249. # :call-seq:
  250. # escape( str )
  251. # escape( str, unsafe )
  252. #
  253. # == Args
  254. #
  255. # +str+::
  256. # String to make safe
  257. # +unsafe+::
  258. # Regexp to apply. Defaults to self.regexp[:UNSAFE]
  259. #
  260. # == Description
  261. #
  262. # constructs a safe String from +str+, removing unsafe characters,
  263. # replacing them with codes.
  264. #
  265. def escape(str, unsafe = @regexp[:UNSAFE])
  266. unless unsafe.kind_of?(Regexp)
  267. # perhaps unsafe is String object
  268. unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false)
  269. end
  270. str.gsub(unsafe) do
  271. us = $&
  272. tmp = ''
  273. us.each_byte do |uc|
  274. tmp << sprintf('%%%02X', uc)
  275. end
  276. tmp
  277. end.force_encoding(Encoding::US_ASCII)
  278. end
  279. #
  280. # :call-seq:
  281. # unescape( str )
  282. # unescape( str, unsafe )
  283. #
  284. # == Args
  285. #
  286. # +str+::
  287. # String to remove escapes from
  288. # +unsafe+::
  289. # Regexp to apply. Defaults to self.regexp[:ESCAPED]
  290. #
  291. # == Description
  292. #
  293. # Removes escapes from +str+
  294. #
  295. def unescape(str, escaped = @regexp[:ESCAPED])
  296. str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(str.encoding)
  297. end
  298. @@to_s = Kernel.instance_method(:to_s)
  299. def inspect
  300. @@to_s.bind(self).call
  301. end
  302. private
  303. # Constructs the default Hash of patterns
  304. def initialize_pattern(opts = {})
  305. ret = {}
  306. ret[:ESCAPED] = escaped = (opts.delete(:ESCAPED) || PATTERN::ESCAPED)
  307. ret[:UNRESERVED] = unreserved = opts.delete(:UNRESERVED) || PATTERN::UNRESERVED
  308. ret[:RESERVED] = reserved = opts.delete(:RESERVED) || PATTERN::RESERVED
  309. ret[:DOMLABEL] = opts.delete(:DOMLABEL) || PATTERN::DOMLABEL
  310. ret[:TOPLABEL] = opts.delete(:TOPLABEL) || PATTERN::TOPLABEL
  311. ret[:HOSTNAME] = hostname = opts.delete(:HOSTNAME)
  312. # RFC 2396 (URI Generic Syntax)
  313. # RFC 2732 (IPv6 Literal Addresses in URL's)
  314. # RFC 2373 (IPv6 Addressing Architecture)
  315. # uric = reserved | unreserved | escaped
  316. ret[:URIC] = uric = "(?:[#{unreserved}#{reserved}]|#{escaped})"
  317. # uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
  318. # "&" | "=" | "+" | "$" | ","
  319. ret[:URIC_NO_SLASH] = uric_no_slash = "(?:[#{unreserved};?:@&=+$,]|#{escaped})"
  320. # query = *uric
  321. ret[:QUERY] = query = "#{uric}*"
  322. # fragment = *uric
  323. ret[:FRAGMENT] = fragment = "#{uric}*"
  324. # hostname = *( domainlabel "." ) toplabel [ "." ]
  325. # reg-name = *( unreserved / pct-encoded / sub-delims ) # RFC3986
  326. unless hostname
  327. ret[:HOSTNAME] = hostname = "(?:[a-zA-Z0-9\\-.]|%\\h\\h)+"
  328. end
  329. # RFC 2373, APPENDIX B:
  330. # IPv6address = hexpart [ ":" IPv4address ]
  331. # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
  332. # hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
  333. # hexseq = hex4 *( ":" hex4)
  334. # hex4 = 1*4HEXDIG
  335. #
  336. # XXX: This definition has a flaw. "::" + IPv4address must be
  337. # allowed too. Here is a replacement.
  338. #
  339. # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
  340. ret[:IPV4ADDR] = ipv4addr = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"
  341. # hex4 = 1*4HEXDIG
  342. hex4 = "[#{PATTERN::HEX}]{1,4}"
  343. # lastpart = hex4 | IPv4address
  344. lastpart = "(?:#{hex4}|#{ipv4addr})"
  345. # hexseq1 = *( hex4 ":" ) hex4
  346. hexseq1 = "(?:#{hex4}:)*#{hex4}"
  347. # hexseq2 = *( hex4 ":" ) lastpart
  348. hexseq2 = "(?:#{hex4}:)*#{lastpart}"
  349. # IPv6address = hexseq2 | [ hexseq1 ] "::" [ hexseq2 ]
  350. ret[:IPV6ADDR] = ipv6addr = "(?:#{hexseq2}|(?:#{hexseq1})?::(?:#{hexseq2})?)"
  351. # IPv6prefix = ( hexseq1 | [ hexseq1 ] "::" [ hexseq1 ] ) "/" 1*2DIGIT
  352. # unused
  353. # ipv6reference = "[" IPv6address "]" (RFC 2732)
  354. ret[:IPV6REF] = ipv6ref = "\\[#{ipv6addr}\\]"
  355. # host = hostname | IPv4address
  356. # host = hostname | IPv4address | IPv6reference (RFC 2732)
  357. ret[:HOST] = host = "(?:#{hostname}|#{ipv4addr}|#{ipv6ref})"
  358. # port = *digit
  359. port = '\d*'
  360. # hostport = host [ ":" port ]
  361. ret[:HOSTPORT] = hostport = "#{host}(?::#{port})?"
  362. # userinfo = *( unreserved | escaped |
  363. # ";" | ":" | "&" | "=" | "+" | "$" | "," )
  364. ret[:USERINFO] = userinfo = "(?:[#{unreserved};:&=+$,]|#{escaped})*"
  365. # pchar = unreserved | escaped |
  366. # ":" | "@" | "&" | "=" | "+" | "$" | ","
  367. pchar = "(?:[#{unreserved}:@&=+$,]|#{escaped})"
  368. # param = *pchar
  369. param = "#{pchar}*"
  370. # segment = *pchar *( ";" param )
  371. segment = "#{pchar}*(?:;#{param})*"
  372. # path_segments = segment *( "/" segment )
  373. ret[:PATH_SEGMENTS] = path_segments = "#{segment}(?:/#{segment})*"
  374. # server = [ [ userinfo "@" ] hostport ]
  375. server = "(?:#{userinfo}@)?#{hostport}"
  376. # reg_name = 1*( unreserved | escaped | "$" | "," |
  377. # ";" | ":" | "@" | "&" | "=" | "+" )
  378. ret[:REG_NAME] = reg_name = "(?:[#{unreserved}$,;:@&=+]|#{escaped})+"
  379. # authority = server | reg_name
  380. authority = "(?:#{server}|#{reg_name})"
  381. # rel_segment = 1*( unreserved | escaped |
  382. # ";" | "@" | "&" | "=" | "+" | "$" | "," )
  383. ret[:REL_SEGMENT] = rel_segment = "(?:[#{unreserved};@&=+$,]|#{escaped})+"
  384. # scheme = alpha *( alpha | digit | "+" | "-" | "." )
  385. ret[:SCHEME] = scheme = "[#{PATTERN::ALPHA}][\\-+.#{PATTERN::ALPHA}\\d]*"
  386. # abs_path = "/" path_segments
  387. ret[:ABS_PATH] = abs_path = "/#{path_segments}"
  388. # rel_path = rel_segment [ abs_path ]
  389. ret[:REL_PATH] = rel_path = "#{rel_segment}(?:#{abs_path})?"
  390. # net_path = "//" authority [ abs_path ]
  391. ret[:NET_PATH] = net_path = "//#{authority}(?:#{abs_path})?"
  392. # hier_part = ( net_path | abs_path ) [ "?" query ]
  393. ret[:HIER_PART] = hier_part = "(?:#{net_path}|#{abs_path})(?:\\?(?:#{query}))?"
  394. # opaque_part = uric_no_slash *uric
  395. ret[:OPAQUE_PART] = opaque_part = "#{uric_no_slash}#{uric}*"
  396. # absoluteURI = scheme ":" ( hier_part | opaque_part )
  397. ret[:ABS_URI] = abs_uri = "#{scheme}:(?:#{hier_part}|#{opaque_part})"
  398. # relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
  399. ret[:REL_URI] = rel_uri = "(?:#{net_path}|#{abs_path}|#{rel_path})(?:\\?#{query})?"
  400. # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
  401. ret[:URI_REF] = "(?:#{abs_uri}|#{rel_uri})?(?:##{fragment})?"
  402. ret[:X_ABS_URI] = "
  403. (#{scheme}): (?# 1: scheme)
  404. (?:
  405. (#{opaque_part}) (?# 2: opaque)
  406. |
  407. (?:(?:
  408. //(?:
  409. (?:(?:(#{userinfo})@)? (?# 3: userinfo)
  410. (?:(#{host})(?::(\\d*))?))? (?# 4: host, 5: port)
  411. |
  412. (#{reg_name}) (?# 6: registry)
  413. )
  414. |
  415. (?!//)) (?# XXX: '//' is the mark for hostport)
  416. (#{abs_path})? (?# 7: path)
  417. )(?:\\?(#{query}))? (?# 8: query)
  418. )
  419. (?:\\#(#{fragment}))? (?# 9: fragment)
  420. "
  421. ret[:X_REL_URI] = "
  422. (?:
  423. (?:
  424. //
  425. (?:
  426. (?:(#{userinfo})@)? (?# 1: userinfo)
  427. (#{host})?(?::(\\d*))? (?# 2: host, 3: port)
  428. |
  429. (#{reg_name}) (?# 4: registry)
  430. )
  431. )
  432. |
  433. (#{rel_segment}) (?# 5: rel_segment)
  434. )?
  435. (#{abs_path})? (?# 6: abs_path)
  436. (?:\\?(#{query}))? (?# 7: query)
  437. (?:\\#(#{fragment}))? (?# 8: fragment)
  438. "
  439. ret
  440. end
  441. # Constructs the default Hash of Regexp's
  442. def initialize_regexp(pattern)
  443. ret = {}
  444. # for URI::split
  445. ret[:ABS_URI] = Regexp.new('\A\s*' + pattern[:X_ABS_URI] + '\s*\z', Regexp::EXTENDED)
  446. ret[:REL_URI] = Regexp.new('\A\s*' + pattern[:X_REL_URI] + '\s*\z', Regexp::EXTENDED)
  447. # for URI::extract
  448. ret[:URI_REF] = Regexp.new(pattern[:URI_REF])
  449. ret[:ABS_URI_REF] = Regexp.new(pattern[:X_ABS_URI], Regexp::EXTENDED)
  450. ret[:REL_URI_REF] = Regexp.new(pattern[:X_REL_URI], Regexp::EXTENDED)
  451. # for URI::escape/unescape
  452. ret[:ESCAPED] = Regexp.new(pattern[:ESCAPED])
  453. ret[:UNSAFE] = Regexp.new("[^#{pattern[:UNRESERVED]}#{pattern[:RESERVED]}]")
  454. # for Generic#initialize
  455. ret[:SCHEME] = Regexp.new("\\A#{pattern[:SCHEME]}\\z")
  456. ret[:USERINFO] = Regexp.new("\\A#{pattern[:USERINFO]}\\z")
  457. ret[:HOST] = Regexp.new("\\A#{pattern[:HOST]}\\z")
  458. ret[:PORT] = Regexp.new("\\A#{pattern[:PORT]}\\z")
  459. ret[:OPAQUE] = Regexp.new("\\A#{pattern[:OPAQUE_PART]}\\z")
  460. ret[:REGISTRY] = Regexp.new("\\A#{pattern[:REG_NAME]}\\z")
  461. ret[:ABS_PATH] = Regexp.new("\\A#{pattern[:ABS_PATH]}\\z")
  462. ret[:REL_PATH] = Regexp.new("\\A#{pattern[:REL_PATH]}\\z")
  463. ret[:QUERY] = Regexp.new("\\A#{pattern[:QUERY]}\\z")
  464. ret[:FRAGMENT] = Regexp.new("\\A#{pattern[:FRAGMENT]}\\z")
  465. ret
  466. end
  467. def convert_to_uri(uri)
  468. if uri.is_a?(URI::Generic)
  469. uri
  470. elsif uri = String.try_convert(uri)
  471. parse(uri)
  472. else
  473. raise ArgumentError,
  474. "bad argument (expected URI object or URI string)"
  475. end
  476. end
  477. end # class Parser
  478. # URI::Parser.new
  479. DEFAULT_PARSER = Parser.new
  480. DEFAULT_PARSER.pattern.each_pair do |sym, str|
  481. unless REGEXP::PATTERN.const_defined?(sym)
  482. REGEXP::PATTERN.const_set(sym, str)
  483. end
  484. end
  485. DEFAULT_PARSER.regexp.each_pair do |sym, str|
  486. const_set(sym, str)
  487. end
  488. module Util # :nodoc:
  489. def make_components_hash(klass, array_hash)
  490. tmp = {}
  491. if array_hash.kind_of?(Array) &&
  492. array_hash.size == klass.component.size - 1
  493. klass.component[1..-1].each_index do |i|
  494. begin
  495. tmp[klass.component[i + 1]] = array_hash[i].clone
  496. rescue TypeError
  497. tmp[klass.component[i + 1]] = array_hash[i]
  498. end
  499. end
  500. elsif array_hash.kind_of?(Hash)
  501. array_hash.each do |key, value|
  502. begin
  503. tmp[key] = value.clone
  504. rescue TypeError
  505. tmp[key] = value
  506. end
  507. end
  508. else
  509. raise ArgumentError,
  510. "expected Array of or Hash of components of #{klass.to_s} (#{klass.component[1..-1].join(', ')})"
  511. end
  512. tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase
  513. return tmp
  514. end
  515. module_function :make_components_hash
  516. end
  517. # module for escaping unsafe characters with codes.
  518. module Escape
  519. #
  520. # == Synopsis
  521. #
  522. # URI.escape(str [, unsafe])
  523. #
  524. # == Args
  525. #
  526. # +str+::
  527. # String to replaces in.
  528. # +unsafe+::
  529. # Regexp that matches all symbols that must be replaced with codes.
  530. # By default uses <tt>REGEXP::UNSAFE</tt>.
  531. # When this argument is a String, it represents a character set.
  532. #
  533. # == Description
  534. #
  535. # Escapes the string, replacing all unsafe characters with codes.
  536. #
  537. # == Usage
  538. #
  539. # require 'uri'
  540. #
  541. # enc_uri = URI.escape("http://example.com/?a=\11\15")
  542. # p enc_uri
  543. # # => "http://example.com/?a=%09%0D"
  544. #
  545. # p URI.unescape(enc_uri)
  546. # # => "http://example.com/?a=\t\r"
  547. #
  548. # p URI.escape("@?@!", "!?")
  549. # # => "@%3F@%21"
  550. #
  551. def escape(*arg)
  552. warn "#{caller(1)[0]}: warning: URI.escape is obsolete" if $VERBOSE
  553. DEFAULT_PARSER.escape(*arg)
  554. end
  555. alias encode escape
  556. #
  557. # == Synopsis
  558. #
  559. # URI.unescape(str)
  560. #
  561. # == Args
  562. #
  563. # +str+::
  564. # Unescapes the string.
  565. #
  566. # == Usage
  567. #
  568. # require 'uri'
  569. #
  570. # enc_uri = URI.escape("http://example.com/?a=\11\15")
  571. # p enc_uri
  572. # # => "http://example.com/?a=%09%0D"
  573. #
  574. # p URI.unescape(enc_uri)
  575. # # => "http://example.com/?a=\t\r"
  576. #
  577. def unescape(*arg)
  578. warn "#{caller(1)[0]}: warning: URI.unescape is obsolete" if $VERBOSE
  579. DEFAULT_PARSER.unescape(*arg)
  580. end
  581. alias decode unescape
  582. end # module Escape
  583. extend Escape
  584. include REGEXP
  585. @@schemes = {}
  586. # Returns a Hash of the defined schemes
  587. def self.scheme_list
  588. @@schemes
  589. end
  590. #
  591. # Base class for all URI exceptions.
  592. #
  593. class Error < StandardError; end
  594. #
  595. # Not a URI.
  596. #
  597. class InvalidURIError < Error; end
  598. #
  599. # Not a URI component.
  600. #
  601. class InvalidComponentError < Error; end
  602. #
  603. # URI is valid, bad usage is not.
  604. #
  605. class BadURIError < Error; end
  606. #
  607. # == Synopsis
  608. #
  609. # URI::split(uri)
  610. #
  611. # == Args
  612. #
  613. # +uri+::
  614. # String with URI.
  615. #
  616. # == Description
  617. #
  618. # Splits the string on following parts and returns array with result:
  619. #
  620. # * Scheme
  621. # * Userinfo
  622. # * Host
  623. # * Port
  624. # * Registry
  625. # * Path
  626. # * Opaque
  627. # * Query
  628. # * Fragment
  629. #
  630. # == Usage
  631. #
  632. # require 'uri'
  633. #
  634. # p URI.split("http://www.ruby-lang.org/")
  635. # # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
  636. #
  637. def self.split(uri)
  638. DEFAULT_PARSER.split(uri)
  639. end
  640. #
  641. # == Synopsis
  642. #
  643. # URI::parse(uri_str)
  644. #
  645. # == Args
  646. #
  647. # +uri_str+::
  648. # String with URI.
  649. #
  650. # == Description
  651. #
  652. # Creates one of the URI's subclasses instance from the string.
  653. #
  654. # == Raises
  655. #
  656. # URI::InvalidURIError
  657. # Raised if URI given is not a correct one.
  658. #
  659. # == Usage
  660. #
  661. # require 'uri'
  662. #
  663. # uri = URI.parse("http://www.ruby-lang.org/")
  664. # p uri
  665. # # => #<URI::HTTP:0x202281be URL:http://www.ruby-lang.org/>
  666. # p uri.scheme
  667. # # => "http"
  668. # p uri.host
  669. # # => "www.ruby-lang.org"
  670. #
  671. def self.parse(uri)
  672. DEFAULT_PARSER.parse(uri)
  673. end
  674. #
  675. # == Synopsis
  676. #
  677. # URI::join(str[, str, ...])
  678. #
  679. # == Args
  680. #
  681. # +str+::
  682. # String(s) to work with
  683. #
  684. # == Description
  685. #
  686. # Joins URIs.
  687. #
  688. # == Usage
  689. #
  690. # require 'uri'
  691. #
  692. # p URI.join("http://example.com/","main.rbx")
  693. # # => #<URI::HTTP:0x2022ac02 URL:http://localhost/main.rbx>
  694. #
  695. # p URI.join('http://example.com', 'foo')
  696. # # => #<URI::HTTP:0x01ab80a0 URL:http://example.com/foo>
  697. #
  698. # p URI.join('http://example.com', '/foo', '/bar')
  699. # # => #<URI::HTTP:0x01aaf0b0 URL:http://example.com/bar>
  700. #
  701. # p URI.join('http://example.com', '/foo', 'bar')
  702. # # => #<URI::HTTP:0x801a92af0 URL:http://example.com/bar>
  703. #
  704. # p URI.join('http://example.com', '/foo/', 'bar')
  705. # # => #<URI::HTTP:0x80135a3a0 URL:http://example.com/foo/bar>
  706. #
  707. #
  708. def self.join(*str)
  709. DEFAULT_PARSER.join(*str)
  710. end
  711. #
  712. # == Synopsis
  713. #
  714. # URI::extract(str[, schemes][,&blk])
  715. #
  716. # == Args
  717. #
  718. # +str+::
  719. # String to extract URIs from.
  720. # +schemes+::
  721. # Limit URI matching to a specific schemes.
  722. #
  723. # == Description
  724. #
  725. # Extracts URIs from a string. If block given, iterates through all matched URIs.
  726. # Returns nil if block given or array with matches.
  727. #
  728. # == Usage
  729. #
  730. # require "uri"
  731. #
  732. # URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
  733. # # => ["http://foo.example.com/bla", "mailto:test@example.com"]
  734. #
  735. def self.extract(str, schemes = nil, &block)
  736. DEFAULT_PARSER.extract(str, schemes, &block)
  737. end
  738. #
  739. # == Synopsis
  740. #
  741. # URI::regexp([match_schemes])
  742. #
  743. # == Args
  744. #
  745. # +match_schemes+::
  746. # Array of schemes. If given, resulting regexp matches to URIs
  747. # whose scheme is one of the match_schemes.
  748. #
  749. # == Description
  750. # Returns a Regexp object which matches to URI-like strings.
  751. # The Regexp object returned by this method includes arbitrary
  752. # number of capture group (parentheses). Never rely on it's number.
  753. #
  754. # == Usage
  755. #
  756. # require 'uri'
  757. #
  758. # # extract first URI from html_string
  759. # html_string.slice(URI.regexp)
  760. #
  761. # # remove ftp URIs
  762. # html_string.sub(URI.regexp(['ftp'])
  763. #
  764. # # You should not rely on the number of parentheses
  765. # html_string.scan(URI.regexp) do |*matches|
  766. # p $&
  767. # end
  768. #
  769. def self.regexp(schemes = nil)
  770. DEFAULT_PARSER.make_regexp(schemes)
  771. end
  772. TBLENCWWWCOMP_ = {} # :nodoc:
  773. 256.times do |i|
  774. TBLENCWWWCOMP_[i.chr] = '%%%02X' % i
  775. end
  776. TBLENCWWWCOMP_[' '] = '+'
  777. TBLENCWWWCOMP_.freeze
  778. TBLDECWWWCOMP_ = {} # :nodoc:
  779. 256.times do |i|
  780. h, l = i>>4, i&15
  781. TBLDECWWWCOMP_['%%%X%X' % [h, l]] = i.chr
  782. TBLDECWWWCOMP_['%%%x%X' % [h, l]] = i.chr
  783. TBLDECWWWCOMP_['%%%X%x' % [h, l]] = i.chr
  784. TBLDECWWWCOMP_['%%%x%x' % [h, l]] = i.chr
  785. end
  786. TBLDECWWWCOMP_['+'] = ' '
  787. TBLDECWWWCOMP_.freeze
  788. HTML5ASCIIINCOMPAT = [Encoding::UTF_7, Encoding::UTF_16BE, Encoding::UTF_16LE,
  789. Encoding::UTF_32BE, Encoding::UTF_32LE] # :nodoc:
  790. # Encode given +str+ to URL-encoded form data.
  791. #
  792. # This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP
  793. # (ASCII space) to + and converts others to %XX.
  794. #
  795. # If +enc+ is given, convert +str+ to the encoding before percent encoding.
  796. #
  797. # This is an implementation of
  798. # http://www.w3.org/TR/html5/association-of-controls-and-forms.html#url-encoded-form-data
  799. #
  800. # See URI.decode_www_form_component, URI.encode_www_form
  801. def self.encode_www_form_component(str, enc=nil)
  802. str = str.to_s.dup
  803. if str.encoding != Encoding::ASCII_8BIT
  804. if enc && enc != Encoding::ASCII_8BIT
  805. str.encode!(Encoding::UTF_8, invalid: :replace, undef: :replace)
  806. str.encode!(enc, fallback: ->(x){"&#{x.ord};"})
  807. end
  808. str.force_encoding(Encoding::ASCII_8BIT)
  809. end
  810. str.gsub!(/[^*\-.0-9A-Z_a-z]/, TBLENCWWWCOMP_)
  811. str.force_encoding(Encoding::US_ASCII)
  812. end
  813. # Decode given +str+ of URL-encoded form data.
  814. #
  815. # This decodes + to SP.
  816. #
  817. # See URI.encode_www_form_component, URI.decode_www_form
  818. def self.decode_www_form_component(str, enc=Encoding::UTF_8)
  819. raise ArgumentError, "invalid %-encoding (#{str})" unless /\A[^%]*(?:%\h\h[^%]*)*\z/ =~ str
  820. str.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
  821. end
  822. # Generate URL-encoded form data from given +enum+.
  823. #
  824. # This generates application/x-www-form-urlencoded data defined in HTML5
  825. # from given an Enumerable object.
  826. #
  827. # This internally uses URI.encode_www_form_component(str).
  828. #
  829. # This method doesn't convert the encoding of given items, so convert them
  830. # before call this method if you want to send data as other than original
  831. # encoding or mixed encoding data. (Strings which are encoded in an HTML5
  832. # ASCII incompatible encoding are converted to UTF-8.)
  833. #
  834. # This method doesn't handle files. When you send a file, use
  835. # multipart/form-data.
  836. #
  837. # This refers http://url.spec.whatwg.org/#concept-urlencoded-serializer
  838. #
  839. # URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
  840. # #=> "q=ruby&lang=en"
  841. # URI.encode_www_form("q" => "ruby", "lang" => "en")
  842. # #=> "q=ruby&lang=en"
  843. # URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
  844. # #=> "q=ruby&q=perl&lang=en"
  845. # URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
  846. # #=> "q=ruby&q=perl&lang=en"
  847. #
  848. # See URI.encode_www_form_component, URI.decode_www_form
  849. def self.encode_www_form(enum, enc=nil)
  850. enum.map do |k,v|
  851. if v.nil?
  852. encode_www_form_component(k, enc)
  853. elsif v.respond_to?(:to_ary)
  854. v.to_ary.map do |w|
  855. str = encode_www_form_component(k, enc)
  856. unless w.nil?
  857. str << '='
  858. str << encode_www_form_component(w, enc)
  859. end
  860. end.join('&')
  861. else
  862. str = encode_www_form_component(k, enc)
  863. str << '='
  864. str << encode_www_form_component(v, enc)
  865. end
  866. end.join('&')
  867. end
  868. # Decode URL-encoded form data from given +str+.
  869. #
  870. # This decodes application/x-www-form-urlencoded data
  871. # and returns array of key-value array.
  872. #
  873. # This refers http://url.spec.whatwg.org/#concept-urlencoded-parser ,
  874. # so this supports only &-separator, don't support ;-separator.
  875. #
  876. # ary = URI.decode_www_form("a=1&a=2&b=3")
  877. # p ary #=> [['a', '1'], ['a', '2'], ['b', '3']]
  878. # p ary.assoc('a').last #=> '1'
  879. # p ary.assoc('b').last #=> '3'
  880. # p ary.rassoc('a').last #=> '2'
  881. # p Hash[ary] # => {"a"=>"2", "b"=>"3"}
  882. #
  883. # See URI.decode_www_form_component, URI.encode_www_form
  884. def self.decode_www_form(str, enc=Encoding::UTF_8, separator: '&', use__charset_: false, isindex: false)
  885. raise ArgumentError, "the input of #{self.name}.#{__method__} must be ASCII only string" unless str.ascii_only?
  886. ary = []
  887. return ary if str.empty?
  888. enc = Encoding.find(enc)
  889. str.b.each_line(separator) do |string|
  890. string.chomp!(separator)
  891. key, sep, val = string.partition('=')
  892. if isindex
  893. if sep.empty?
  894. val = key
  895. key = ''
  896. end
  897. isindex = false
  898. end
  899. if use__charset_ and key == '_charset_' and e = get_encoding(val)
  900. enc = e
  901. use__charset_ = false
  902. end
  903. key.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
  904. if val
  905. val.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
  906. else
  907. val = ''
  908. end
  909. ary << [key, val]
  910. end
  911. ary.each do |k, v|
  912. k.force_encoding(enc)
  913. k.scrub!
  914. v.force_encoding(enc)
  915. v.scrub!
  916. end
  917. ary
  918. end
  919. private
  920. # curl http://encoding.spec.whatwg.org/encodings.json|rb -rpp -rjson -e'H={};h={"shift_jis"=>"Windows-31J","euc-jp"=>"cp51932","iso-2022-jp"=>"cp50221","x-mac-cyrillic"=>"macCyrillic"};JSON($<.read).map{|x|x["encodings"]}.flatten.each{|x|Encoding.find(n=h.fetch(n=x["name"],n))rescue next;x["labels"].each{|y|H[y]=n}};pp H'
  921. WEB_ENCODINGS_ = {
  922. "unicode-1-1-utf-8"=>"utf-8",
  923. "utf-8"=>"utf-8",
  924. "utf8"=>"utf-8",
  925. "866"=>"ibm866",
  926. "cp866"=>"ibm866",
  927. "csibm866"=>"ibm866",
  928. "ibm866"=>"ibm866",
  929. "csisolatin2"=>"iso-8859-2",
  930. "iso-8859-2"=>"iso-8859-2",
  931. "iso-ir-101"=>"iso-8859-2",
  932. "iso8859-2"=>"iso-8859-2",
  933. "iso88592"=>"iso-8859-2",
  934. "iso_8859-2"=>"iso-8859-2",
  935. "iso_8859-2:1987"=>"iso-8859-2",
  936. "l2"=>"iso-8859-2",
  937. "latin2"=>"iso-8859-2",
  938. "csisolatin3"=>"iso-8859-3",
  939. "iso-8859-3"=>"iso-8859-3",
  940. "iso-ir-109"=>"iso-8859-3",
  941. "iso8859-3"=>"iso-8859-3",
  942. "iso88593"=>"iso-8859-3",
  943. "iso_8859-3"=>"iso-8859-3",
  944. "iso_8859-3:1988"=>"iso-8859-3",
  945. "l3"=>"iso-8859-3",
  946. "latin3"=>"iso-8859-3",
  947. "csisolatin4"=>"iso-8859-4",
  948. "iso-8859-4"=>"iso-8859-4",
  949. "iso-ir-110"=>"iso-8859-4",
  950. "iso8859-4"=>"iso-8859-4",
  951. "iso88594"=>"iso-8859-4",
  952. "iso_8859-4"=>"iso-8859-4",
  953. "iso_8859-4:1988"=>"iso-8859-4",
  954. "l4"=>"iso-8859-4",
  955. "latin4"=>"iso-8859-4",
  956. "csisolatincyrillic"=>"iso-8859-5",
  957. "cyrillic"=>"iso-8859-5",
  958. "iso-8859-5"=>"iso-8859-5",
  959. "iso-ir-144"=>"iso-8859-5",
  960. "iso8859-5"=>"iso-8859-5",
  961. "iso88595"=>"iso-8859-5",
  962. "iso_8859-5"=>"iso-8859-5",
  963. "iso_8859-5:1988"=>"iso-8859-5",
  964. "arabic"=>"iso-8859-6",
  965. "asmo-708"=>"iso-8859-6",
  966. "csiso88596e"=>"iso-8859-6",
  967. "csiso88596i"=>"iso-8859-6",
  968. "csisolatinarabic"=>"iso-8859-6",
  969. "ecma-114"=>"iso-8859-6",
  970. "iso-8859-6"=>"iso-8859-6",
  971. "iso-8859-6-e"=>"iso-8859-6",
  972. "iso-8859-6-i"=>"iso-8859-6",
  973. "iso-ir-127"=>"iso-8859-6",
  974. "iso8859-6"=>"iso-8859-6",
  975. "iso88596"=>"iso-8859-6",
  976. "iso_8859-6"=>"iso-8859-6",
  977. "iso_8859-6:1987"=>"iso-8859-6",
  978. "csisolatingreek"=>"iso-8859-7",
  979. "ecma-118"=>"iso-8859-7",
  980. "elot_928"=>"iso-8859-7",
  981. "greek"=>"iso-8859-7",
  982. "greek8"=>"iso-8859-7",
  983. "iso-8859-7"=>"iso-8859-7",
  984. "iso-ir-126"=>"iso-8859-7",
  985. "iso8859-7"=>"iso-8859-7",
  986. "iso88597"=>"iso-8859-7",
  987. "iso_8859-7"=>"iso-8859-7",
  988. "iso_8859-7:1987"=>"iso-8859-7",
  989. "sun_eu_greek"=>"iso-8859-7",
  990. "csiso88598e"=>"iso-8859-8",
  991. "csisolatinhebrew"=>"iso-8859-8",
  992. "hebrew"=>"iso-8859-8",
  993. "iso-8859-8"=>"iso-8859-8",
  994. "iso-8859-8-e"=>"iso-8859-8",
  995. "iso-ir-138"=>"iso-8859-8",
  996. "iso8859-8"=>"iso-8859-8",
  997. "iso88598"=>"iso-8859-8",
  998. "iso_8859-8"=>"iso-8859-8",
  999. "iso_8859-8:1988"=>"iso-8859-8",
  1000. "visual"=>"iso-8859-8",
  1001. "csisolatin6"=>"iso-8859-10",
  1002. "iso-8859-10"=>"iso-8859-10",
  1003. "iso-ir-157"=>"iso-8859-10",
  1004. "iso8859-10"=>"iso-8859-10",
  1005. "iso885910"=>"iso-8859-10",
  1006. "l6"=>"iso-8859-10",
  1007. "latin6"=>"iso-8859-10",
  1008. "iso-8859-13"=>"iso-8859-13",
  1009. "iso8859-13"=>"iso-8859-13",
  1010. "iso885913"=>"iso-8859-13",
  1011. "iso-8859-14"=>"iso-8859-14",
  1012. "iso8859-14"=>"iso-8859-14",
  1013. "iso885914"=>"iso-8859-14",
  1014. "csisolatin9"=>"iso-8859-15",
  1015. "iso-8859-15"=>"iso-8859-15",
  1016. "iso8859-15"=>"iso-8859-15",
  1017. "iso885915"=>"iso-8859-15",
  1018. "iso_8859-15"=>"iso-8859-15",
  1019. "l9"=>"iso-8859-15",
  1020. "iso-8859-16"=>"iso-8859-16",
  1021. "cskoi8r"=>"koi8-r",
  1022. "koi"=>"koi8-r",
  1023. "koi8"=>"koi8-r",
  1024. "koi8-r"=>"koi8-r",
  1025. "koi8_r"=>"koi8-r",
  1026. "koi8-u"=>"koi8-u",
  1027. "dos-874"=>"windows-874",
  1028. "iso-8859-11"=>"windows-874",
  1029. "iso8859-11"=>"windows-874",
  1030. "iso885911"=>"windows-874",
  1031. "tis-620"=>"windows-874",
  1032. "windows-874"=>"windows-874",
  1033. "cp1250"=>"windows-1250",
  1034. "windows-1250"=>"windows-1250",
  1035. "x-cp1250"=>"windows-1250",
  1036. "cp1251"=>"windows-1251",
  1037. "windows-1251"=>"windows-1251",
  1038. "x-cp1251"=>"windows-1251",
  1039. "ansi_x3.4-1968"=>"windows-1252",
  1040. "ascii"=>"windows-1252",
  1041. "cp1252"=>"windows-1252",
  1042. "cp819"=>"windows-1252",
  1043. "csisolatin1"=>"windows-1252",
  1044. "ibm819"=>"windows-1252",
  1045. "iso-8859-1"=>"windows-1252",
  1046. "iso-ir-100"=>"windows-1252",
  1047. "iso8859-1"=>"windows-1252",
  1048. "iso88591"=>"windows-1252",
  1049. "iso_8859-1"=>"windows-1252",
  1050. "iso_8859-1:1987"=>"windows-1252",
  1051. "l1"=>"windows-1252",
  1052. "latin1"=>"windows-1252",
  1053. "us-ascii"=>"windows-1252",
  1054. "windows-1252"=>"windows-1252",
  1055. "x-cp1252"=>"windows-1252",
  1056. "cp1253"=>"windows-1253",
  1057. "windows-1253"=>"windows-1253",
  1058. "x-cp1253"=>"windows-1253",
  1059. "cp1254"=>"windows-1254",
  1060. "csisolatin5"=>"windows-1254",
  1061. "iso-8859-9"=>"windows-1254",
  1062. "iso-ir-148"=>"windows-1254",
  1063. "iso8859-9"=>"windows-1254",
  1064. "iso88599"=>"windows-1254",
  1065. "iso_8859-9"=>"windows-1254",
  1066. "iso_8859-9:1989"=>"windows-1254",
  1067. "l5"=>"windows-1254",
  1068. "latin5"=>"windows-1254",
  1069. "windows-1254"=>"windows-1254",
  1070. "x-cp1254"=>"windows-1254",
  1071. "cp1255"=>"windows-1255",
  1072. "windows-1255"=>"windows-1255",
  1073. "x-cp1255"=>"windows-1255",
  1074. "cp1256"=>"windows-1256",
  1075. "windows-1256"=>"windows-1256",
  1076. "x-cp1256"=>"windows-1256",
  1077. "cp1257"=>"windows-1257",
  1078. "windows-1257"=>"windows-1257",
  1079. "x-cp1257"=>"windows-1257",
  1080. "cp1258"=>"windows-1258",
  1081. "windows-1258"=>"windows-1258",
  1082. "x-cp1258"=>"windows-1258",
  1083. "x-mac-cyrillic"=>"macCyrillic",
  1084. "x-mac-ukrainian"=>"macCyrillic",
  1085. "chinese"=>"gbk",
  1086. "csgb2312"=>"gbk",
  1087. "csiso58gb231280"=>"gbk",
  1088. "gb2312"=>"gbk",
  1089. "gb_2312"=>"gbk",
  1090. "gb_2312-80"=>"gbk",
  1091. "gbk"=>"gbk",
  1092. "iso-ir-58"=>"gbk",
  1093. "x-gbk"=>"gbk",
  1094. "gb18030"=>"gb18030",
  1095. "big5"=>"big5",
  1096. "big5-hkscs"=>"big5",
  1097. "cn-big5"=>"big5",
  1098. "csbig5"=>"big5",
  1099. "x-x-big5"=>"big5",
  1100. "cseucpkdfmtjapanese"=>"cp51932",
  1101. "euc-jp"=>"cp51932",
  1102. "x-euc-jp"=>"cp51932",
  1103. "csiso2022jp"=>"cp50221",
  1104. "iso-2022-jp"=>"cp50221",
  1105. "csshiftjis"=>"Windows-31J",
  1106. "ms_kanji"=>"Windows-31J",
  1107. "shift-jis"=>"Windows-31J",
  1108. "shift_jis"=>"Windows-31J",
  1109. "sjis"=>"Windows-31J",
  1110. "windows-31j"=>"Windows-31J",
  1111. "x-sjis"=>"Windows-31J",
  1112. "cseuckr"=>"euc-kr",
  1113. "csksc56011987"=>"euc-kr",
  1114. "euc-kr"=>"euc-kr",
  1115. "iso-ir-149"=>"euc-kr",
  1116. "korean"=>"euc-kr",
  1117. "ks_c_5601-1987"=>"euc-kr",
  1118. "ks_c_5601-1989"=>"euc-kr",
  1119. "ksc5601"=>"euc-kr",
  1120. "ksc_5601"=>"euc-kr",
  1121. "windows-949"=>"euc-kr",
  1122. "utf-16be"=>"utf-16be",
  1123. "utf-16"=>"utf-16le",
  1124. "utf-16le"=>"utf-16le"
  1125. } # :nodoc:
  1126. # :nodoc:
  1127. # return encoding or nil
  1128. # http://encoding.spec.whatwg.org/#concept-encoding-get
  1129. def self.get_encoding(label)
  1130. Encoding.find(WEB_ENCODINGS_[label.to_str.strip.downcase]) rescue nil
  1131. end
  1132. end # module URI
  1133. module Kernel
  1134. #
  1135. # Returns +uri+ converted to a URI object.
  1136. #
  1137. def URI(uri)
  1138. if uri.is_a?(URI::Generic)
  1139. uri
  1140. elsif uri = String.try_convert(uri)
  1141. URI.parse(uri)
  1142. else
  1143. raise ArgumentError,
  1144. "bad argument (expected URI object or URI string)"
  1145. end
  1146. end
  1147. module_function :URI
  1148. end