From 5bec1655c45b2e3408e28494d7549e4eccc3cabd Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Thu, 22 Aug 2019 17:36:25 -0700 Subject: [PATCH] Handle cookies when handling HTTP redirects in open_uri This approach will handle the Set-Cookie header during the redirect. To avoid redirect loops for arbitrary cookies and the same URI, it will not redirect to an URI more than once for the cookie/non-cookie cases. Fixes [Bug #11322] --- lib/open-uri.rb | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/open-uri.rb b/lib/open-uri.rb index d9517e4b9e..6d34d698c3 100644 --- a/lib/open-uri.rb +++ b/lib/open-uri.rb @@ -230,7 +230,7 @@ def OpenURI.open_loop(uri, options) # :nodoc: uri_set = {} buf = nil while true - redirect = catch(:open_uri_redirect) { + redirect, cookie = catch(:open_uri_redirect) { buf = Buffer.new uri.buffer_open(buf, find_proxy.call(uri), options) nil @@ -252,9 +252,13 @@ def OpenURI.open_loop(uri, options) # :nodoc: options = options.dup options.delete :http_basic_authentication end + if cookie + options = options.dup + options[:cookie] = cookie.split(';')[0] + end uri = redirect - raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s - uri_set[uri.to_s] = true + raise "HTTP redirection loop: #{uri}" if uri_set.include?([uri.to_s, !!cookie]) + uri_set[[uri.to_s, !!cookie]] = true else break end @@ -344,6 +348,9 @@ def OpenURI.open_http(buf, target, proxy, options) # :nodoc: resp = nil http.start { + if cookie = options[:cookie] + header['Cookie'] = cookie + end req = Net::HTTP::Get.new(request_uri, header) if options.include? :http_basic_authentication user, pass = options[:http_basic_authentication] @@ -382,7 +389,7 @@ def OpenURI.open_http(buf, target, proxy, options) # :nodoc: rescue URI::InvalidURIError raise OpenURI::HTTPError.new(io.status.join(' ') + ' (Invalid Location URI)', io) end - throw :open_uri_redirect, loc_uri + throw :open_uri_redirect, [loc_uri, resp['Set-Cookie']] else raise OpenURI::HTTPError.new(io.status.join(' '), io) end -- 2.22.0