class Rack::Protection::PathTraversal

def cleanup(path)

def cleanup(path)
  encoding = path.encoding
  dot   = '.'.encode(encoding)
  slash = '/'.encode(encoding)
  backslash = '\\'.encode(encoding)
  parts     = []
  unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash).gsub(/%5c/i, backslash)
  unescaped = unescaped.gsub(backslash, slash)
  unescaped.split(slash).each do |part|
    next if part.empty? or part == dot
    part == '..' ? parts.pop : parts << part
  end
  cleaned = slash + parts.join(slash)
  cleaned << slash if parts.any? and unescaped =~ %r{/\.{0,2}$}
  cleaned
end