Merge branch '8784-dir-listings'
[arvados.git] / services / api / config / initializers / fix_www_decode.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 module URI
6   if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.2')
7     # Rack uses the standard library method URI.decode_www_form_component to
8     # process parameters.  This method first validates the string with a
9     # regular expression, and then decodes it using another regular expression.
10     # Ruby 2.1 and earlier has a bug is in the validation; the regular
11     # expression that is used generates many backtracking points, which results
12     # in exponential memory growth when matching large strings.  The fix is to
13     # monkey-patch the version of the method from Ruby 2.2 which checks that
14     # the string is not invalid instead of checking it is valid.
15     def self.decode_www_form_component(str, enc=Encoding::UTF_8)
16       raise ArgumentError, "invalid %-encoding (#{str})" if /%(?!\h\h)/ =~ str
17       str.b.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
18     end
19   end
20 end