From 8824d2ef417e0a4ed059846dfe9f3b264ffe9652 Mon Sep 17 00:00:00 2001 From: Yusuke Endoh Date: Mon, 9 Nov 2026 03:22:12 +0900 Subject: [PATCH] Keep the RFC 2396 regexps within the match cache The bounded repeats {2}, {1,3} and {1,4} inside other repeats keep the regexp match cache from being used, and URI.extract and URI.regexp took quadratic time on some inputs. Spell them out with optional atoms so that the regexps satisfy Regexp.linear_time?. Reported-by: Bilal Karaaslan (https://hackerone.com/bilalkaraaslan) Co-Authored-By: Claude Opus 5.5 --- lib/uri/rfc2396_parser.rb | 8 +++++--- test/uri/test_parser.rb | 9 +++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/uri/rfc2396_parser.rb b/lib/uri/rfc2396_parser.rb index cefd126c..36bfea74 100644 --- a/lib/uri/rfc2396_parser.rb +++ b/lib/uri/rfc2396_parser.rb @@ -33,7 +33,7 @@ module PATTERN # "a" | "b" | "c" | "d" | "e" | "f" HEX = "a-fA-F\\d" # escaped = "%" hex hex - ESCAPED = "%[#{HEX}]{2}" + ESCAPED = "%[#{HEX}][#{HEX}]" # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | # "(" | ")" # unreserved = alphanum | mark @@ -374,9 +374,11 @@ def initialize_pattern(opts = {}) # allowed too. Here is a replacement. # # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT - ret[:IPV4ADDR] = ipv4addr = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" + dig3 = "\\d\\d?\\d?" + ret[:IPV4ADDR] = ipv4addr = "#{dig3}\\.#{dig3}\\.#{dig3}\\.#{dig3}" # hex4 = 1*4HEXDIG - hex4 = "[#{PATTERN::HEX}]{1,4}" + hex = "[#{PATTERN::HEX}]" + hex4 = "#{hex}#{hex}?#{hex}?#{hex}?" # lastpart = hex4 | IPv4address lastpart = "(?:#{hex4}|#{ipv4addr})" # hexseq1 = *( hex4 ":" ) hex4 diff --git a/test/uri/test_parser.rb b/test/uri/test_parser.rb index c14824f5..3328b585 100644 --- a/test/uri/test_parser.rb +++ b/test/uri/test_parser.rb @@ -121,4 +121,13 @@ def test_rfc2822_make_regexp assert_match(regexp, "http://example.com/") refute_match(regexp, "https://example.com/") end + + def test_rfc2396_regexp_linear_time + omit "Regexp.linear_time? is not available" unless Regexp.respond_to?(:linear_time?) + URI::RFC2396_PARSER.regexp.each do |name, re| + assert Regexp.linear_time?(re), "regexp[#{name.inspect}] should be linear time" + end + assert Regexp.linear_time?(URI::RFC2396_PARSER.make_regexp) + assert Regexp.linear_time?(URI::RFC2396_PARSER.make_regexp(%w[http https])) + end end