Skip to content

Commit

Permalink
Immediately unlink temporary files (#2613)
Browse files Browse the repository at this point in the history
Puma has a limit (`Puma::Const::MAX_BODY` - around 110 KiB) over which
it will write request bodies to disk for handing off to the
application. When it does this, the request body can be left on disk
if the Puma process receives SIGKILL. Consider an extremely minimal
`config.ru`:

    run(proc { [204, {}, []] })

If we then:

1. Start `puma`, noting the process ID.
2. Start a slow file transfer, using `curl --limit-rate 100k` (for
   example) and `-T $PATH_TO_LARGE_FILE`.
3. Watch `$TMPDIR/puma*`.

We will see Puma start to write this temporary file. If we then send
SIGKILL to Puma, the file won't be cleaned up. With this patch, it
will - at least on POSIX systems. On Windows it may still be available.

This is suggested in the Ruby Tempfile documentation, and even uses this
specific example:
https://ruby-doc.org/stdlib-2.7.2/libdoc/tempfile/rdoc/Tempfile.html#class-Tempfile-label-Unlink+after+creation

> On POSIX systems, it's possible to unlink a file right after creating
> it, and before closing it. This removes the filesystem entry without
> closing the file handle, so it ensures that only the processes that
> already had the file handle open can access the file’s contents. It's
> strongly recommended that you do this if you do not want any other
> processes to be able to read from or write to the Tempfile, and you do
> not need to know the Tempfile's filename either.
>
> For example, a practical use case for unlink-after-creation would be
> this: you need a large byte buffer that's too large to comfortably fit
> in RAM, e.g. when you're writing a web server and you want to buffer
> the client's file upload data.
  • Loading branch information
smcgivern committed Apr 27, 2021
1 parent 01ffec5 commit e870ab6
Showing 1 changed file with 2 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/puma/client.rb
Expand Up @@ -295,6 +295,7 @@ def setup_body

if remain > MAX_BODY
@body = Tempfile.new(Const::PUMA_TMP_BASE)
@body.unlink
@body.binmode
@tempfile = @body
else
Expand Down Expand Up @@ -386,6 +387,7 @@ def setup_chunked_body(body)
@prev_chunk = ""

@body = Tempfile.new(Const::PUMA_TMP_BASE)
@body.unlink
@body.binmode
@tempfile = @body
@chunked_content_length = 0
Expand Down

0 comments on commit e870ab6

Please sign in to comment.