Skip to content

fix character encoding sniffing #142

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
17 changes: 7 additions & 10 deletions lib/net/http/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ def check_bom(str)
def scanning_meta(str)
require 'strscan'
ss = StringScanner.new(str)
if ss.scan_until(/<meta[\t\n\f\r ]*/)
while ss.scan_until(/<meta[\t\n\f\r ]*/)
attrs = {} # attribute_list
got_pragma = false
need_pragma = nil
Expand All @@ -490,11 +490,11 @@ def scanning_meta(str)
end

# step: Processing
return if need_pragma.nil?
return if need_pragma && !got_pragma
next if need_pragma.nil?
next if need_pragma && !got_pragma

charset = Encoding.find(charset) rescue nil
return unless charset
next unless charset
charset = Encoding::UTF_8 if charset == Encoding::UTF_16
return charset # tentative
end
Expand All @@ -519,19 +519,16 @@ def get_attribute(ss)
case ss.peek(1)
when '"'
ss.getch
value = ss.scan(/[^"]+/)
value.downcase!
value = ss.scan(/[^"]+/)&.downcase
ss.getch
when "'"
ss.getch
value = ss.scan(/[^']+/)
value.downcase!
value = ss.scan(/[^']+/)&.downcase
ss.getch
when '>'
value = ''
else
value = ss.scan(/[^\t\n\f\r >]+/)
value.downcase!
value = ss.scan(/[^\t\n\f\r >]+/)&.downcase
end
[name, value]
end
Expand Down
26 changes: 25 additions & 1 deletion test/net/http/test_httpresponse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,31 @@ def test_read_body_body_encoding_true_with_iso8859_1_meta_charset
end

def test_read_body_body_encoding_true_with_utf8_meta_content_charset
res_body = "<meta http-equiv='content-type' content='text/html; charset=UTF-8'>hello\u1234</html>"
res_body = "<meta http-equiv='content-type' content='text/html; charset=UTF-8'>hello</html>"
io = dummy_io(<<EOS)
HTTP/1.1 200 OK
Connection: close
Content-Length: #{res_body.bytesize}
Content-Type: text/html

#{res_body}
EOS

res = Net::HTTPResponse.read_new(io)
res.body_encoding = true

body = nil

res.reading_body io, true do
body = res.read_body
end

assert_equal res_body, body
assert_equal Encoding::UTF_8, body.encoding
end

def test_read_body_body_encoding_true_with_empty_meta_content
res_body = "<meta name='keywords' content=''><meta http-equiv='content-type' content='text/html; charset=UTF-8'>"
io = dummy_io(<<EOS)
HTTP/1.1 200 OK
Connection: close
Expand Down