addressable 2.9.2 → 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
@@ -973,7 +1068,7 @@ module Addressable
973
1068
  #
974
1069
  # @param [String, #to_str] new_user The new user component.
975
1070
  def user=(new_user)
976
- if new_user && !new_user.respond_to?(:to_str)
1071
+ if !new_user.nil? && !new_user.respond_to?(:to_str)
977
1072
  raise TypeError, "Can't convert #{new_user.class} into String."
978
1073
  end
979
1074
  @user = new_user ? new_user.to_str : nil
@@ -1029,7 +1124,7 @@ module Addressable
1029
1124
  #
1030
1125
  # @param [String, #to_str] new_password The new password component.
1031
1126
  def password=(new_password)
1032
- if new_password && !new_password.respond_to?(:to_str)
1127
+ if !new_password.nil? && !new_password.respond_to?(:to_str)
1033
1128
  raise TypeError, "Can't convert #{new_password.class} into String."
1034
1129
  end
1035
1130
  @password = new_password ? new_password.to_str : nil
@@ -1060,10 +1155,11 @@ module Addressable
1060
1155
  current_user = self.user
1061
1156
  current_password = self.password
1062
1157
  (current_user || current_password) && @userinfo ||= begin
1158
+ # Before Ruby 3.0, an interpolated string here would be frozen.
1063
1159
  if current_user && current_password
1064
- "#{current_user}:#{current_password}"
1160
+ "#{current_user}:#{current_password}".dup
1065
1161
  elsif current_user && !current_password
1066
- "#{current_user}"
1162
+ current_user.dup
1067
1163
  end
1068
1164
  end
1069
1165
  end
@@ -1096,12 +1192,12 @@ module Addressable
1096
1192
  #
1097
1193
  # @param [String, #to_str] new_userinfo The new userinfo component.
1098
1194
  def userinfo=(new_userinfo)
1099
- if new_userinfo && !new_userinfo.respond_to?(:to_str)
1195
+ if !new_userinfo.nil? && !new_userinfo.respond_to?(:to_str)
1100
1196
  raise TypeError, "Can't convert #{new_userinfo.class} into String."
1101
1197
  end
1102
1198
  new_user, new_password = if new_userinfo
1103
1199
  [
1104
- new_userinfo.to_str.strip[/^(.*):/, 1],
1200
+ new_userinfo.to_str.strip[/^([^:]*):?/, 1],
1105
1201
  new_userinfo.to_str.strip[/:(.*)$/, 1]
1106
1202
  ]
1107
1203
  else
@@ -1135,16 +1231,39 @@ module Addressable
1135
1231
 
1136
1232
  @normalized_host ||= begin
1137
1233
  if !self.host.strip.empty?
1138
- result = ::Addressable::IDNA.to_ascii(
1139
- URI.unencode_component(self.host.strip.downcase)
1140
- )
1141
- 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/
1142
1254
  # Single trailing dots are unnecessary.
1143
1255
  result = result[0...-1]
1144
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.
1145
1260
  result = Addressable::URI.normalize_component(
1146
1261
  result,
1147
- NormalizeCharacterClasses::HOST
1262
+ if IP_LITERAL =~ self.host
1263
+ NormalizeCharacterClasses::HOST
1264
+ else
1265
+ NormalizeCharacterClasses::REG_NAME
1266
+ end
1148
1267
  )
1149
1268
  result
1150
1269
  else
@@ -1161,7 +1280,7 @@ module Addressable
1161
1280
  #
1162
1281
  # @param [String, #to_str] new_host The new host component.
1163
1282
  def host=(new_host)
1164
- if new_host && !new_host.respond_to?(:to_str)
1283
+ if !new_host.nil? && !new_host.respond_to?(:to_str)
1165
1284
  raise TypeError, "Can't convert #{new_host.class} into String."
1166
1285
  end
1167
1286
  @host = new_host ? new_host.to_str : nil
@@ -1198,7 +1317,7 @@ module Addressable
1198
1317
  if new_hostname &&
1199
1318
  (new_hostname.respond_to?(:ipv4?) || new_hostname.respond_to?(:ipv6?))
1200
1319
  new_hostname = new_hostname.to_s
1201
- elsif new_hostname && !new_hostname.respond_to?(:to_str)
1320
+ elsif !new_hostname.nil? && !new_hostname.respond_to?(:to_str)
1202
1321
  raise TypeError, "Can't convert #{new_hostname.class} into String."
1203
1322
  end
1204
1323
  v = new_hostname ? new_hostname.to_str : nil
@@ -1279,7 +1398,7 @@ module Addressable
1279
1398
  #
1280
1399
  # @param [String, #to_str] new_authority The new authority component.
1281
1400
  def authority=(new_authority)
1282
- if new_authority
1401
+ unless new_authority.nil?
1283
1402
  if !new_authority.respond_to?(:to_str)
1284
1403
  raise TypeError, "Can't convert #{new_authority.class} into String."
1285
1404
  end
@@ -1338,24 +1457,31 @@ module Addressable
1338
1457
  #
1339
1458
  # @param [String, #to_str] new_origin The new origin component.
1340
1459
  def origin=(new_origin)
1341
- if new_origin
1460
+ unless new_origin.nil?
1342
1461
  if !new_origin.respond_to?(:to_str)
1343
1462
  raise TypeError, "Can't convert #{new_origin.class} into String."
1344
1463
  end
1345
1464
  new_origin = new_origin.to_str
1346
- new_scheme = new_origin[/^([^:\/?#]+):\/\//, 1]
1347
- unless new_scheme
1465
+ origin_match = new_origin.match(
1466
+ /\A([^:\/?#]+):\/\/(\[[^\]]+\]|[^\/?#:@]+)(?::([^\/?#]*))?\z/
1467
+ )
1468
+ unless new_origin =~ /\A[^:\/?#]+:\/\//
1348
1469
  raise InvalidURIError, 'An origin cannot omit the scheme.'
1349
1470
  end
1350
- new_host = new_origin[/:\/\/([^\/?#:]+)/, 1]
1351
- unless new_host
1352
- 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.'
1353
1479
  end
1354
- new_port = new_origin[/:([^:@\[\]\/]*?)$/, 1]
1355
- # An empty port is the same as no port (Section 3.2.3 of RFC 3986).
1356
- if new_port == EMPTY_STR && new_origin =~ /\A[^:\/?#]+:\/\/[^\/?#:@\[\]]+:\z/
1357
- new_port = nil
1480
+ if new_port && new_port !~ /\A\d*\z/
1481
+ raise InvalidURIError, "Invalid port number: #{new_port.inspect}"
1358
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
1359
1485
  end
1360
1486
 
1361
1487
  self.scheme = new_scheme
@@ -1425,12 +1551,24 @@ module Addressable
1425
1551
  raise InvalidURIError, "Invalid encoding in port"
1426
1552
  end
1427
1553
 
1428
- 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/)
1429
1560
  raise InvalidURIError,
1430
1561
  "Invalid port number: #{new_port.inspect}"
1431
1562
  end
1432
1563
 
1433
- @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
1434
1572
  @port = nil if @port == 0
1435
1573
 
1436
1574
  # Reset dependent values
@@ -1515,7 +1653,10 @@ module Addressable
1515
1653
  #
1516
1654
  # @param [String, #to_str] new_site The new site value.
1517
1655
  def site=(new_site)
1518
- if new_site
1656
+ if new_site.nil?
1657
+ self.scheme = nil
1658
+ self.authority = nil
1659
+ else
1519
1660
  if !new_site.respond_to?(:to_str)
1520
1661
  raise TypeError, "Can't convert #{new_site.class} into String."
1521
1662
  end
@@ -1526,9 +1667,6 @@ module Addressable
1526
1667
  self.authority = new_site[
1527
1668
  /^(?:(?:[^:\/?#]+):)?(?:\/\/([^\/?#]*))?$/, 1
1528
1669
  ]
1529
- else
1530
- self.scheme = nil
1531
- self.authority = nil
1532
1670
  end
1533
1671
  end
1534
1672
 
@@ -1546,20 +1684,19 @@ module Addressable
1546
1684
  def normalized_path
1547
1685
  @normalized_path ||= begin
1548
1686
  path = self.path.to_s
1549
- if self.scheme == nil && path =~ NORMPATH
1550
- # Relative paths with colons in the first segment are ambiguous.
1551
- path = path.sub(":", "%2F")
1552
- end
1553
1687
  # String#split(delimiter, -1) uses the more strict splitting behavior
1554
1688
  # found by default in Python.
1555
1689
  result = path.strip.split(SLASH, -1).map do |segment|
1556
1690
  Addressable::URI.normalize_component(
1557
1691
  segment,
1558
- Addressable::URI::NormalizeCharacterClasses::PCHAR
1692
+ NormalizeByPosition::PCHAR,
1693
+ NormalizeByPosition::LEAVE_IN_SEGMENT
1559
1694
  )
1560
1695
  end.join(SLASH)
1561
1696
 
1562
- result = URI.normalize_path(result)
1697
+ result = NormalizeByPosition.encode_relative_colons(
1698
+ URI.normalize_path(result), self.scheme
1699
+ )
1563
1700
  if result.empty? &&
1564
1701
  ["http", "https", "ftp", "tftp"].include?(self.normalized_scheme)
1565
1702
  result = SLASH.dup
@@ -1576,7 +1713,7 @@ module Addressable
1576
1713
  #
1577
1714
  # @param [String, #to_str] new_path The new path component.
1578
1715
  def path=(new_path)
1579
- if new_path && !new_path.respond_to?(:to_str)
1716
+ if !new_path.nil? && !new_path.respond_to?(:to_str)
1580
1717
  raise TypeError, "Can't convert #{new_path.class} into String."
1581
1718
  end
1582
1719
  @path = (new_path || EMPTY_STR).to_str
@@ -1625,15 +1762,11 @@ module Addressable
1625
1762
  return nil unless self.query
1626
1763
  return @normalized_query if flags.empty? && @normalized_query != NONE
1627
1764
  normalized_query = begin
1628
- pairs = (query || "").split("&", -1)
1765
+ pairs = query.split("&", -1)
1629
1766
  pairs.delete_if(&:empty?).uniq! if flags.include?(:compacted)
1630
1767
  pairs.sort! if flags.include?(:sorted)
1631
1768
  component = pairs.map do |pair|
1632
- Addressable::URI.normalize_component(
1633
- pair,
1634
- Addressable::URI::NormalizeCharacterClasses::QUERY,
1635
- "+"
1636
- )
1769
+ NormalizeByPosition.query_pair(pair, NormalizeByPosition::QUERY_PAIR)
1637
1770
  end.join("&")
1638
1771
  component == "" ? nil : component
1639
1772
  end
@@ -1648,7 +1781,7 @@ module Addressable
1648
1781
  #
1649
1782
  # @param [String, #to_str] new_query The new query component.
1650
1783
  def query=(new_query)
1651
- if new_query && !new_query.respond_to?(:to_str)
1784
+ if !new_query.nil? && !new_query.respond_to?(:to_str)
1652
1785
  raise TypeError, "Can't convert #{new_query.class} into String."
1653
1786
  end
1654
1787
  @query = new_query ? new_query.to_str : nil
@@ -1684,6 +1817,9 @@ module Addressable
1684
1817
  raise ArgumentError, "Invalid return type. Must be Hash or Array."
1685
1818
  end
1686
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"
1687
1823
  split_query = self.query.split("&").map do |pair|
1688
1824
  pair.split("=", 2) if pair && !pair.empty?
1689
1825
  end.compact
@@ -1691,14 +1827,16 @@ module Addressable
1691
1827
  # I'd rather use key/value identifiers instead of array lookups,
1692
1828
  # but in this case I really want to maintain the exact pair structure,
1693
1829
  # so it's best to make all changes in-place.
1694
- 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)
1695
1833
  if pair[1].respond_to?(:to_str)
1696
1834
  value = pair[1].to_str
1697
1835
  # I loathe the fact that I have to do this. Stupid HTML 4.01.
1698
1836
  # Treating '+' as a space was just an unbelievably bad idea.
1699
1837
  # There was nothing wrong with '%20'!
1700
1838
  # If it ain't broke, don't fix it!
1701
- value = value.tr("+", " ") if ["http", "https", nil].include?(scheme)
1839
+ value = value.tr("+", " ") if form_encoded
1702
1840
  pair[1] = URI.unencode_component(value)
1703
1841
  end
1704
1842
  if return_type == Hash
@@ -1775,17 +1913,40 @@ module Addressable
1775
1913
  self.query = buffer.chop
1776
1914
  end
1777
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
+
1778
1932
  ##
1779
1933
  # The HTTP request URI for this URI. This is the path and the
1780
- # 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.
1781
1937
  #
1782
1938
  # @return [String] The request URI required for an HTTP request.
1783
1939
  def request_uri
1784
1940
  return nil if self.absolute? && self.scheme !~ /^https?$/i
1785
- return (
1941
+ target = (
1786
1942
  (!self.path.empty? ? self.path : SLASH) +
1787
1943
  (self.query ? "?#{self.query}" : EMPTY_STR)
1788
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)
1789
1950
  end
1790
1951
 
1791
1952
  ##
@@ -1828,7 +1989,8 @@ module Addressable
1828
1989
  @normalized_fragment = begin
1829
1990
  component = Addressable::URI.normalize_component(
1830
1991
  self.fragment,
1831
- Addressable::URI::NormalizeCharacterClasses::FRAGMENT
1992
+ NormalizeByPosition::FRAGMENT,
1993
+ NormalizeByPosition::LEAVE_IN_FRAGMENT
1832
1994
  )
1833
1995
  component == "" ? nil : component
1834
1996
  end
@@ -1842,7 +2004,7 @@ module Addressable
1842
2004
  #
1843
2005
  # @param [String, #to_str] new_fragment The new fragment component.
1844
2006
  def fragment=(new_fragment)
1845
- if new_fragment && !new_fragment.respond_to?(:to_str)
2007
+ if !new_fragment.nil? && !new_fragment.respond_to?(:to_str)
1846
2008
  raise TypeError, "Can't convert #{new_fragment.class} into String."
1847
2009
  end
1848
2010
  @fragment = new_fragment ? new_fragment.to_str : nil
@@ -2111,28 +2273,27 @@ module Addressable
2111
2273
  components[:password] = nil
2112
2274
  components[:host] = nil
2113
2275
  components[:port] = nil
2114
- 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
2115
2282
  components[:path] = nil
2116
- if normalized_self.query == uri.query
2117
- components[:query] = nil
2118
- end
2119
2283
  else
2120
- if uri.path != SLASH and components[:path]
2121
- self_splitted_path = split_path(components[:path])
2122
- uri_splitted_path = split_path(uri.path)
2123
- self_dir = self_splitted_path.shift
2124
- uri_dir = uri_splitted_path.shift
2125
- while !self_splitted_path.empty? && !uri_splitted_path.empty? and self_dir == uri_dir
2126
- self_dir = self_splitted_path.shift
2127
- uri_dir = uri_splitted_path.shift
2128
- end
2129
- 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
2130
2289
  end
2131
2290
  end
2132
2291
  end
2133
2292
  end
2134
- # Avoid network-path references.
2135
- 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
2136
2297
  components[:scheme] = normalized_self.scheme
2137
2298
  end
2138
2299
  # A first segment containing a colon would be read as a scheme.
@@ -2270,8 +2431,11 @@ module Addressable
2270
2431
  end
2271
2432
 
2272
2433
  ##
2273
- # A hash value that will make a URI equivalent to its normalized
2274
- # 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.
2275
2439
  #
2276
2440
  # @return [Integer] A hash of the URI.
2277
2441
  def hash
@@ -2351,6 +2515,9 @@ module Addressable
2351
2515
  ##
2352
2516
  # Converts the URI to a <code>String</code>.
2353
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
+ #
2354
2521
  # @return [String] The URI's <code>String</code> representation.
2355
2522
  def to_s
2356
2523
  if self.scheme == nil && self.path != nil && !self.path.empty? &&
@@ -2368,6 +2535,7 @@ module Addressable
2368
2535
  uri_string.force_encoding(Encoding::UTF_8)
2369
2536
  uri_string
2370
2537
  end
2538
+ frozen? ? @uri_string.dup : @uri_string
2371
2539
  end
2372
2540
 
2373
2541
  ##
@@ -2411,10 +2579,14 @@ module Addressable
2411
2579
  validation_was_deferred =
2412
2580
  !!(defined?(@validation_deferred) && @validation_deferred)
2413
2581
  raise LocalJumpError, "No block given." unless block_given?
2582
+ saved = save_components unless validation_was_deferred || frozen?
2414
2583
  @validation_deferred = true
2415
2584
  yield
2416
2585
  @validation_deferred = validation_was_deferred
2417
2586
  validate unless validation_was_deferred
2587
+ rescue Exception
2588
+ restore_components(saved) if saved
2589
+ raise
2418
2590
  ensure
2419
2591
  @validation_deferred = validation_was_deferred
2420
2592
  end
@@ -2442,15 +2614,6 @@ module Addressable
2442
2614
  SELF_REF = '.'
2443
2615
  PARENT = '..'
2444
2616
 
2445
- # Deprecated. No longer used by normalize_path; will be removed in 2.10.0.
2446
- RULE_2A = /\/\.\/|\/\.$/
2447
- RULE_2B_2C = /\/([^\/]*)\/\.\.\/|\/([^\/]*)\/\.\.$/
2448
- RULE_2D = /^\.\.?\/?/
2449
- RULE_PREFIXED_PARENT = /^\/\.\.?\/|^(\/\.\.?)+\/?$/
2450
- if respond_to?(:deprecate_constant, true)
2451
- deprecate_constant :RULE_2A, :RULE_2B_2C, :RULE_2D, :RULE_PREFIXED_PARENT
2452
- end
2453
-
2454
2617
  ##
2455
2618
  # Resolves paths to their simplest form.
2456
2619
  #
@@ -2516,6 +2679,12 @@ module Addressable
2516
2679
  raise InvalidURIError,
2517
2680
  "Absolute URI missing hierarchical segment: '#{self.to_s}'"
2518
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
2519
2688
  if self.host == nil
2520
2689
  if self.port != nil ||
2521
2690
  self.user != nil ||
@@ -2534,16 +2703,79 @@ module Addressable
2534
2703
  "Cannot have a path with two leading slashes " +
2535
2704
  "without an authority set: '#{self.to_s}'"
2536
2705
  end
2537
- unreserved = CharacterClasses::UNRESERVED
2538
- sub_delims = CharacterClasses::SUB_DELIMS
2539
- if !self.host.nil? && (self.host =~ /[<>{}\/\\\?\#\@"[[:space:]]]/ ||
2540
- (self.host[/^\[(.*)\]$/, 1] != nil && self.host[/^\[(.*)\]$/, 1] !~
2541
- Regexp.new("^[#{unreserved}#{sub_delims}:]*$")))
2706
+ if !self.host.nil? && self.host =~ /[<>{}\/\\\?\#\@"[[:space:]]]/
2542
2707
  raise InvalidURIError, "Invalid character in host: '#{self.host.to_s}'"
2543
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
2544
2731
  return nil
2545
2732
  end
2546
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
+
2547
2779
  ##
2548
2780
  # Replaces the internal state of self with the specified URI's state.
2549
2781
  # Used in destructive operations to avoid massive code repetition.
@@ -2567,17 +2799,49 @@ module Addressable
2567
2799
  end
2568
2800
 
2569
2801
  ##
2570
- # Splits path string with "/" (slash).
2571
- # It is considered that there is empty string after last slash when
2572
- # 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.
2804
+ #
2805
+ # @param [Addressable::URI] base The normalized base URI.
2806
+ # @param [String] path The normalized path to route to.
2573
2807
  #
2574
- # @param [String] path The path to split.
2808
+ # @return [String, nil] The relative path.
2575
2809
  #
2576
- # @return [Array<String>] An array of parts of path.
2577
- def split_path(path)
2578
- splitted = path.split(SLASH)
2579
- splitted << EMPTY_STR if path.end_with? SLASH
2580
- splitted
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
2581
2845
  end
2582
2846
 
2583
2847
  ##
@@ -2612,10 +2876,60 @@ module Addressable
2612
2876
  end
2613
2877
  end
2614
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
+
2615
2911
  ##
2616
2912
  # Resets instance variables
2617
2913
  #
2618
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
+
2619
2933
  def reset_ivs
2620
2934
  @site = nil
2621
2935
  @normalized_site = nil
@@ -2646,5 +2960,30 @@ module Addressable
2646
2960
  NONE = Module.new.freeze
2647
2961
 
2648
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
2649
2988
  end
2650
2989
  end