addressable 2.9.1 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,7 @@
19
19
 
20
20
  require "addressable/version"
21
21
  require "addressable/idna"
22
+ require "addressable/unicode_normalization"
22
23
  require "public_suffix"
23
24
 
24
25
  ##
@@ -62,6 +63,9 @@ module Addressable
62
63
 
63
64
  module NormalizeCharacterClasses
64
65
  HOST = /[^#{CharacterClasses::HOST}]/
66
+ # A registered name has no ":", "[" or "]": those only delimit an IP
67
+ # literal and the port.
68
+ REG_NAME = /[^#{CharacterClasses::UNRESERVED + CharacterClasses::SUB_DELIMS}]/
65
69
  UNRESERVED = /[^#{CharacterClasses::UNRESERVED}]/
66
70
  PCHAR = /[^#{CharacterClasses::PCHAR}]/
67
71
  SCHEME = /[^#{CharacterClasses::SCHEME}]/
@@ -69,6 +73,63 @@ module Addressable
69
73
  QUERY = %r{[^a-zA-Z0-9\-\.\_\~\!\$\'\(\)\*\+\,\=\:\@\/\?%]|%(?!2B|2b)}
70
74
  end
71
75
 
76
+ # Normalization decodes a pct-encoded character unless it's a delimiter
77
+ # where it appears, since decoding it there would change how the URI is
78
+ # read: "/" in a path, "&", ";" and "+" in a query, and "=" in a query
79
+ # name. A delimiter that isn't allowed in the component, such as "?" in
80
+ # a path segment, is encoded again anyway. "%25" also stays encoded, and
81
+ # a bare "%" is encoded first, so every "%" left after decoding starts a
82
+ # triplet and none is decoded twice; so these classes never encode "%".
83
+ module NormalizeByPosition
84
+ PCHAR = /[^#{CharacterClasses::PCHAR}%]/
85
+ PATH = /[^#{CharacterClasses::PATH}%]/
86
+ QUERY = /[^#{CharacterClasses::QUERY}%]/
87
+ # "&" and ";" can separate query pairs, so they're encoded in a pair.
88
+ QUERY_PAIR = /[^#{
89
+ CharacterClasses::QUERY.sub("\\&", "").sub("\\;", "")
90
+ }%]/
91
+ FRAGMENT = /[^#{CharacterClasses::FRAGMENT}%]/
92
+ LEAVE_IN_SEGMENT = "%"
93
+ LEAVE_IN_PATH = "/%"
94
+ LEAVE_IN_QUERY_VALUE = "&;+%"
95
+ LEAVE_IN_QUERY_NAME = "&;+=%"
96
+ LEAVE_IN_FRAGMENT = "%"
97
+ # A relative path's first segment can't hold a colon (RFC 3986
98
+ # section 4.2).
99
+ FIRST_SEGMENT = /\A[^\/]*/
100
+ BARE_PERCENT = /%(?![0-9A-Fa-f]{2})/
101
+ TRIPLET = /%[0-9A-Fa-f]{2}/
102
+ # NFC turns U+037E GREEK QUESTION MARK into ";", the only character
103
+ # it turns into a reserved one. A delimiter isn't equivalent to the
104
+ # text it came from, so U+037E is left out of NFC.
105
+ NFC_DELIMITER = /(\u037E)/
106
+ SPLIT_TRIPLETS_AND_DELIMITER = /(%[0-9A-Fa-f]{2}|\u037E)/
107
+
108
+ ##
109
+ # Normalizes a query's name=value pair, keeping "=" encoded in the
110
+ # name. The name and value are normalized apart, so NFC can't compose
111
+ # the "=" between them with a combining mark.
112
+ def self.query_pair(pair, character_class)
113
+ name, separator, value = pair.partition("=")
114
+ normalized = Addressable::URI.normalize_component(
115
+ name, character_class, LEAVE_IN_QUERY_NAME
116
+ )
117
+ return normalized if separator.empty?
118
+ normalized + separator + Addressable::URI.normalize_component(
119
+ value, character_class, LEAVE_IN_QUERY_VALUE
120
+ )
121
+ end
122
+
123
+ ##
124
+ # Encodes the colons in the first segment of a relative path, which
125
+ # would otherwise be read as ending a scheme.
126
+ def self.encode_relative_colons(path, scheme)
127
+ return path if scheme || path.start_with?("/")
128
+ path.sub(FIRST_SEGMENT) { |segment| segment.gsub(":", "%3A") }
129
+ end
130
+ end
131
+ private_constant :NormalizeByPosition
132
+
72
133
  module CharacterClassesRegexps
73
134
  AUTHORITY = /[^#{CharacterClasses::AUTHORITY}]/
74
135
  FRAGMENT = /[^#{CharacterClasses::FRAGMENT}]/
@@ -82,6 +143,8 @@ module Addressable
82
143
  end
83
144
 
84
145
  SLASH = '/'
146
+ IP_LITERAL = /\A\[.*\]\z/m
147
+ private_constant :IP_LITERAL
85
148
  EMPTY_STR = ''
86
149
 
87
150
  URIREGEX = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/
@@ -102,6 +165,21 @@ module Addressable
102
165
  "prospero" => 1525
103
166
  }.freeze
104
167
 
168
+ # The largest port, the largest integer the platform stores without a
169
+ # bignum. A port is an Integer, and on a Ruby built without GMP,
170
+ # converting a long run of digits takes time quadratic in its length, so
171
+ # a longer one is rejected before it's converted. Rubies before 2.5
172
+ # don't have RbConfig::LIMITS, so it's worked out from the word size.
173
+ LARGEST_PORT = begin
174
+ require "rbconfig/sizeof"
175
+ RbConfig::LIMITS["FIXNUM_MAX"]
176
+ rescue LoadError, NameError
177
+ nil
178
+ end || (1 << (0.size * 8 - 2)) - 1
179
+ # The schemes of PORT_MAPPING run over TCP or UDP, whose ports are 16-bit.
180
+ LARGEST_TRANSPORT_PORT = 65535
181
+ private_constant :LARGEST_PORT, :LARGEST_TRANSPORT_PORT
182
+
105
183
  ##
106
184
  # Returns a URI object based on the parsed string.
107
185
  #
@@ -241,7 +319,8 @@ module Addressable
241
319
  uri[offset[0]...offset[1]] = new_authority
242
320
  end
243
321
  parsed = self.parse(uri)
244
- if parsed.scheme =~ /^[^\/?#\.]+\.[^\/?#]+$/
322
+ if parsed.scheme =~ /^[^\/?#\.]+\.[^\/?#]+$/ ||
323
+ (parsed.scheme =~ /\Alocalhost\z/i && parsed.path =~ /\A\d+(?:\/|\z)/)
245
324
  parsed = self.parse(hints[:scheme] + "://" + uri)
246
325
  end
247
326
  if parsed.path.include?(".")
@@ -483,10 +562,16 @@ module Addressable
483
562
  "got #{return_type.inspect}"
484
563
  end
485
564
 
486
- result = uri.gsub(/%[0-9a-f]{2}/i) do |sequence|
565
+ encoding = uri.encoding
566
+ # A decoded byte on its own may not be a valid character, so the
567
+ # result is built from the string's bytes and given its encoding once.
568
+ # A string that can't be searched as it is raises as it did, from
569
+ # gsub on the string itself.
570
+ source = encoding.ascii_compatible? && uri.valid_encoding? ? uri.b : uri
571
+ result = source.gsub(/%[0-9a-f]{2}/i) do |sequence|
487
572
  c = sequence[1..3].to_i(16).chr
488
- c.force_encoding(sequence.encoding)
489
- leave_encoded.include?(c) ? sequence : c
573
+ c.force_encoding(encoding)
574
+ leave_encoded.include?(c) ? sequence : c.force_encoding(source.encoding)
490
575
  end
491
576
 
492
577
  result.force_encoding(Encoding::UTF_8)
@@ -565,33 +650,47 @@ module Addressable
565
650
  "Expected String or Regexp, got #{character_class.inspect}"
566
651
  end
567
652
  if character_class.kind_of?(String)
568
- leave_re = if leave_encoded.length > 0
569
- character_class = "#{character_class}%" unless character_class.include?('%')
570
-
571
- bytes = leave_encoded.bytes
572
- leave_encoded_pattern = bytes.map { |b| SEQUENCE_ENCODING_TABLE[b] }.join('|')
573
- "|%(?!#{leave_encoded_pattern}|#{leave_encoded_pattern.upcase})"
653
+ if leave_encoded.length > 0
654
+ # A decoded "%25" would start a new triplet, so it stays encoded.
655
+ leave_encoded += "%" unless leave_encoded.include?("%")
656
+ character_class += "%" unless character_class.include?("%")
574
657
  end
575
-
576
- character_class = if leave_re
577
- /[^#{character_class}]#{leave_re}/
578
- else
579
- /[^#{character_class}]/
580
- end
658
+ character_class = /[^#{character_class}]/
581
659
  end
582
660
  # We can't perform regexps on invalid UTF sequences, but
583
661
  # here we need to, so switch to ASCII.
584
662
  component = component.dup
585
663
  component.force_encoding(Encoding::ASCII_8BIT)
664
+ keep_percent = leave_encoded.include?("%")
665
+ # Then every "%" must start a triplet, or decoding could form one:
666
+ # "%%32%46" would become "%2F".
667
+ if keep_percent
668
+ component = component.gsub(NormalizeByPosition::BARE_PERCENT, "%25")
669
+ end
670
+ upcase_encoded = keep_percent ? "" : leave_encoded
586
671
  unencoded = self.unencode_component(component, String, leave_encoded)
587
672
  begin
673
+ # Composing a triplet's last hex digit with a combining mark that
674
+ # follows it would break the triplet, so only the text between
675
+ # triplets is normalized, and U+037E is left as it is.
676
+ split = if keep_percent
677
+ NormalizeByPosition::SPLIT_TRIPLETS_AND_DELIMITER
678
+ else
679
+ NormalizeByPosition::NFC_DELIMITER
680
+ end
681
+ normalized = unencoded.split(split).map.with_index do |part, index|
682
+ index.odd? ? part : UnicodeNormalization.normalize(part, :nfc)
683
+ end.join
588
684
  encoded = self.encode_component(
589
- unencoded.unicode_normalize(:nfc),
685
+ normalized,
590
686
  character_class,
591
- leave_encoded
687
+ upcase_encoded
592
688
  )
593
689
  rescue ArgumentError
594
- encoded = self.encode_component(unencoded)
690
+ encoded = self.encode_component(unencoded, character_class, upcase_encoded)
691
+ end
692
+ if keep_percent
693
+ encoded = encoded.gsub(NormalizeByPosition::TRIPLET, &:upcase)
595
694
  end
596
695
  encoded.force_encoding(Encoding::UTF_8)
597
696
  return encoded
@@ -687,20 +786,22 @@ module Addressable
687
786
  :password => self.unencode_component(uri_object.password),
688
787
  :host => self.unencode_component(uri_object.host),
689
788
  :port => (uri_object.port.nil? ? nil : uri_object.port.to_s),
690
- :path => self.unencode_component(uri_object.path),
691
- :query => self.unencode_component(uri_object.query),
692
- :fragment => self.unencode_component(uri_object.fragment)
693
789
  }
694
790
  components.each do |key, value|
695
791
  if value != nil
696
792
  begin
697
- components[key] = value.to_str.unicode_normalize(:nfc)
793
+ components[key] =
794
+ UnicodeNormalization.normalize(value.to_str, :nfc)
698
795
  rescue ArgumentError
699
796
  # Likely a malformed UTF-8 character, skip unicode normalization
700
797
  components[key] = value.to_str
701
798
  end
702
799
  end
703
800
  end
801
+ # The query may hold invalid UTF-8, which String#split refuses.
802
+ query = uri_object.query && uri_object.query.b.split("&", -1).map do |pair|
803
+ NormalizeByPosition.query_pair(pair, NormalizeByPosition::QUERY)
804
+ end.join("&")
704
805
  encoded_uri = Addressable::URI.new(
705
806
  :scheme => self.encode_component(components[:scheme],
706
807
  Addressable::URI::CharacterClassesRegexps::SCHEME),
@@ -710,12 +811,15 @@ module Addressable
710
811
  Addressable::URI::CharacterClassesRegexps::UNRESERVED),
711
812
  :host => components[:host],
712
813
  :port => components[:port],
713
- :path => self.encode_component(components[:path],
714
- Addressable::URI::CharacterClassesRegexps::PATH),
715
- :query => self.encode_component(components[:query],
716
- Addressable::URI::CharacterClassesRegexps::QUERY),
717
- :fragment => self.encode_component(components[:fragment],
718
- Addressable::URI::CharacterClassesRegexps::FRAGMENT)
814
+ :path => NormalizeByPosition.encode_relative_colons(
815
+ self.normalize_component(uri_object.path,
816
+ NormalizeByPosition::PATH, NormalizeByPosition::LEAVE_IN_PATH),
817
+ uri_object.scheme
818
+ ),
819
+ :query => query,
820
+ :fragment => self.normalize_component(uri_object.fragment,
821
+ NormalizeByPosition::FRAGMENT,
822
+ NormalizeByPosition::LEAVE_IN_FRAGMENT)
719
823
  )
720
824
  if return_type == String
721
825
  return encoded_uri.to_s
@@ -847,17 +951,19 @@ module Addressable
847
951
  defer_validation do
848
952
  # Bunch of crazy logic required because of the composite components
849
953
  # like userinfo and authority.
850
- self.scheme = options[:scheme] if options[:scheme]
851
- self.user = options[:user] if options[:user]
852
- self.password = options[:password] if options[:password]
853
- self.userinfo = options[:userinfo] if options[:userinfo]
854
- self.host = options[:host] if options[:host]
855
- self.port = options[:port] if options[:port]
856
- self.authority = options[:authority] if options[:authority]
857
- self.path = options[:path] if options[:path]
858
- self.query = options[:query] if options[:query]
859
- self.query_values = options[:query_values] if options[:query_values]
860
- self.fragment = options[:fragment] if options[:fragment]
954
+ self.scheme = options[:scheme] unless options[:scheme].nil?
955
+ self.user = options[:user] unless options[:user].nil?
956
+ self.password = options[:password] unless options[:password].nil?
957
+ self.userinfo = options[:userinfo] unless options[:userinfo].nil?
958
+ self.host = options[:host] unless options[:host].nil?
959
+ self.port = options[:port] unless options[:port].nil?
960
+ self.authority = options[:authority] unless options[:authority].nil?
961
+ self.path = options[:path] unless options[:path].nil?
962
+ self.query = options[:query] unless options[:query].nil?
963
+ unless options[:query_values].nil?
964
+ self.query_values = options[:query_values]
965
+ end
966
+ self.fragment = options[:fragment] unless options[:fragment].nil?
861
967
  end
862
968
 
863
969
  to_s # force path validation
@@ -868,18 +974,7 @@ module Addressable
868
974
  #
869
975
  # @return [Addressable::URI] The frozen URI object.
870
976
  def freeze
871
- self.normalized_scheme
872
- self.normalized_user
873
- self.normalized_password
874
- self.normalized_userinfo
875
- self.normalized_host
876
- self.normalized_port
877
- self.normalized_authority
878
- self.normalized_site
879
- self.normalized_path
880
- self.normalized_query
881
- self.normalized_fragment
882
- self.hash
977
+ prepare_to_freeze
883
978
  super
884
979
  end
885
980
 
@@ -915,7 +1010,7 @@ module Addressable
915
1010
  #
916
1011
  # @param [String, #to_str] new_scheme The new scheme component.
917
1012
  def scheme=(new_scheme)
918
- if new_scheme && !new_scheme.respond_to?(:to_str)
1013
+ if !new_scheme.nil? && !new_scheme.respond_to?(:to_str)
919
1014
  raise TypeError, "Can't convert #{new_scheme.class} into String."
920
1015
  elsif new_scheme
921
1016
  new_scheme = new_scheme.to_str
@@ -928,6 +1023,11 @@ module Addressable
928
1023
 
929
1024
  # Reset dependent values
930
1025
  @normalized_scheme = NONE
1026
+ @normalized_user = NONE
1027
+ @normalized_password = NONE
1028
+ @normalized_userinfo = NONE
1029
+ @normalized_port = NONE
1030
+ @normalized_path = nil
931
1031
  remove_composite_values
932
1032
 
933
1033
  # Ensure we haven't created an invalid URI
@@ -968,7 +1068,7 @@ module Addressable
968
1068
  #
969
1069
  # @param [String, #to_str] new_user The new user component.
970
1070
  def user=(new_user)
971
- if new_user && !new_user.respond_to?(:to_str)
1071
+ if !new_user.nil? && !new_user.respond_to?(:to_str)
972
1072
  raise TypeError, "Can't convert #{new_user.class} into String."
973
1073
  end
974
1074
  @user = new_user ? new_user.to_str : nil
@@ -983,6 +1083,7 @@ module Addressable
983
1083
  @normalized_userinfo = NONE
984
1084
  @authority = nil
985
1085
  @normalized_user = NONE
1086
+ @normalized_password = NONE
986
1087
  remove_composite_values
987
1088
 
988
1089
  # Ensure we haven't created an invalid URI
@@ -1023,7 +1124,7 @@ module Addressable
1023
1124
  #
1024
1125
  # @param [String, #to_str] new_password The new password component.
1025
1126
  def password=(new_password)
1026
- if new_password && !new_password.respond_to?(:to_str)
1127
+ if !new_password.nil? && !new_password.respond_to?(:to_str)
1027
1128
  raise TypeError, "Can't convert #{new_password.class} into String."
1028
1129
  end
1029
1130
  @password = new_password ? new_password.to_str : nil
@@ -1038,6 +1139,7 @@ module Addressable
1038
1139
  @normalized_userinfo = NONE
1039
1140
  @authority = nil
1040
1141
  @normalized_password = NONE
1142
+ @normalized_user = NONE
1041
1143
  remove_composite_values
1042
1144
 
1043
1145
  # Ensure we haven't created an invalid URI
@@ -1053,10 +1155,11 @@ module Addressable
1053
1155
  current_user = self.user
1054
1156
  current_password = self.password
1055
1157
  (current_user || current_password) && @userinfo ||= begin
1158
+ # Before Ruby 3.0, an interpolated string here would be frozen.
1056
1159
  if current_user && current_password
1057
- "#{current_user}:#{current_password}"
1160
+ "#{current_user}:#{current_password}".dup
1058
1161
  elsif current_user && !current_password
1059
- "#{current_user}"
1162
+ current_user.dup
1060
1163
  end
1061
1164
  end
1062
1165
  end
@@ -1089,12 +1192,12 @@ module Addressable
1089
1192
  #
1090
1193
  # @param [String, #to_str] new_userinfo The new userinfo component.
1091
1194
  def userinfo=(new_userinfo)
1092
- if new_userinfo && !new_userinfo.respond_to?(:to_str)
1195
+ if !new_userinfo.nil? && !new_userinfo.respond_to?(:to_str)
1093
1196
  raise TypeError, "Can't convert #{new_userinfo.class} into String."
1094
1197
  end
1095
1198
  new_user, new_password = if new_userinfo
1096
1199
  [
1097
- new_userinfo.to_str.strip[/^(.*):/, 1],
1200
+ new_userinfo.to_str.strip[/^([^:]*):?/, 1],
1098
1201
  new_userinfo.to_str.strip[/:(.*)$/, 1]
1099
1202
  ]
1100
1203
  else
@@ -1128,16 +1231,39 @@ module Addressable
1128
1231
 
1129
1232
  @normalized_host ||= begin
1130
1233
  if !self.host.strip.empty?
1131
- result = ::Addressable::IDNA.to_ascii(
1132
- URI.unencode_component(self.host.strip.downcase)
1133
- )
1134
- if result =~ /[^\.]\.$/
1234
+ host = self.host.strip.downcase
1235
+ unencoded = URI.unencode_component(host)
1236
+ # Bytes that aren't valid UTF-8 can't be converted to a domain
1237
+ # name, so they stay pct-encoded. So does a host IDNA rejects: it
1238
+ # can't be resolved as a domain name, but it's still a valid host
1239
+ # (RFC 3987, section 3.1). Only its ASCII letters are lowercased.
1240
+ result = if unencoded.valid_encoding?
1241
+ # The host is decoded once. A "%" that decoding gives is a
1242
+ # percent sign in the name, so it's written as "%25" again,
1243
+ # where normalizing below would read it as part of a triplet.
1244
+ # Decoded letters are lowercased too, as "%41" gives "A".
1245
+ begin
1246
+ ::Addressable::IDNA.to_ascii(unencoded.downcase).gsub('%', '%25')
1247
+ rescue *::Addressable::IDNA::CONVERSION_ERRORS
1248
+ self.host.strip.tr("A-Z", "a-z")
1249
+ end
1250
+ else
1251
+ host
1252
+ end
1253
+ if result =~ /[^\.]\.\z/
1135
1254
  # Single trailing dots are unnecessary.
1136
1255
  result = result[0...-1]
1137
1256
  end
1257
+ # Only an IP literal keeps its ":", "[" and "]". In a registered
1258
+ # name they stay pct-encoded, or they would be read as a port or
1259
+ # an IP literal when the normalized URI is parsed again.
1138
1260
  result = Addressable::URI.normalize_component(
1139
1261
  result,
1140
- NormalizeCharacterClasses::HOST
1262
+ if IP_LITERAL =~ self.host
1263
+ NormalizeCharacterClasses::HOST
1264
+ else
1265
+ NormalizeCharacterClasses::REG_NAME
1266
+ end
1141
1267
  )
1142
1268
  result
1143
1269
  else
@@ -1154,7 +1280,7 @@ module Addressable
1154
1280
  #
1155
1281
  # @param [String, #to_str] new_host The new host component.
1156
1282
  def host=(new_host)
1157
- if new_host && !new_host.respond_to?(:to_str)
1283
+ if !new_host.nil? && !new_host.respond_to?(:to_str)
1158
1284
  raise TypeError, "Can't convert #{new_host.class} into String."
1159
1285
  end
1160
1286
  @host = new_host ? new_host.to_str : nil
@@ -1191,7 +1317,7 @@ module Addressable
1191
1317
  if new_hostname &&
1192
1318
  (new_hostname.respond_to?(:ipv4?) || new_hostname.respond_to?(:ipv6?))
1193
1319
  new_hostname = new_hostname.to_s
1194
- elsif new_hostname && !new_hostname.respond_to?(:to_str)
1320
+ elsif !new_hostname.nil? && !new_hostname.respond_to?(:to_str)
1195
1321
  raise TypeError, "Can't convert #{new_hostname.class} into String."
1196
1322
  end
1197
1323
  v = new_hostname ? new_hostname.to_str : nil
@@ -1272,7 +1398,7 @@ module Addressable
1272
1398
  #
1273
1399
  # @param [String, #to_str] new_authority The new authority component.
1274
1400
  def authority=(new_authority)
1275
- if new_authority
1401
+ unless new_authority.nil?
1276
1402
  if !new_authority.respond_to?(:to_str)
1277
1403
  raise TypeError, "Can't convert #{new_authority.class} into String."
1278
1404
  end
@@ -1331,24 +1457,31 @@ module Addressable
1331
1457
  #
1332
1458
  # @param [String, #to_str] new_origin The new origin component.
1333
1459
  def origin=(new_origin)
1334
- if new_origin
1460
+ unless new_origin.nil?
1335
1461
  if !new_origin.respond_to?(:to_str)
1336
1462
  raise TypeError, "Can't convert #{new_origin.class} into String."
1337
1463
  end
1338
1464
  new_origin = new_origin.to_str
1339
- new_scheme = new_origin[/^([^:\/?#]+):\/\//, 1]
1340
- unless new_scheme
1465
+ origin_match = new_origin.match(
1466
+ /\A([^:\/?#]+):\/\/(\[[^\]]+\]|[^\/?#:@]+)(?::([^\/?#]*))?\z/
1467
+ )
1468
+ unless new_origin =~ /\A[^:\/?#]+:\/\//
1341
1469
  raise InvalidURIError, 'An origin cannot omit the scheme.'
1342
1470
  end
1343
- new_host = new_origin[/:\/\/([^\/?#:]+)/, 1]
1344
- unless new_host
1345
- raise InvalidURIError, 'An origin cannot omit the host.'
1471
+ new_scheme, new_host, new_port = origin_match.captures if origin_match
1472
+ # Userinfo with a colon matches as a host and a port.
1473
+ if origin_match.nil? || new_port.to_s.include?("@")
1474
+ if new_origin =~ /\A[^:\/?#]+:\/\/\z/
1475
+ raise InvalidURIError, 'An origin cannot omit the host.'
1476
+ end
1477
+ raise InvalidURIError,
1478
+ 'An origin cannot include userinfo, a path, query, or fragment.'
1346
1479
  end
1347
- new_port = new_origin[/:([^:@\[\]\/]*?)$/, 1]
1348
- # An empty port is the same as no port (Section 3.2.3 of RFC 3986).
1349
- if new_port == EMPTY_STR && new_origin =~ /\A[^:\/?#]+:\/\/[^\/?#:@\[\]]+:\z/
1350
- new_port = nil
1480
+ if new_port && new_port !~ /\A\d*\z/
1481
+ raise InvalidURIError, "Invalid port number: #{new_port.inspect}"
1351
1482
  end
1483
+ # An empty port is the same as no port (Section 3.2.3 of RFC 3986).
1484
+ new_port = nil if new_port == EMPTY_STR
1352
1485
  end
1353
1486
 
1354
1487
  self.scheme = new_scheme
@@ -1418,12 +1551,24 @@ module Addressable
1418
1551
  raise InvalidURIError, "Invalid encoding in port"
1419
1552
  end
1420
1553
 
1421
- if new_port != nil && !(new_port.to_s =~ /^\d+$/)
1554
+ # A large Integer is rejected before it's written out as digits.
1555
+ if new_port.is_a?(Integer) && new_port > LARGEST_PORT
1556
+ raise InvalidURIError, "Port number too large"
1557
+ end
1558
+
1559
+ if new_port != nil && !(new_port.to_s =~ /\A\d+\z/)
1422
1560
  raise InvalidURIError,
1423
1561
  "Invalid port number: #{new_port.inspect}"
1424
1562
  end
1425
1563
 
1426
- @port = new_port.to_s.to_i
1564
+ digits = new_port.to_s.sub(/\A0+/, EMPTY_STR)
1565
+ largest = LARGEST_PORT.to_s
1566
+ if digits.size > largest.size ||
1567
+ (digits.size == largest.size && digits > largest)
1568
+ raise InvalidURIError, "Port number too large"
1569
+ end
1570
+
1571
+ @port = digits.to_i
1427
1572
  @port = nil if @port == 0
1428
1573
 
1429
1574
  # Reset dependent values
@@ -1508,7 +1653,10 @@ module Addressable
1508
1653
  #
1509
1654
  # @param [String, #to_str] new_site The new site value.
1510
1655
  def site=(new_site)
1511
- if new_site
1656
+ if new_site.nil?
1657
+ self.scheme = nil
1658
+ self.authority = nil
1659
+ else
1512
1660
  if !new_site.respond_to?(:to_str)
1513
1661
  raise TypeError, "Can't convert #{new_site.class} into String."
1514
1662
  end
@@ -1519,9 +1667,6 @@ module Addressable
1519
1667
  self.authority = new_site[
1520
1668
  /^(?:(?:[^:\/?#]+):)?(?:\/\/([^\/?#]*))?$/, 1
1521
1669
  ]
1522
- else
1523
- self.scheme = nil
1524
- self.authority = nil
1525
1670
  end
1526
1671
  end
1527
1672
 
@@ -1539,20 +1684,19 @@ module Addressable
1539
1684
  def normalized_path
1540
1685
  @normalized_path ||= begin
1541
1686
  path = self.path.to_s
1542
- if self.scheme == nil && path =~ NORMPATH
1543
- # Relative paths with colons in the first segment are ambiguous.
1544
- path = path.sub(":", "%2F")
1545
- end
1546
1687
  # String#split(delimiter, -1) uses the more strict splitting behavior
1547
1688
  # found by default in Python.
1548
1689
  result = path.strip.split(SLASH, -1).map do |segment|
1549
1690
  Addressable::URI.normalize_component(
1550
1691
  segment,
1551
- Addressable::URI::NormalizeCharacterClasses::PCHAR
1692
+ NormalizeByPosition::PCHAR,
1693
+ NormalizeByPosition::LEAVE_IN_SEGMENT
1552
1694
  )
1553
1695
  end.join(SLASH)
1554
1696
 
1555
- result = URI.normalize_path(result)
1697
+ result = NormalizeByPosition.encode_relative_colons(
1698
+ URI.normalize_path(result), self.scheme
1699
+ )
1556
1700
  if result.empty? &&
1557
1701
  ["http", "https", "ftp", "tftp"].include?(self.normalized_scheme)
1558
1702
  result = SLASH.dup
@@ -1569,7 +1713,7 @@ module Addressable
1569
1713
  #
1570
1714
  # @param [String, #to_str] new_path The new path component.
1571
1715
  def path=(new_path)
1572
- if new_path && !new_path.respond_to?(:to_str)
1716
+ if !new_path.nil? && !new_path.respond_to?(:to_str)
1573
1717
  raise TypeError, "Can't convert #{new_path.class} into String."
1574
1718
  end
1575
1719
  @path = (new_path || EMPTY_STR).to_str
@@ -1616,26 +1760,20 @@ module Addressable
1616
1760
  # @return [String] The query component, normalized.
1617
1761
  def normalized_query(*flags)
1618
1762
  return nil unless self.query
1619
- return @normalized_query unless @normalized_query == NONE
1620
- @normalized_query = begin
1621
- modified_query_class = Addressable::URI::CharacterClasses::QUERY.dup
1622
- # Make sure possible key-value pair delimiters are escaped.
1623
- modified_query_class.sub!("\\&", "").sub!("\\;", "")
1624
- pairs = (query || "").split("&", -1)
1763
+ return @normalized_query if flags.empty? && @normalized_query != NONE
1764
+ normalized_query = begin
1765
+ pairs = query.split("&", -1)
1625
1766
  pairs.delete_if(&:empty?).uniq! if flags.include?(:compacted)
1626
1767
  pairs.sort! if flags.include?(:sorted)
1627
1768
  component = pairs.map do |pair|
1628
- Addressable::URI.normalize_component(
1629
- pair,
1630
- Addressable::URI::NormalizeCharacterClasses::QUERY,
1631
- "+"
1632
- )
1769
+ NormalizeByPosition.query_pair(pair, NormalizeByPosition::QUERY_PAIR)
1633
1770
  end.join("&")
1634
1771
  component == "" ? nil : component
1635
1772
  end
1636
1773
  # All normalized values should be UTF-8
1637
- force_utf8_encoding_if_needed(@normalized_query)
1638
- @normalized_query
1774
+ force_utf8_encoding_if_needed(normalized_query)
1775
+ @normalized_query = normalized_query if flags.empty?
1776
+ normalized_query
1639
1777
  end
1640
1778
 
1641
1779
  ##
@@ -1643,7 +1781,7 @@ module Addressable
1643
1781
  #
1644
1782
  # @param [String, #to_str] new_query The new query component.
1645
1783
  def query=(new_query)
1646
- if new_query && !new_query.respond_to?(:to_str)
1784
+ if !new_query.nil? && !new_query.respond_to?(:to_str)
1647
1785
  raise TypeError, "Can't convert #{new_query.class} into String."
1648
1786
  end
1649
1787
  @query = new_query ? new_query.to_str : nil
@@ -1679,6 +1817,9 @@ module Addressable
1679
1817
  raise ArgumentError, "Invalid return type. Must be Hash or Array."
1680
1818
  end
1681
1819
  return nil if self.query == nil
1820
+ query_scheme = normalized_scheme
1821
+ form_encoded = query_scheme.nil? ||
1822
+ query_scheme == "http" || query_scheme == "https"
1682
1823
  split_query = self.query.split("&").map do |pair|
1683
1824
  pair.split("=", 2) if pair && !pair.empty?
1684
1825
  end.compact
@@ -1686,14 +1827,16 @@ module Addressable
1686
1827
  # I'd rather use key/value identifiers instead of array lookups,
1687
1828
  # but in this case I really want to maintain the exact pair structure,
1688
1829
  # so it's best to make all changes in-place.
1689
- pair[0] = URI.unencode_component(pair[0])
1830
+ key = pair[0]
1831
+ key = key.tr("+", " ") if form_encoded
1832
+ pair[0] = URI.unencode_component(key)
1690
1833
  if pair[1].respond_to?(:to_str)
1691
1834
  value = pair[1].to_str
1692
1835
  # I loathe the fact that I have to do this. Stupid HTML 4.01.
1693
1836
  # Treating '+' as a space was just an unbelievably bad idea.
1694
1837
  # There was nothing wrong with '%20'!
1695
1838
  # If it ain't broke, don't fix it!
1696
- value = value.tr("+", " ") if ["http", "https", nil].include?(scheme)
1839
+ value = value.tr("+", " ") if form_encoded
1697
1840
  pair[1] = URI.unencode_component(value)
1698
1841
  end
1699
1842
  if return_type == Hash
@@ -1770,17 +1913,40 @@ module Addressable
1770
1913
  self.query = buffer.chop
1771
1914
  end
1772
1915
 
1916
+ # Characters that can end or split an HTTP request line: control
1917
+ # characters and space.
1918
+ #
1919
+ # RFC 3986 leaves other characters out of a URI too, such as
1920
+ # non-ASCII text, '"', '{', '|', '^', and the brackets in a query like
1921
+ # "ids[]=1". Those are left as written. They can't end the request
1922
+ # line, servers commonly accept them, and encoding them would change
1923
+ # request targets that work today: a server that maps paths to keys
1924
+ # without decoding them, such as S3, would get a different key, and a
1925
+ # signature over the path and query as written (an HTTP message
1926
+ # signature, for example) would no longer match the request line.
1927
+ # For the same reason, the path and query aren't normalized here;
1928
+ # callers who want that can use normalize.request_uri.
1929
+ REQUEST_TARGET_UNSAFE = /[\x00-\x20\x7F]/n
1930
+ private_constant :REQUEST_TARGET_UNSAFE
1931
+
1773
1932
  ##
1774
1933
  # The HTTP request URI for this URI. This is the path and the
1775
- # query string.
1934
+ # query string, with control characters and spaces percent-encoded so
1935
+ # that it can't end or split the request line. Every other character is
1936
+ # left as written.
1776
1937
  #
1777
1938
  # @return [String] The request URI required for an HTTP request.
1778
1939
  def request_uri
1779
1940
  return nil if self.absolute? && self.scheme !~ /^https?$/i
1780
- return (
1941
+ target = (
1781
1942
  (!self.path.empty? ? self.path : SLASH) +
1782
1943
  (self.query ? "?#{self.query}" : EMPTY_STR)
1783
1944
  )
1945
+ bytes = target.b
1946
+ return target if bytes !~ REQUEST_TARGET_UNSAFE
1947
+ bytes.gsub(REQUEST_TARGET_UNSAFE) do |character|
1948
+ format("%%%02X", character.ord)
1949
+ end.force_encoding(target.encoding)
1784
1950
  end
1785
1951
 
1786
1952
  ##
@@ -1823,7 +1989,8 @@ module Addressable
1823
1989
  @normalized_fragment = begin
1824
1990
  component = Addressable::URI.normalize_component(
1825
1991
  self.fragment,
1826
- Addressable::URI::NormalizeCharacterClasses::FRAGMENT
1992
+ NormalizeByPosition::FRAGMENT,
1993
+ NormalizeByPosition::LEAVE_IN_FRAGMENT
1827
1994
  )
1828
1995
  component == "" ? nil : component
1829
1996
  end
@@ -1837,7 +2004,7 @@ module Addressable
1837
2004
  #
1838
2005
  # @param [String, #to_str] new_fragment The new fragment component.
1839
2006
  def fragment=(new_fragment)
1840
- if new_fragment && !new_fragment.respond_to?(:to_str)
2007
+ if !new_fragment.nil? && !new_fragment.respond_to?(:to_str)
1841
2008
  raise TypeError, "Can't convert #{new_fragment.class} into String."
1842
2009
  end
1843
2010
  @fragment = new_fragment ? new_fragment.to_str : nil
@@ -2106,28 +2273,27 @@ module Addressable
2106
2273
  components[:password] = nil
2107
2274
  components[:host] = nil
2108
2275
  components[:port] = nil
2109
- if normalized_self.path == uri.path
2276
+ if normalized_self.path == uri.path &&
2277
+ normalized_self.query == uri.query &&
2278
+ (normalized_self.fragment || uri.fragment.nil?)
2279
+ components[:path] = nil
2280
+ components[:query] = nil
2281
+ elsif normalized_self.path == uri.path && normalized_self.query
2110
2282
  components[:path] = nil
2111
- if normalized_self.query == uri.query
2112
- components[:query] = nil
2113
- end
2114
2283
  else
2115
- if uri.path != SLASH and components[:path]
2116
- self_splitted_path = split_path(components[:path])
2117
- uri_splitted_path = split_path(uri.path)
2118
- self_dir = self_splitted_path.shift
2119
- uri_dir = uri_splitted_path.shift
2120
- while !self_splitted_path.empty? && !uri_splitted_path.empty? and self_dir == uri_dir
2121
- self_dir = self_splitted_path.shift
2122
- uri_dir = uri_splitted_path.shift
2123
- end
2124
- components[:path] = (uri_splitted_path.fill('..') + [self_dir] + self_splitted_path).join(SLASH)
2284
+ # An empty path would keep the base's query (RFC 3986 5.2.2),
2285
+ # and join keeps the base's fragment for an empty reference.
2286
+ components[:path] = relative_path_from(uri, normalized_self.path)
2287
+ if components[:path].nil?
2288
+ components = normalized_self.to_hash
2125
2289
  end
2126
2290
  end
2127
2291
  end
2128
2292
  end
2129
- # Avoid network-path references.
2130
- if components[:host] != nil
2293
+ # Avoid network-path references, and keep the scheme for a URI
2294
+ # without an authority, which would otherwise take the base's.
2295
+ if components[:host] != nil ||
2296
+ normalized_self.authority != uri.authority
2131
2297
  components[:scheme] = normalized_self.scheme
2132
2298
  end
2133
2299
  # A first segment containing a colon would be read as a scheme.
@@ -2265,8 +2431,11 @@ module Addressable
2265
2431
  end
2266
2432
 
2267
2433
  ##
2268
- # A hash value that will make a URI equivalent to its normalized
2269
- # form.
2434
+ # A hash value consistent with <code>eql?</code>: URIs with the same
2435
+ # string have the same hash. Like <code>eql?</code>, it doesn't
2436
+ # normalize, so URIs that are only equal by <code>==</code>, such as
2437
+ # <code>HTTP://EXAMPLE.COM</code> and <code>http://example.com/</code>,
2438
+ # can have different hashes.
2270
2439
  #
2271
2440
  # @return [Integer] A hash of the URI.
2272
2441
  def hash
@@ -2346,6 +2515,9 @@ module Addressable
2346
2515
  ##
2347
2516
  # Converts the URI to a <code>String</code>.
2348
2517
  #
2518
+ # A frozen URI returns a new, mutable copy each time, so that callers
2519
+ # can change the string without changing the URI.
2520
+ #
2349
2521
  # @return [String] The URI's <code>String</code> representation.
2350
2522
  def to_s
2351
2523
  if self.scheme == nil && self.path != nil && !self.path.empty? &&
@@ -2363,6 +2535,7 @@ module Addressable
2363
2535
  uri_string.force_encoding(Encoding::UTF_8)
2364
2536
  uri_string
2365
2537
  end
2538
+ frozen? ? @uri_string.dup : @uri_string
2366
2539
  end
2367
2540
 
2368
2541
  ##
@@ -2403,12 +2576,17 @@ module Addressable
2403
2576
  # @param [Proc] block
2404
2577
  # A set of operations to perform on a given URI.
2405
2578
  def defer_validation
2406
- validation_was_deferred = !!@validation_deferred
2579
+ validation_was_deferred =
2580
+ !!(defined?(@validation_deferred) && @validation_deferred)
2407
2581
  raise LocalJumpError, "No block given." unless block_given?
2582
+ saved = save_components unless validation_was_deferred || frozen?
2408
2583
  @validation_deferred = true
2409
2584
  yield
2410
2585
  @validation_deferred = validation_was_deferred
2411
2586
  validate unless validation_was_deferred
2587
+ rescue Exception
2588
+ restore_components(saved) if saved
2589
+ raise
2412
2590
  ensure
2413
2591
  @validation_deferred = validation_was_deferred
2414
2592
  end
@@ -2436,15 +2614,6 @@ module Addressable
2436
2614
  SELF_REF = '.'
2437
2615
  PARENT = '..'
2438
2616
 
2439
- # Deprecated. No longer used by normalize_path; will be removed in 2.10.0.
2440
- RULE_2A = /\/\.\/|\/\.$/
2441
- RULE_2B_2C = /\/([^\/]*)\/\.\.\/|\/([^\/]*)\/\.\.$/
2442
- RULE_2D = /^\.\.?\/?/
2443
- RULE_PREFIXED_PARENT = /^\/\.\.?\/|^(\/\.\.?)+\/?$/
2444
- if respond_to?(:deprecate_constant, true)
2445
- deprecate_constant :RULE_2A, :RULE_2B_2C, :RULE_2D, :RULE_PREFIXED_PARENT
2446
- end
2447
-
2448
2617
  ##
2449
2618
  # Resolves paths to their simplest form.
2450
2619
  #
@@ -2510,6 +2679,12 @@ module Addressable
2510
2679
  raise InvalidURIError,
2511
2680
  "Absolute URI missing hierarchical segment: '#{self.to_s}'"
2512
2681
  end
2682
+ if self.port != nil && self.port > LARGEST_TRANSPORT_PORT &&
2683
+ URI.port_mapping.key?(self.normalized_scheme)
2684
+ raise InvalidURIError,
2685
+ "Port number out of range for #{self.normalized_scheme}: " +
2686
+ "#{self.port}"
2687
+ end
2513
2688
  if self.host == nil
2514
2689
  if self.port != nil ||
2515
2690
  self.user != nil ||
@@ -2528,16 +2703,79 @@ module Addressable
2528
2703
  "Cannot have a path with two leading slashes " +
2529
2704
  "without an authority set: '#{self.to_s}'"
2530
2705
  end
2531
- unreserved = CharacterClasses::UNRESERVED
2532
- sub_delims = CharacterClasses::SUB_DELIMS
2533
- if !self.host.nil? && (self.host =~ /[<>{}\/\\\?\#\@"[[:space:]]]/ ||
2534
- (self.host[/^\[(.*)\]$/, 1] != nil && self.host[/^\[(.*)\]$/, 1] !~
2535
- Regexp.new("^[#{unreserved}#{sub_delims}:]*$")))
2706
+ if !self.host.nil? && self.host =~ /[<>{}\/\\\?\#\@"[[:space:]]]/
2536
2707
  raise InvalidURIError, "Invalid character in host: '#{self.host.to_s}'"
2537
2708
  end
2709
+ if !self.host.nil? && self.host =~ /[\[\]]/ && !ip_literal?(self.host)
2710
+ raise InvalidURIError,
2711
+ "Brackets in a host must enclose an IPv6 address or an IPvFuture " +
2712
+ "literal: '#{self.host.to_s}'"
2713
+ end
2714
+ # Outside an IP literal, a colon would be read as the port delimiter
2715
+ # when the URI is serialized and parsed again.
2716
+ if !self.host.nil? && self.host.include?(":") && self.host[0] != "["
2717
+ raise InvalidURIError,
2718
+ "A colon in a host must be inside the brackets of an IP literal: " +
2719
+ "'#{self.host.to_s}'"
2720
+ end
2721
+ # These would end the userinfo early, or split it, when the URI is
2722
+ # serialized and parsed again. A backslash ends it for browsers, which
2723
+ # read it as a slash. An @ is left alone: the last @ ends the userinfo,
2724
+ # so it reads the same once serialized.
2725
+ if !self.user.nil? && self.user =~ /[\/?#\[\]\\:]/
2726
+ raise InvalidURIError, "Invalid character in user: '#{self.user}'"
2727
+ end
2728
+ if !self.password.nil? && self.password =~ /[\/?#\[\]\\]/
2729
+ raise InvalidURIError, "Invalid character in password"
2730
+ end
2538
2731
  return nil
2539
2732
  end
2540
2733
 
2734
+ # Parts of an IP-literal, from RFC 3986, section 3.2.2.
2735
+ IPV6_PIECE = /\A[0-9A-Fa-f]{1,4}\z/
2736
+ DEC_OCTET = "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
2737
+ IPV4_ADDRESS = /\A#{DEC_OCTET}(?:\.#{DEC_OCTET}){3}\z/
2738
+ IPV_FUTURE = /\A[vV][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&'()*+,;=:]+\z/
2739
+ private_constant :IPV6_PIECE, :DEC_OCTET, :IPV4_ADDRESS, :IPV_FUTURE
2740
+
2741
+ ##
2742
+ # Whether a host is an IP-literal from RFC 3986, section 3.2.2: an IPv6
2743
+ # address or an IPvFuture literal, in brackets.
2744
+ #
2745
+ # @param [String] host The host to check.
2746
+ #
2747
+ # @return [TrueClass, FalseClass]
2748
+ def ip_literal?(host)
2749
+ inner = host[/\A\[([^\[\]]*)\]\z/, 1]
2750
+ return false if inner.nil?
2751
+ inner =~ IPV_FUTURE ? true : ipv6_address?(inner)
2752
+ end
2753
+
2754
+ ##
2755
+ # Whether a string is an IPv6address from RFC 3986, section 3.2.2: eight
2756
+ # groups of up to four hex digits, where "::" stands for one or more
2757
+ # groups of zeros and an IPv4 address can stand for the last two groups.
2758
+ #
2759
+ # @param [String] address The string to check.
2760
+ #
2761
+ # @return [TrueClass, FalseClass]
2762
+ def ipv6_address?(address)
2763
+ halves = address.split("::", -1)
2764
+ return false if halves.empty? || halves.size > 2
2765
+ halves = halves.map { |half| half.empty? ? [] : half.split(":", -1) }
2766
+ groups = 0
2767
+ last = halves.last
2768
+ if last.last && last.last.include?(".")
2769
+ return false unless last.last =~ IPV4_ADDRESS
2770
+ halves[-1] = last[0...-1]
2771
+ groups = 2
2772
+ end
2773
+ pieces = halves.flatten
2774
+ return false unless pieces.all? { |piece| piece =~ IPV6_PIECE }
2775
+ groups += pieces.size
2776
+ halves.size == 2 ? groups <= 7 : groups == 8
2777
+ end
2778
+
2541
2779
  ##
2542
2780
  # Replaces the internal state of self with the specified URI's state.
2543
2781
  # Used in destructive operations to avoid massive code repetition.
@@ -2561,17 +2799,49 @@ module Addressable
2561
2799
  end
2562
2800
 
2563
2801
  ##
2564
- # Splits path string with "/" (slash).
2565
- # It is considered that there is empty string after last slash when
2566
- # path ends with slash.
2802
+ # Returns a relative path that resolves to path against the base URI,
2803
+ # or nil if no relative path does.
2567
2804
  #
2568
- # @param [String] path The path to split.
2805
+ # @param [Addressable::URI] base The normalized base URI.
2806
+ # @param [String] path The normalized path to route to.
2569
2807
  #
2570
- # @return [Array<String>] An array of parts of path.
2571
- def split_path(path)
2572
- splitted = path.split(SLASH)
2573
- splitted << EMPTY_STR if path.end_with? SLASH
2574
- splitted
2808
+ # @return [String, nil] The relative path.
2809
+ #
2810
+ # @api private
2811
+ def relative_path_from(base, path)
2812
+ base_path = base.path
2813
+ base_path = SLASH if base_path.empty? && base.authority
2814
+ slash = base_path.rindex(SLASH)
2815
+ base_dir = slash ? base_path[0..slash] : EMPTY_STR
2816
+ rooted = path.start_with?(SLASH)
2817
+ if rooted != base_dir.start_with?(SLASH)
2818
+ # Merging keeps the slash a base directory starts with, and a path
2819
+ # without an authority can't start with "//".
2820
+ return rooted ? path : nil
2821
+ end
2822
+ if base_path == SLASH && path != SLASH && !path.start_with?("//")
2823
+ return path
2824
+ end
2825
+ base_segments = base_dir.split(SLASH, -1)
2826
+ base_segments.pop
2827
+ segments = path.split(SLASH, -1)
2828
+ # Normalization keeps a ".." it can't remove, and resolving a relative
2829
+ # path would remove it.
2830
+ return nil if segments.include?(PARENT)
2831
+ shared = 0
2832
+ while shared < segments.size - 1 &&
2833
+ base_segments[shared] == segments[shared]
2834
+ shared += 1
2835
+ end
2836
+ # Without a leading slash, ".." can't climb out of a base directory.
2837
+ return nil if !rooted && shared < base_segments.size
2838
+ relative = "../" * (base_segments.size - shared) +
2839
+ segments[shared..-1].join(SLASH)
2840
+ # An empty path is the base itself, and a leading "/" an absolute path.
2841
+ if relative.empty? || relative.start_with?(SLASH)
2842
+ relative = "./" + relative
2843
+ end
2844
+ relative
2575
2845
  end
2576
2846
 
2577
2847
  ##
@@ -2581,6 +2851,9 @@ module Addressable
2581
2851
  def remove_composite_values
2582
2852
  @uri_string = nil
2583
2853
  @hash = nil
2854
+ @site = nil
2855
+ @normalized_site = nil
2856
+ @normalized_authority = nil
2584
2857
  end
2585
2858
 
2586
2859
  ##
@@ -2595,11 +2868,71 @@ module Addressable
2595
2868
 
2596
2869
  private
2597
2870
 
2871
+ def initialize_copy(other)
2872
+ super
2873
+ instance_variables.each do |ivar|
2874
+ value = instance_variable_get(ivar)
2875
+ instance_variable_set(ivar, value.dup) if value.kind_of?(String)
2876
+ end
2877
+ end
2878
+
2879
+ # Ruby 3.0+ passes freeze: when clone is called with it.
2880
+ def initialize_clone(other, freeze: nil)
2881
+ super(other)
2882
+ prepare_to_freeze if freeze.nil? ? other.frozen? : freeze
2883
+ end
2884
+
2885
+ ##
2886
+ # Computes every cached value, so that a frozen URI never needs to set
2887
+ # one, and replaces the strings it holds with frozen copies. A string
2888
+ # passed to a setter is copied rather than frozen, so that freezing the
2889
+ # URI doesn't freeze the caller's string.
2890
+ def prepare_to_freeze
2891
+ self.normalized_scheme
2892
+ self.normalized_user
2893
+ self.normalized_password
2894
+ self.normalized_userinfo
2895
+ self.normalized_host
2896
+ self.normalized_port
2897
+ self.normalized_authority
2898
+ self.normalized_site
2899
+ self.normalized_path
2900
+ self.normalized_query
2901
+ self.normalized_fragment
2902
+ self.hash
2903
+ instance_variables.each do |ivar|
2904
+ value = instance_variable_get(ivar)
2905
+ if value.kind_of?(String) && !value.frozen?
2906
+ instance_variable_set(ivar, value.dup.freeze)
2907
+ end
2908
+ end
2909
+ end
2910
+
2598
2911
  ##
2599
2912
  # Resets instance variables
2600
2913
  #
2601
2914
  # @api private
2915
+ ##
2916
+ # A setter puts the components back if it raises, so that a failed
2917
+ # assignment doesn't leave the URI half changed. Within defer_validation
2918
+ # the outermost block does that instead, and a frozen URI can't change.
2919
+ def components_restored_elsewhere?
2920
+ frozen? || (defined?(@validation_deferred) && @validation_deferred)
2921
+ end
2922
+
2923
+ def save_components
2924
+ [@scheme, @user, @password, @host, @port, @path, @query, @fragment]
2925
+ end
2926
+
2927
+ # The other instance variables are derived from these, so clear them.
2928
+ def restore_components(saved)
2929
+ reset_ivs
2930
+ @scheme, @user, @password, @host, @port, @path, @query, @fragment = saved
2931
+ end
2932
+
2602
2933
  def reset_ivs
2934
+ @site = nil
2935
+ @normalized_site = nil
2603
2936
  @scheme = nil
2604
2937
  @user = nil
2605
2938
  @normalized_scheme = NONE
@@ -2627,5 +2960,30 @@ module Addressable
2627
2960
  NONE = Module.new.freeze
2628
2961
 
2629
2962
  private_constant :NONE
2963
+
2964
+ # Wraps each setter so that it changes nothing when it raises.
2965
+ module RestoreOnFailure
2966
+ [
2967
+ :scheme=, :user=, :password=, :userinfo=, :host=, :hostname=, :tld=,
2968
+ :authority=, :origin=, :port=, :site=, :path=, :query=,
2969
+ :query_values=, :request_uri=, :fragment=
2970
+ ].each do |setter|
2971
+ # A method from define_method can't be called in another Ractor.
2972
+ module_eval <<-RUBY, __FILE__, __LINE__ + 1
2973
+ def #{setter}(value)
2974
+ return super if components_restored_elsewhere?
2975
+ saved = save_components
2976
+ begin
2977
+ super
2978
+ rescue Exception
2979
+ restore_components(saved)
2980
+ raise
2981
+ end
2982
+ end
2983
+ RUBY
2984
+ end
2985
+ end
2986
+ private_constant :RestoreOnFailure
2987
+ prepend RestoreOnFailure
2630
2988
  end
2631
2989
  end