PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/uri/common.rb

https://github.com/dream-hunter/ruby
Ruby | 1002 lines | 409 code | 80 blank | 513 comment | 25 complexity | c288638375a5814c01ddb075dec13446 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-3.0, 0BSD, Unlicense
  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. # * <tt>:ESCAPED</tt> (URI::PATTERN::ESCAPED in default)
  73. # * <tt>:UNRESERVED</tt> (URI::PATTERN::UNRESERVED in default)
  74. # * <tt>:DOMLABEL</tt> (URI::PATTERN::DOMLABEL in default)
  75. # * <tt>:TOPLABEL</tt> (URI::PATTERN::TOPLABEL in default)
  76. # * <tt>:HOSTNAME</tt> (URI::PATTERN::HOSTNAME in default)
  77. #
  78. # == Examples
  79. #
  80. # p = URI::Parser.new(:ESCPAED => "(?:%[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] = URI(uris[0], self)
  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. end # class Parser
  468. # URI::Parser.new
  469. DEFAULT_PARSER = Parser.new
  470. DEFAULT_PARSER.pattern.each_pair do |sym, str|
  471. unless REGEXP::PATTERN.const_defined?(sym)
  472. REGEXP::PATTERN.const_set(sym, str)
  473. end
  474. end
  475. DEFAULT_PARSER.regexp.each_pair do |sym, str|
  476. const_set(sym, str)
  477. end
  478. module Util # :nodoc:
  479. def make_components_hash(klass, array_hash)
  480. tmp = {}
  481. if array_hash.kind_of?(Array) &&
  482. array_hash.size == klass.component.size - 1
  483. klass.component[1..-1].each_index do |i|
  484. begin
  485. tmp[klass.component[i + 1]] = array_hash[i].clone
  486. rescue TypeError
  487. tmp[klass.component[i + 1]] = array_hash[i]
  488. end
  489. end
  490. elsif array_hash.kind_of?(Hash)
  491. array_hash.each do |key, value|
  492. begin
  493. tmp[key] = value.clone
  494. rescue TypeError
  495. tmp[key] = value
  496. end
  497. end
  498. else
  499. raise ArgumentError,
  500. "expected Array of or Hash of components of #{klass.to_s} (#{klass.component[1..-1].join(', ')})"
  501. end
  502. tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase
  503. return tmp
  504. end
  505. module_function :make_components_hash
  506. end
  507. # module for escaping unsafe characters with codes.
  508. module Escape
  509. #
  510. # == Synopsis
  511. #
  512. # URI.escape(str [, unsafe])
  513. #
  514. # == Args
  515. #
  516. # +str+::
  517. # String to replaces in.
  518. # +unsafe+::
  519. # Regexp that matches all symbols that must be replaced with codes.
  520. # By default uses <tt>REGEXP::UNSAFE</tt>.
  521. # When this argument is a String, it represents a character set.
  522. #
  523. # == Description
  524. #
  525. # Escapes the string, replacing all unsafe characters with codes.
  526. #
  527. # == Usage
  528. #
  529. # require 'uri'
  530. #
  531. # enc_uri = URI.escape("http://example.com/?a=\11\15")
  532. # p enc_uri
  533. # # => "http://example.com/?a=%09%0D"
  534. #
  535. # p URI.unescape(enc_uri)
  536. # # => "http://example.com/?a=\t\r"
  537. #
  538. # p URI.escape("@?@!", "!?")
  539. # # => "@%3F@%21"
  540. #
  541. def escape(*arg)
  542. warn "#{caller(1)[0]}: warning: URI.escape is obsolete" if $VERBOSE
  543. DEFAULT_PARSER.escape(*arg)
  544. end
  545. alias encode escape
  546. #
  547. # == Synopsis
  548. #
  549. # URI.unescape(str)
  550. #
  551. # == Args
  552. #
  553. # +str+::
  554. # Unescapes the string.
  555. #
  556. # == Usage
  557. #
  558. # require 'uri'
  559. #
  560. # enc_uri = URI.escape("http://example.com/?a=\11\15")
  561. # p enc_uri
  562. # # => "http://example.com/?a=%09%0D"
  563. #
  564. # p URI.unescape(enc_uri)
  565. # # => "http://example.com/?a=\t\r"
  566. #
  567. def unescape(*arg)
  568. warn "#{caller(1)[0]}: warning: URI.unescape is obsolete" if $VERBOSE
  569. DEFAULT_PARSER.unescape(*arg)
  570. end
  571. alias decode unescape
  572. end # module Escape
  573. extend Escape
  574. include REGEXP
  575. @@schemes = {}
  576. # Returns a Hash of the defined schemes
  577. def self.scheme_list
  578. @@schemes
  579. end
  580. #
  581. # Base class for all URI exceptions.
  582. #
  583. class Error < StandardError; end
  584. #
  585. # Not a URI.
  586. #
  587. class InvalidURIError < Error; end
  588. #
  589. # Not a URI component.
  590. #
  591. class InvalidComponentError < Error; end
  592. #
  593. # URI is valid, bad usage is not.
  594. #
  595. class BadURIError < Error; end
  596. #
  597. # == Synopsis
  598. #
  599. # URI::split(uri)
  600. #
  601. # == Args
  602. #
  603. # +uri+::
  604. # String with URI.
  605. #
  606. # == Description
  607. #
  608. # Splits the string on following parts and returns array with result:
  609. #
  610. # * Scheme
  611. # * Userinfo
  612. # * Host
  613. # * Port
  614. # * Registry
  615. # * Path
  616. # * Opaque
  617. # * Query
  618. # * Fragment
  619. #
  620. # == Usage
  621. #
  622. # require 'uri'
  623. #
  624. # p URI.split("http://www.ruby-lang.org/")
  625. # # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
  626. #
  627. def self.split(uri)
  628. DEFAULT_PARSER.split(uri)
  629. end
  630. #
  631. # == Synopsis
  632. #
  633. # URI::parse(uri_str)
  634. #
  635. # == Args
  636. #
  637. # +uri_str+::
  638. # String with URI.
  639. #
  640. # == Description
  641. #
  642. # Creates one of the URI's subclasses instance from the string.
  643. #
  644. # == Raises
  645. #
  646. # URI::InvalidURIError
  647. # Raised if URI given is not a correct one.
  648. #
  649. # == Usage
  650. #
  651. # require 'uri'
  652. #
  653. # uri = URI.parse("http://www.ruby-lang.org/")
  654. # p uri
  655. # # => #<URI::HTTP:0x202281be URL:http://www.ruby-lang.org/>
  656. # p uri.scheme
  657. # # => "http"
  658. # p uri.host
  659. # # => "www.ruby-lang.org"
  660. #
  661. def self.parse(uri)
  662. DEFAULT_PARSER.parse(uri)
  663. end
  664. #
  665. # == Synopsis
  666. #
  667. # URI::join(str[, str, ...])
  668. #
  669. # == Args
  670. #
  671. # +str+::
  672. # String(s) to work with
  673. #
  674. # == Description
  675. #
  676. # Joins URIs.
  677. #
  678. # == Usage
  679. #
  680. # require 'uri'
  681. #
  682. # p URI.join("http://example.com/","main.rbx")
  683. # # => #<URI::HTTP:0x2022ac02 URL:http://localhost/main.rbx>
  684. #
  685. # p URI.join('http://example.com', 'foo')
  686. # # => #<URI::HTTP:0x01ab80a0 URL:http://example.com/foo>
  687. #
  688. # p URI.join('http://example.com', '/foo', '/bar')
  689. # # => #<URI::HTTP:0x01aaf0b0 URL:http://example.com/bar>
  690. #
  691. # p URI.join('http://example.com', '/foo', 'bar')
  692. # # => #<URI::HTTP:0x801a92af0 URL:http://example.com/bar>
  693. #
  694. # p URI.join('http://example.com', '/foo/', 'bar')
  695. # # => #<URI::HTTP:0x80135a3a0 URL:http://example.com/foo/bar>
  696. #
  697. #
  698. def self.join(*str)
  699. DEFAULT_PARSER.join(*str)
  700. end
  701. #
  702. # == Synopsis
  703. #
  704. # URI::extract(str[, schemes][,&blk])
  705. #
  706. # == Args
  707. #
  708. # +str+::
  709. # String to extract URIs from.
  710. # +schemes+::
  711. # Limit URI matching to a specific schemes.
  712. #
  713. # == Description
  714. #
  715. # Extracts URIs from a string. If block given, iterates through all matched URIs.
  716. # Returns nil if block given or array with matches.
  717. #
  718. # == Usage
  719. #
  720. # require "uri"
  721. #
  722. # URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
  723. # # => ["http://foo.example.com/bla", "mailto:test@example.com"]
  724. #
  725. def self.extract(str, schemes = nil, &block)
  726. DEFAULT_PARSER.extract(str, schemes, &block)
  727. end
  728. #
  729. # == Synopsis
  730. #
  731. # URI::regexp([match_schemes])
  732. #
  733. # == Args
  734. #
  735. # +match_schemes+::
  736. # Array of schemes. If given, resulting regexp matches to URIs
  737. # whose scheme is one of the match_schemes.
  738. #
  739. # == Description
  740. # Returns a Regexp object which matches to URI-like strings.
  741. # The Regexp object returned by this method includes arbitrary
  742. # number of capture group (parentheses). Never rely on it's number.
  743. #
  744. # == Usage
  745. #
  746. # require 'uri'
  747. #
  748. # # extract first URI from html_string
  749. # html_string.slice(URI.regexp)
  750. #
  751. # # remove ftp URIs
  752. # html_string.sub(URI.regexp(['ftp'])
  753. #
  754. # # You should not rely on the number of parentheses
  755. # html_string.scan(URI.regexp) do |*matches|
  756. # p $&
  757. # end
  758. #
  759. def self.regexp(schemes = nil)
  760. DEFAULT_PARSER.make_regexp(schemes)
  761. end
  762. TBLENCWWWCOMP_ = {} # :nodoc:
  763. TBLDECWWWCOMP_ = {} # :nodoc:
  764. HTML5ASCIIINCOMPAT = [Encoding::UTF_7, Encoding::UTF_16BE, Encoding::UTF_16LE,
  765. Encoding::UTF_32BE, Encoding::UTF_32LE] # :nodoc:
  766. # Encode given +str+ to URL-encoded form data.
  767. #
  768. # This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP
  769. # (ASCII space) to + and converts others to %XX.
  770. #
  771. # This is an implementation of
  772. # http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
  773. #
  774. # See URI.decode_www_form_component, URI.encode_www_form
  775. def self.encode_www_form_component(str)
  776. if TBLENCWWWCOMP_.empty?
  777. tbl = {}
  778. 256.times do |i|
  779. tbl[i.chr] = '%%%02X' % i
  780. end
  781. tbl[' '] = '+'
  782. begin
  783. TBLENCWWWCOMP_.replace(tbl)
  784. TBLENCWWWCOMP_.freeze
  785. rescue
  786. end
  787. end
  788. str = str.to_s
  789. if HTML5ASCIIINCOMPAT.include?(str.encoding)
  790. str = str.encode(Encoding::UTF_8)
  791. else
  792. str = str.dup
  793. end
  794. str.force_encoding(Encoding::ASCII_8BIT)
  795. str.gsub!(/[^*\-.0-9A-Z_a-z]/, TBLENCWWWCOMP_)
  796. str.force_encoding(Encoding::US_ASCII)
  797. end
  798. # Decode given +str+ of URL-encoded form data.
  799. #
  800. # This decods + to SP.
  801. #
  802. # See URI.encode_www_form_component, URI.decode_www_form
  803. def self.decode_www_form_component(str, enc=Encoding::UTF_8)
  804. if TBLDECWWWCOMP_.empty?
  805. tbl = {}
  806. 256.times do |i|
  807. h, l = i>>4, i&15
  808. tbl['%%%X%X' % [h, l]] = i.chr
  809. tbl['%%%x%X' % [h, l]] = i.chr
  810. tbl['%%%X%x' % [h, l]] = i.chr
  811. tbl['%%%x%x' % [h, l]] = i.chr
  812. end
  813. tbl['+'] = ' '
  814. begin
  815. TBLDECWWWCOMP_.replace(tbl)
  816. TBLDECWWWCOMP_.freeze
  817. rescue
  818. end
  819. end
  820. raise ArgumentError, "invalid %-encoding (#{str})" unless /\A(?:%\h\h|[^%]+)*\z/ =~ str
  821. str.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
  822. end
  823. # Generate URL-encoded form data from given +enum+.
  824. #
  825. # This generates application/x-www-form-urlencoded data defined in HTML5
  826. # from given an Enumerable object.
  827. #
  828. # This internally uses URI.encode_www_form_component(str).
  829. #
  830. # This method doesn't convert the encoding of given items, so convert them
  831. # before call this method if you want to send data as other than original
  832. # encoding or mixed encoding data. (Strings which are encoded in an HTML5
  833. # ASCII incompatible encoding are converted to UTF-8.)
  834. #
  835. # This method doesn't handle files. When you send a file, use
  836. # multipart/form-data.
  837. #
  838. # This is an implementation of
  839. # http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
  840. #
  841. # URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
  842. # #=> "q=ruby&lang=en"
  843. # URI.encode_www_form("q" => "ruby", "lang" => "en")
  844. # #=> "q=ruby&lang=en"
  845. # URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
  846. # #=> "q=ruby&q=perl&lang=en"
  847. # URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
  848. # #=> "q=ruby&q=perl&lang=en"
  849. #
  850. # See URI.encode_www_form_component, URI.decode_www_form
  851. def self.encode_www_form(enum)
  852. enum.map do |k,v|
  853. if v.nil?
  854. encode_www_form_component(k)
  855. elsif v.respond_to?(:to_ary)
  856. v.to_ary.map do |w|
  857. str = encode_www_form_component(k)
  858. unless w.nil?
  859. str << '='
  860. str << encode_www_form_component(w)
  861. end
  862. end.join('&')
  863. else
  864. str = encode_www_form_component(k)
  865. str << '='
  866. str << encode_www_form_component(v)
  867. end
  868. end.join('&')
  869. end
  870. WFKV_ = '(?:%\h\h|[^%#=;&])' # :nodoc:
  871. # Decode URL-encoded form data from given +str+.
  872. #
  873. # This decodes application/x-www-form-urlencoded data
  874. # and returns array of key-value array.
  875. # This internally uses URI.decode_www_form_component.
  876. #
  877. # _charset_ hack is not supported now because the mapping from given charset
  878. # to Ruby's encoding is not clear yet.
  879. # see also http://www.w3.org/TR/html5/syntax.html#character-encodings-0
  880. #
  881. # This refers http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
  882. #
  883. # ary = URI.decode_www_form("a=1&a=2&b=3")
  884. # p ary #=> [['a', '1'], ['a', '2'], ['b', '3']]
  885. # p ary.assoc('a').last #=> '1'
  886. # p ary.assoc('b').last #=> '3'
  887. # p ary.rassoc('a').last #=> '2'
  888. # p Hash[ary] # => {"a"=>"2", "b"=>"3"}
  889. #
  890. # See URI.decode_www_form_component, URI.encode_www_form
  891. def self.decode_www_form(str, enc=Encoding::UTF_8)
  892. return [] if str.empty?
  893. unless /\A#{WFKV_}*=#{WFKV_}*(?:[;&]#{WFKV_}*=#{WFKV_}*)*\z/o =~ str
  894. raise ArgumentError, "invalid data of application/x-www-form-urlencoded (#{str})"
  895. end
  896. ary = []
  897. $&.scan(/([^=;&]+)=([^;&]*)/) do
  898. ary << [decode_www_form_component($1, enc), decode_www_form_component($2, enc)]
  899. end
  900. ary
  901. end
  902. end # module URI
  903. module Kernel
  904. #
  905. # Returns +uri+ converted to a URI object.
  906. #
  907. def URI(uri, parser = URI::DEFAULT_PARSER)
  908. if uri.is_a?(URI::Generic)
  909. uri
  910. elsif uri = String.try_convert(uri)
  911. parser.parse(uri)
  912. else
  913. raise ArgumentError,
  914. "bad argument (expected URI object or URI string)"
  915. end
  916. end
  917. module_function :URI
  918. end