Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/Driver/Userland/ConnectionHandler/ConnectionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,11 @@ private function dispatchRequest($requestId)
$this->requests[$requestId]['stdin']
);

$response = $this->kernel->handleRequest($request);
try {
$response = $this->kernel->handleRequest($request);
} finally {
$request->cleanUploadedFiles();
}

if ($response instanceof ResponseInterface) {
$this->sendResponse($requestId, $response);
Expand Down
128 changes: 126 additions & 2 deletions src/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PHPFastCGI\FastCGIDaemon\Http;

use Symfony\Component\HttpFoundation\Request as HttpFoundationRequest;
use function Zend\Diactoros\createUploadedFile;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\ServerRequestFactory;

Expand All @@ -11,6 +12,21 @@
*/
class Request implements RequestInterface
{
/**
* @var int
*/
private static $bufferSize = 10485760; // 10 MB

/**
* @var string
*/
private static $uploadDir = null;

/**
* @var array
*/
private $uploadedFiles = [];

/**
* @var array
*/
Expand Down Expand Up @@ -48,6 +64,39 @@ public function getParams()
return $this->params;
}

/**
* Remove all uploaded files
*/
public function cleanUploadedFiles(): void
{
foreach ($this->uploadedFiles as $file) {
@unlink($file['tmp_name']);
}
}

/**
* Set a buffer size to read uploaded files
*/
public static function setBufferSize(int $size): void
{
static::$bufferSize = $size;
}

public static function getBufferSize(): int
{
return static::$bufferSize;
}

public static function setUploadDir(string $dir): void
{
static::$uploadDir = $dir;
}

public static function getUploadDir(): string
{
return static::$uploadDir ?: sys_get_temp_dir();
}

/**
* {@inheritdoc}
*/
Expand All @@ -73,6 +122,15 @@ public function getPost()
$requestMethod = $this->params['REQUEST_METHOD'];
$contentType = $this->params['CONTENT_TYPE'];

if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'multipart/form-data') === 0) {
if (preg_match('/boundary=(?P<quote>[\'"]?)(.*)(?P=quote)/', $contentType, $matches)) {
list($postData, $this->uploadedFiles) = $this->parseMultipartFormData($this->stdin, $matches[2]);
parse_str($postData, $post);

return $post;
}
}

if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'application/x-www-form-urlencoded') === 0) {
$postData = stream_get_contents($this->stdin);
rewind($this->stdin);
Expand All @@ -84,6 +142,67 @@ public function getPost()
return $post ?: [];
}

private function parseMultipartFormData($stream, $boundary) {
$post = "";
$files = [];
$fieldType = $fieldName = $filename = $mimeType = null;
$inHeader = $getContent = false;

while (!feof($stream)) {
$getContent = $fieldName && !$inHeader;
$buffer = stream_get_line($stream, static::$bufferSize, "\n" . ($getContent ? '--'.$boundary : ''));
$buffer = trim($buffer, "\r");

// Find the empty line between headers and body
if ($inHeader && strlen($buffer) == 0) {
$inHeader = false;

continue;
}

if ($getContent) {
if ($fieldType === 'data') {
$post .= (isset($post[0]) ? '&' : '') . $fieldName . "=" . urlencode($buffer);
} elseif ($fieldType === 'file' && $filename) {
$tmpPath = tempnam($this->getUploadDir(), 'fastcgi_upload');
$err = file_put_contents($tmpPath, $buffer);
$files[$fieldName] = [
'type' => $mimeType ?: 'application/octet-stream',
'name' => $filename,
'tmp_name' => $tmpPath,
'error' => ($err === false) ? true : 0,
'size' => filesize($tmpPath),
];
$filename = $mimeType = null;
}
$fieldName = $fieldType = null;

continue;
}

// Assert: We may be in the header, lets try to find 'Content-Disposition' and 'Content-Type'.
if (strpos($buffer, 'Content-Disposition') === 0) {
$inHeader = true;
if (preg_match('/name=\"([^\"]*)\"/', $buffer, $matches)) {
$fieldName = $matches[1];
}
if (preg_match('/filename=\"([^\"]*)\"/', $buffer, $matches)) {
$filename = $matches[1];
$fieldType = 'file';
} else {
$fieldType = 'data';
}
} elseif (strpos($buffer, 'Content-Type') === 0) {
$inHeader = true;
if (preg_match('/Content-Type: (.*)?/', $buffer, $matches)) {
$mimeType = trim($matches[1]);
}
}
}

return [$post, $files];
}

/**
* {@inheritdoc}
*/
Expand Down Expand Up @@ -129,7 +248,12 @@ public function getServerRequest()
$uri = ServerRequestFactory::marshalUriFromServer($server, $headers);
$method = ServerRequestFactory::get('REQUEST_METHOD', $server, 'GET');

$request = new ServerRequest($server, [], $uri, $method, $this->stdin, $headers);
$files = [];
foreach ($this->uploadedFiles as $file) {
$files[] = createUploadedFile($file);
}

$request = new ServerRequest($server, $files, $uri, $method, $this->stdin, $headers);

return $request
->withCookieParams($cookies)
Expand All @@ -150,6 +274,6 @@ public function getHttpFoundationRequest()
$post = $this->getPost();
$cookies = $this->getCookies();

return new HttpFoundationRequest($query, $post, [], $cookies, [], $this->params, $this->stdin);
return new HttpFoundationRequest($query, $post, [], $cookies, $this->uploadedFiles, $this->params, $this->stdin);
}
}
62 changes: 62 additions & 0 deletions test/Http/RequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,66 @@ public function testRequest()
$this->assertEquals($expectedCookies, $httpFoundationRequest->cookies->all());
$this->assertEquals($content, $httpFoundationRequest->getContent());
}

public function testMultipartContent()
{
$expectedPost = ['foo' => 'A normal stream', 'baz' => 'string'];

// Set up FastCGI params and content
$params = [
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_METHOD' => 'POST',
'content_type' => 'multipart/form-data; boundary="578de3b0e3c46.2334ba3"',
'REQUEST_URI' => '/my-page',
];

// Set up the FastCGI stdin data stream resource
$content = <<<HTTP
--578de3b0e3c46.2334ba3
Content-Disposition: form-data; name="foo"
Content-Length: 15

A normal stream
--578de3b0e3c46.2334ba3
Content-Disposition: form-data; name="bar"; filename="bar.png"
Content-Length: 71
Content-Type: image/png

?PNG

???
IHDR??? ??? ?????? ???? IDATxc???51?)?:??????IEND?B`?
--578de3b0e3c46.2334ba3
Content-Type: text/plain
Content-Disposition: form-data; name="baz"
Content-Length: 6

string
--578de3b0e3c46.2334ba3--
HTTP;

$stream = fopen('php://memory', 'r+');
fwrite($stream, $content);

// Create the request
$request = new Request($params, $stream);

// Check request object
$this->assertEquals($expectedPost, $request->getPost());
$this->assertEquals($stream, $request->getStdin());

// Check the PSR server request
rewind($stream);
$serverRequest = $request->getServerRequest();
$this->assertEquals($expectedPost, $serverRequest->getParsedBody());
$this->assertCount(1, $serverRequest->getUploadedFiles());
$this->assertEquals($content, $serverRequest->getBody()->__toString());

// Check the HttpFoundation request
rewind($stream);
$httpFoundationRequest = $request->getHttpFoundationRequest();
$this->assertEquals($expectedPost, $httpFoundationRequest->request->all());
$this->assertCount(1, $httpFoundationRequest->files->all());
$this->assertEquals($content, $httpFoundationRequest->getContent());
}
}