From a9c761dc2636d2645e05c8e1e6741917fe408c3f Mon Sep 17 00:00:00 2001 From: Sean McGivern <27fv8yygye@snkmail.com> Date: Tue, 27 Apr 2021 15:35:42 +0100 Subject: [PATCH] Immediately unlink temporary files (#2613) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- lib/puma/client.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/puma/client.rb b/lib/puma/client.rb index 690af4503f..b6895bbef3 100644 --- a/lib/puma/client.rb +++ b/lib/puma/client.rb @@ -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 @@ -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