From 15bc4111c4c4e1af580b63c62e08decf2d5527d5 Mon Sep 17 00:00:00 2001 From: Stephen Sykes Date: Tue, 8 May 2018 22:12:16 +0300 Subject: [PATCH] Only escape location in redirect if needed. Fixes #103 --- lib/fastimage.rb | 13 ++++++++++++- test/test.rb | 6 ++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/fastimage.rb b/lib/fastimage.rb index aab7443..a17c69d 100644 --- a/lib/fastimage.rb +++ b/lib/fastimage.rb @@ -242,6 +242,17 @@ class FastImage fetch_using_http_from_parsed_uri end + # Some invalid locations need escaping + def escaped_location(location) + begin + URI(location) + rescue URI::InvalidURIError + URI.escape(location) + else + location + end + end + def fetch_using_http_from_parsed_uri http_header = {'Accept-Encoding' => 'identity'}.merge(@options[:http_header]) @@ -250,7 +261,7 @@ class FastImage if res.is_a?(Net::HTTPRedirection) && @redirect_count < 4 @redirect_count += 1 begin - @parsed_uri = URI.join(@parsed_uri, URI.escape(res['Location'])) + @parsed_uri = URI.join(@parsed_uri, escaped_location(res['Location'])) rescue URI::InvalidURIError else fetch_using_http_from_parsed_uri diff --git a/test/test.rb b/test/test.rb index 82ef087..30a5f2d 100644 --- a/test/test.rb +++ b/test/test.rb @@ -254,6 +254,12 @@ class FastImageTest < Test::Unit::TestCase assert_equal GoodFixtures[GoodFixtures.keys.first][1], FastImage.size(TestUrl, :raise_on_failure=>true) end + def test_should_handle_permanent_redirect_with_encoded_url + register_redirect(TestUrl, "/pho%20to.gne") + register_redirect("#{TestUrl}pho%20to.gne", "/" + GoodFixtures.keys.first) + assert_equal GoodFixtures[GoodFixtures.keys.first][1], FastImage.size(TestUrl, :raise_on_failure=>true) + end + def register_redirect(from, to) resp = Net::HTTPMovedPermanently.new(1.0, 302, "Moved") resp['Location'] = to