Skip to content

Commit

Permalink
Make multipart reading more robust
Browse files Browse the repository at this point in the history
darcs-hash:20070228133335-4fc50-8d5508a19f04d3a907b1dcd70a8dfac3791ecad8.gz
  • Loading branch information
leahneukirchen committed Feb 28, 2007
1 parent 4fe5360 commit b064d53
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions lib/rack/utils.rb
Expand Up @@ -75,13 +75,14 @@ def capitalize(k)
k.to_s.downcase.gsub(/^.|[-_\s]./) { |x| x.upcase }
end
end

# Adapted from IOWA.
module Multipart
EOL = "\r\n"

def self.parse_multipart(env)
unless env['CONTENT_TYPE'] =~ %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n
unless env['CONTENT_TYPE'] =~
%r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n
nil
else
boundary = "--#{$1}"
Expand All @@ -99,28 +100,30 @@ def self.parse_multipart(env)
status = input.read(boundary_size)
raise EOFError, "bad content body" unless status == boundary + EOL

rx = /(?:#{EOL})?#{Regexp.quote boundary}(#{EOL}|--)/

loop {
head = nil
body = ''
filename = content_type = name = nil

until head && buf =~ /#{boundary}(?:#{EOL}|--)/ # /
until head && buf =~ rx
if !head && i = buf.index("\r\n\r\n")
head = buf.slice!(0, i+2) # First \r\n
buf.slice!(0, 2) # Second \r\n

filename = head[/Content-Disposition:.* filename="?([^\";]*)"?/ni, 1]
content_type = head[/Content-Type: (.*)\r\n/ni, 1]
name = head[/Content-Disposition:.* name="?([^\";]*)"?/ni, 1]

body = Tempfile.new("RackMultipart") if filename

next
end

# Save the read body part.
if head && (boundary.size+4 < buf.size)
body << buf.slice!(0, buf.size - (boundary.size+4))
if head && (boundary_size+4 < buf.size)
body << buf.slice!(0, buf.size - (boundary_size+4))
end

c = input.read(bufsize < content_length ? bufsize : content_length)
Expand All @@ -130,10 +133,10 @@ def self.parse_multipart(env)
end

# Save the rest.
if i = buf.index(/(?:#{EOL})?#{boundary}(#{EOL}|--)/n)
if i = buf.index(rx)
body << buf.slice!(0, i)
buf.slice!(0, boundary_size+2)

content_length = -1 if $1 == "--"
end

Expand Down

0 comments on commit b064d53

Please sign in to comment.