PageRenderTime 65ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/19/uri/common.rb

http://github.com/rubinius/rubinius
Ruby | 1014 lines | 419 code | 82 blank | 513 comment | 26 complexity | 6ed96e903da8ddaabda525ccd3632bdd MD5 | raw file
Possible License(s): BSD-3-Clause, MPL-2.0-no-copyleft-exception, 0BSD, GPL-2.0, LGPL-2.1
  1. #--
  2. # = uri/common.rb
  3. #
  4. # Author:: Akira Yamada <akira@ruby-lang.org>
  5. # Revision:: $Id: common.rb 33048 2011-08-24 07:29:33Z naruse $
  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, &block)
  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("^#{pattern[:SCHEME]}$")
  456. ret[:USERINFO] = Regexp.new("^#{pattern[:USERINFO]}$")
  457. ret[:HOST] = Regexp.new("^#{pattern[:HOST]}$")
  458. ret[:PORT] = Regexp.new("^#{pattern[:PORT]}$")
  459. ret[:OPAQUE] = Regexp.new("^#{pattern[:OPAQUE_PART]}$")
  460. ret[:REGISTRY] = Regexp.new("^#{pattern[:REG_NAME]}$")
  461. ret[:ABS_PATH] = Regexp.new("^#{pattern[:ABS_PATH]}$")
  462. ret[:REL_PATH] = Regexp.new("^#{pattern[:REL_PATH]}$")
  463. ret[:QUERY] = Regexp.new("^#{pattern[:QUERY]}$")
  464. ret[:FRAGMENT] = Regexp.new("^#{pattern[:FRAGMENT]}$")
  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. TBLDECWWWCOMP_ = {} # :nodoc:
  774. HTML5ASCIIINCOMPAT = [Encoding::UTF_7, Encoding::UTF_16BE, Encoding::UTF_16LE,
  775. Encoding::UTF_32BE, Encoding::UTF_32LE] # :nodoc:
  776. # Encode given +str+ to URL-encoded form data.
  777. #
  778. # This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP
  779. # (ASCII space) to + and converts others to %XX.
  780. #
  781. # This is an implementation of
  782. # http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
  783. #
  784. # See URI.decode_www_form_component, URI.encode_www_form
  785. def self.encode_www_form_component(str)
  786. if TBLENCWWWCOMP_.empty?
  787. tbl = {}
  788. 256.times do |i|
  789. tbl[i.chr] = '%%%02X' % i
  790. end
  791. tbl[' '] = '+'
  792. begin
  793. TBLENCWWWCOMP_.replace(tbl)
  794. TBLENCWWWCOMP_.freeze
  795. rescue
  796. end
  797. end
  798. str = str.to_s
  799. if HTML5ASCIIINCOMPAT.include?(str.encoding)
  800. str = str.encode(Encoding::UTF_8)
  801. else
  802. str = str.dup
  803. end
  804. str.force_encoding(Encoding::ASCII_8BIT)
  805. str.gsub!(/[^*\-.0-9A-Z_a-z]/, TBLENCWWWCOMP_)
  806. str.force_encoding(Encoding::US_ASCII)
  807. end
  808. # Decode given +str+ of URL-encoded form data.
  809. #
  810. # This decods + to SP.
  811. #
  812. # See URI.encode_www_form_component, URI.decode_www_form
  813. def self.decode_www_form_component(str, enc=Encoding::UTF_8)
  814. if TBLDECWWWCOMP_.empty?
  815. tbl = {}
  816. 256.times do |i|
  817. h, l = i>>4, i&15
  818. tbl['%%%X%X' % [h, l]] = i.chr
  819. tbl['%%%x%X' % [h, l]] = i.chr
  820. tbl['%%%X%x' % [h, l]] = i.chr
  821. tbl['%%%x%x' % [h, l]] = i.chr
  822. end
  823. tbl['+'] = ' '
  824. begin
  825. TBLDECWWWCOMP_.replace(tbl)
  826. TBLDECWWWCOMP_.freeze
  827. rescue
  828. end
  829. end
  830. raise ArgumentError, "invalid %-encoding (#{str})" unless /\A[^%]*(?:%\h\h[^%]*)*\z/ =~ str
  831. str.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
  832. end
  833. # Generate URL-encoded form data from given +enum+.
  834. #
  835. # This generates application/x-www-form-urlencoded data defined in HTML5
  836. # from given an Enumerable object.
  837. #
  838. # This internally uses URI.encode_www_form_component(str).
  839. #
  840. # This method doesn't convert the encoding of given items, so convert them
  841. # before call this method if you want to send data as other than original
  842. # encoding or mixed encoding data. (Strings which are encoded in an HTML5
  843. # ASCII incompatible encoding are converted to UTF-8.)
  844. #
  845. # This method doesn't handle files. When you send a file, use
  846. # multipart/form-data.
  847. #
  848. # This is an implementation of
  849. # http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
  850. #
  851. # URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
  852. # #=> "q=ruby&lang=en"
  853. # URI.encode_www_form("q" => "ruby", "lang" => "en")
  854. # #=> "q=ruby&lang=en"
  855. # URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
  856. # #=> "q=ruby&q=perl&lang=en"
  857. # URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
  858. # #=> "q=ruby&q=perl&lang=en"
  859. #
  860. # See URI.encode_www_form_component, URI.decode_www_form
  861. def self.encode_www_form(enum)
  862. enum.map do |k,v|
  863. if v.nil?
  864. encode_www_form_component(k)
  865. elsif v.respond_to?(:to_ary)
  866. v.to_ary.map do |w|
  867. str = encode_www_form_component(k)
  868. unless w.nil?
  869. str << '='
  870. str << encode_www_form_component(w)
  871. end
  872. end.join('&')
  873. else
  874. str = encode_www_form_component(k)
  875. str << '='
  876. str << encode_www_form_component(v)
  877. end
  878. end.join('&')
  879. end
  880. WFKV_ = '(?:[^%#=;&]*(?:%\h\h[^%#=;&]*)*)' # :nodoc:
  881. # Decode URL-encoded form data from given +str+.
  882. #
  883. # This decodes application/x-www-form-urlencoded data
  884. # and returns array of key-value array.
  885. # This internally uses URI.decode_www_form_component.
  886. #
  887. # _charset_ hack is not supported now because the mapping from given charset
  888. # to Ruby's encoding is not clear yet.
  889. # see also http://www.w3.org/TR/html5/syntax.html#character-encodings-0
  890. #
  891. # This refers http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
  892. #
  893. # ary = URI.decode_www_form("a=1&a=2&b=3")
  894. # p ary #=> [['a', '1'], ['a', '2'], ['b', '3']]
  895. # p ary.assoc('a').last #=> '1'
  896. # p ary.assoc('b').last #=> '3'
  897. # p ary.rassoc('a').last #=> '2'
  898. # p Hash[ary] # => {"a"=>"2", "b"=>"3"}
  899. #
  900. # See URI.decode_www_form_component, URI.encode_www_form
  901. def self.decode_www_form(str, enc=Encoding::UTF_8)
  902. return [] if str.empty?
  903. unless /\A#{WFKV_}=#{WFKV_}(?:[;&]#{WFKV_}=#{WFKV_})*\z/o =~ str
  904. raise ArgumentError, "invalid data of application/x-www-form-urlencoded (#{str})"
  905. end
  906. ary = []
  907. $&.scan(/([^=;&]+)=([^;&]*)/) do
  908. ary << [decode_www_form_component($1, enc), decode_www_form_component($2, enc)]
  909. end
  910. ary
  911. end
  912. end # module URI
  913. module Kernel
  914. #
  915. # Returns +uri+ converted to a URI object.
  916. #
  917. def URI(uri)
  918. if uri.is_a?(URI::Generic)
  919. uri
  920. elsif uri = String.try_convert(uri)
  921. URI.parse(uri)
  922. else
  923. raise ArgumentError,
  924. "bad argument (expected URI object or URI string)"
  925. end
  926. end
  927. module_function :URI
  928. end