From 340d15e4000e24414b3e3430b54e737834a0f406 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 11 Jan 2021 19:27:14 +0100 Subject: [PATCH] [Cache] fix possible collision when writing tmp file in filesystem adapter --- .../Cache/Traits/FilesystemCommonTrait.php | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php b/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php index 5509e21028..fe61f08c16 100644 --- a/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php +++ b/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php @@ -93,9 +93,20 @@ trait FilesystemCommonTrait set_error_handler(__CLASS__.'::throwError'); try { if (null === $this->tmp) { - $this->tmp = $this->directory.uniqid('', true); + $this->tmp = $this->directory.bin2hex(random_bytes(6)); } - file_put_contents($this->tmp, $data); + try { + $h = fopen($this->tmp, 'x'); + } catch (\ErrorException $e) { + if (false === strpos($e->getMessage(), 'File exists')) { + throw $e; + } + + $this->tmp = $this->directory.bin2hex(random_bytes(6)); + $h = fopen($this->tmp, 'x'); + } + fwrite($h, $data); + fclose($h); if (null !== $expiresAt) { touch($this->tmp, $expiresAt);