Skip to content

Handle invalid encoding in the pure ruby version of CGI.escapeHTML and CGI.unescapeHTML #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions lib/cgi/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,12 @@ def escapeHTML(string)
table = Hash[TABLE_FOR_ESCAPE_HTML__.map {|pair|pair.map {|s|s.encode(enc)}}]
string = string.gsub(/#{"['&\"<>]".encode(enc)}/, table)
string.encode!(origenc) if origenc
return string
string
else
string = string.b
string.gsub!(/['&\"<>]/, TABLE_FOR_ESCAPE_HTML__)
string.force_encoding(enc)
end
string.gsub(/['&\"<>]/, TABLE_FOR_ESCAPE_HTML__)
end

begin
Expand Down Expand Up @@ -90,7 +93,8 @@ def unescapeHTML(string)
when Encoding::ISO_8859_1; 256
else 128
end
string.gsub(/&(apos|amp|quot|gt|lt|\#[0-9]+|\#[xX][0-9A-Fa-f]+);/) do
string = string.b
string.gsub!(/&(apos|amp|quot|gt|lt|\#[0-9]+|\#[xX][0-9A-Fa-f]+);/) do
match = $1.dup
case match
when 'apos' then "'"
Expand All @@ -116,6 +120,7 @@ def unescapeHTML(string)
"&#{match};"
end
end
string.force_encoding enc
end

# Synonym for CGI.escapeHTML(str)
Expand Down
33 changes: 30 additions & 3 deletions test/cgi/test_cgi_util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ def test_cgi_escape_with_unreserved_characters
end

def test_cgi_escape_with_invalid_byte_sequence
assert_nothing_raised(ArgumentError) do
assert_equal('%C0%3C%3C', CGI.escape("\xC0\<\<".dup.force_encoding("UTF-8")))
end
assert_equal('%C0%3C%3C', CGI.escape("\xC0\<\<".dup.force_encoding("UTF-8")))
end

def test_cgi_escape_preserve_encoding
Expand Down Expand Up @@ -191,3 +189,32 @@ def test_cgi_unescapeElement
assert_equal('&lt;BR&gt;<A HREF="url"></A>', unescape_element(escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"]))
end
end

class CGIUtilPureRubyTest < Test::Unit::TestCase
def setup
CGI::Escape.module_eval do
alias _escapeHTML escapeHTML
remove_method :escapeHTML
alias _unescapeHTML unescapeHTML
remove_method :unescapeHTML
end
end

def teardown
CGI::Escape.module_eval do
alias escapeHTML _escapeHTML
remove_method :_escapeHTML
alias unescapeHTML _unescapeHTML
remove_method :_unescapeHTML
end
end

def test_cgi_escapeHTML_with_invalid_byte_sequence
assert_equal("&lt;\xA4??&gt;", CGI.escapeHTML(%[<\xA4??>]))
end

def test_cgi_unescapeHTML_with_invalid_byte_sequence
input = "\xFF&"
assert_equal(input, CGI.unescapeHTML(input))
end
end