Microsoft.AspNetCore.WebUtilities.BufferedReadStream - incorrect implementation of Position property's setter #60416
Labels
area-networking
Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions
Milestone
Is there an existing issue for this?
Describe the bug
Hi. By trying to use Microsoft.AspNetCore.WebUtilities.MultipartReader in a way that is directly using the section streams outside the initial reading loop (made through ReadNextSectionAsync), I've come to at least one case (when dealing with more than two section streams) where the conclusion is that the Position property of BufferedReadStream has an incorrect implementation when trying to position inside the internal buffer. I guess it's a pretty invalidating bug, making the whole MultipartReader support unstable / unpredictible / unusable.
To be more exact, these two lines are incorrect, in my opinion:
aspnetcore/src/Http/WebUtilities/src/BufferedReadStream.cs
Lines 110 to 112 in ec389c7
Explaination
It should advance in the internal buffer not with the offset between old position and new position (i.e. backward innerOffset), but until that offset / distance, so in the end the new Position will reflect the desired input value when getting the property. That means we should advance _bufferCount (number of bytes left for reading until old position) minus innerOffset (previously mentioned offset).
Expected Behavior
It should have been replaced by these lines:
_bufferOffset += _bufferCount - innerOffset;
_bufferCount = innerOffset;
Steps To Reproduce
Try to use a Microsoft.AspNetCore.WebUtilities.MultipartReader in a request having at least two uploaded form data files and store the section streams for later reading (not some copies of them), it will be impossible to correctly read the second stream because the functionality has unpredictible behavior (see description of the problem).
Exceptions (if any)
In some scenarios it throws: IOException("Unexpected end of Stream, the content may have already been read by another component. ")
.NET Version
No response
Anything else?
It would be nice if this can be fixed in order to not be forced to make copies of large uploaded files. I can contribute with the fix for it (described above), if this would be the easiest and fastest way to push the fix, after checking the validity of the issue. Thank you.
The text was updated successfully, but these errors were encountered: