Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Implementation of XSendFile for nginx #8

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
5 changes: 3 additions & 2 deletions config/module.config.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
),
'service_manager' => array(
'factories' => array(
'HumusStreamResponseSender\StreamResponseSender' => 'HumusStreamResponseSender\StreamResponseSenderFactory'
'HumusStreamResponseSender\XSendFileStreamResponseSender'
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please put this in factory.

=> 'HumusStreamResponseSender\StreamResponseSenderFactory'
)
)
);
);
23 changes: 19 additions & 4 deletions src/HumusStreamResponseSender/Controller/Plugin/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
*/
class Stream extends AbstractPlugin
{

/**
* Returns a stream response for a binary file download
*
Expand All @@ -47,12 +46,12 @@ class Stream extends AbstractPlugin
*
* @param string $filename
* @return StreamResponse
* @throws Exception\RuntimeException
* @throws Exception\InvalidArgumentException
*/
public function binaryFile($filename)
{
if (!file_exists($filename) || !is_readable($filename)) {
throw new Exception\RuntimeException(
throw new Exception\InvalidArgumentException(
'Invalid filename given; not readable or does not exist'
);
}
Expand All @@ -62,7 +61,6 @@ public function binaryFile($filename)

$response = new StreamResponse();
$response->setStream($resource);
$response->setStatusCode(206);

$response->setStreamName($basename);
$response->setContentLength(filesize($filename));
Expand All @@ -77,4 +75,21 @@ public function binaryFile($filename)
$response->setHeaders($headers);
return $response;
}

public function xSendFile($filename)
{
$response = new StreamResponse();

$response->setStreamName('X-SendFile');
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

streamName = basename($filename);

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

method called setStreamName will be used to store filename in XSendFileStreamResponseSender.
basename() is not a good idea because $filename will be used as is in XSendFileStreamResponseSender
f.e.
nginx Header (location /protected could be opted in nginx vhost)
X-Accel-Redirect: /protected/path/to/file/which/will/be/downloaded.tar.gz
real path matched to the location /protected is /var/www/download
file could be downloaded from /var/www/download/path/to/file/which/will/be/downloaded.tar.gz

with basename() not existent file /var/www/download/downloaded.tar.gz

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, so no basename here.
You can however have several paths in your nginx settings, e.g.

path1: /protected/
path2: /public/
path3: /usercontent/

use default: path1

and filename, e.g.

  1. /public/file.tar <- use path2, valid
  2. file.tar <- use path1 by default (no "/" as first char of string), valid
  3. some/file.tar <- path1 by default (no "/" as first char of string), use subdirectory, too, valid
  4. /some/invalid/file <- invalid root path used, invalid, exception

As we can't know what nginx maps for the path, we can not do any file_exists checks on them, and that's okay.


$headers = new Headers();
$headers->addHeaders(
array(
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
'Content-Type' => 'application/octet-stream',
)
);
$response->setHeaders($headers);
return $response;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/

namespace HumusStreamResponseSender\Exception;

/**
* @category Humus
* @package HumusStreamResponseSender
* @license MIT
*/
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
2 changes: 1 addition & 1 deletion src/HumusStreamResponseSender/Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public function onBootstrap(EventInterface $e)
{
$app = $e->getTarget();
$serviceManager = $app->getServiceManager();
$streamResponseSender = $serviceManager->get(__NAMESPACE__ . '\StreamResponseSender');
$streamResponseSender = $serviceManager->get(__NAMESPACE__ . '\XSendFileStreamResponseSender');
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

again - use the factory, see above.

$sharedEventManager = $app->getEventManager()->getSharedManager();
/* @var $sharedEventManager SharedEventManager */
$sharedEventManager->attach(
Expand Down
100 changes: 72 additions & 28 deletions src/HumusStreamResponseSender/StreamResponseSender.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,17 @@ class StreamResponseSender extends SimpleStreamResponseSender
/**
* @var int
*/
private $range;
private $rangeStart;

/**
* @param array|Traversable|null|Options $options
* @var int
*/
private $rangeEnd;

/**
* @param null|Options $options
*/
public function __construct($options = null)
public function __construct(Options $options = null)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please revert this change, this is made special this way.
See options classes in ZF2.

{
if (null !== $options) {
$this->setOptions($options);
Expand All @@ -63,13 +68,11 @@ public function __construct($options = null)
/**
* Set options
*
* @param array|Traversable|Options $options
* @param Options $options
* @return $this
*/
public function setOptions($options)
public function setOptions(Options $options)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please revert this change, this is made special this way.
See options classes in ZF2.

{
if (!$options instanceof Options) {
$options = new Options($options);
}
$this->options = $options;
return $this;
}
Expand All @@ -81,9 +84,6 @@ public function setOptions($options)
*/
public function getOptions()
{
if (!$this->options instanceof Options) {
$this->options = new Options();
}
return $this->options;
}

Expand Down Expand Up @@ -123,31 +123,61 @@ public function sendHeaders(SendResponseEvent $event)
$responseHeaders->addHeaderLine('Content-Transfer-Encoding', 'binary');
}

$responseHeaders->addHeaderLine('Accept-Ranges', 'bytes');

$size = $response->getContentLength();
$size2 = $size - 1;

$requestHeaders = $this->getRequest()->getHeaders();

$length = $size;
$range = '0-';
$this->range = 0;
$this->rangeStart = 0;
$this->rangeEnd = null;

if ($requestHeaders->has('Range')) {
$enableDownloadResume = $this->getOptions()->getEnableDownloadResume();
$requestHeaders = $this->getRequest()->getHeaders();

if ($enableDownloadResume && $requestHeaders->has('Range')) {
list($a, $range) = explode('=', $requestHeaders->get('Range')->getFieldValue());
str_replace($range, "-", $range);
if (substr($range, -1) == '-') {
// range: 3442-
$range = substr($range, 0, -1);
if (!is_numeric($range) || $range > $size2) {
// 416 (Requested range not satisfiable)
$response->setStatusCode(416);
$event->setContentSent();
return $this;
}
$this->rangeStart = $range;
$length = $size - $range;
} else {
$ranges = explode('-', $range, 2);
$rangeStart = $ranges[0];
$rangeEnd = $ranges[1];
if (!is_numeric($rangeStart)
|| !is_numeric($rangeEnd)
|| ($rangeStart >= $rangeEnd)
|| $rangeEnd > $size2
) {
// 416 (Requested range not satisfiable)
$response->setStatusCode(416);
$event->setContentSent();
return $this;
}
$this->rangeStart = $rangeStart;
$this->rangeEnd = $rangeEnd;
$length = $rangeEnd - $rangeStart;
$size2 = $rangeEnd;
}
$response->setStatusCode(206); // 206 (Partial Content)
$this->range = (int) $range;
}

$responseHeaders->addHeaderLine('Content-Length: ' . $length);

if ($enableDownloadResume) {
$responseHeaders->addHeaders(
array(
'Content-Length: ' . $length,
'Content-Range: bytes ' . $range . $size2 . '/' . $size,
'Accept-Ranges: bytes',
'Content-Range: bytes ' . $this->rangeStart . $size2 . '/' . $size,
)
);
}

parent::sendHeaders($event);
}
Expand Down Expand Up @@ -179,23 +209,37 @@ public function sendStream(SendResponseEvent $event)
}

set_time_limit(0);
$rangeStart = $this->rangeStart;
if (null !== $this->rangeEnd) {
$rangeEnd = $this->rangeEnd;
$length = $rangeEnd-$rangeStart;
} else {
$length = $response->getContentLength();
}

fseek($stream, $this->range);

fseek($stream, $rangeStart);
$chunkSize = $options->getChunkSize();

if ($chunkSize > $length) {
$chunkSize = $length;
}
$sizeSent = 0;

while (!feof($stream) && (connection_status()==0)) {

echo fread($stream, $chunkSize);
flush();
ob_flush();

$sizeSent += $chunkSize;

if ($sizeSent == $length) {
$event->setContentSent();
return $this;
}

if ($enableSpeedLimit) {
sleep(1);
}
}

$event->setContentSent();
return $this;
}
}
10 changes: 9 additions & 1 deletion src/HumusStreamResponseSender/StreamResponseSenderFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ public function createService(ServiceLocatorInterface $serviceLocator)
} else {
$options = null;
}
$streamResponseSender = new StreamResponseSender($options);

if ($options['is_x_send_file']) {
$options = new XSendFileOptions($options['x_send_file']);
$streamResponseSender = new XSendFileStreamResponseSender($options);
} else {
$options = new Options($options['default']);
$streamResponseSender = new StreamResponseSender($options);
}

$streamResponseSender->setRequest($serviceLocator->get('Request'));
return $streamResponseSender;
}
Expand Down
103 changes: 103 additions & 0 deletions src/HumusStreamResponseSender/XSendFileOptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/

namespace HumusStreamResponseSender;

use Traversable;
use Zend\Stdlib\AbstractOptions;
use HumusStreamResponseSender\XSendFileServerOptions;

/**
* @category Humus
* @package HumusStreamResponseSender
* @license MIT
*/
class XSendFileOptions extends AbstractOptions
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use the other options class for this. You can use seperated interfaces.

{
/**
* @var string
*/
protected $server;

/**
* @var string
*/
protected $internalLocation;

protected $queryParameter;

/**
* @var array
*/
protected $serverOptions;

/**
* @param $serverOptions
* @return $this
*/
public function setServerOptions($serverOptions)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't use array here, specify all server options instead, e.g.
server_port, server_host, server_whatever, ...

{
$this->serverOptions = $serverOptions;
return $this;
}

/**
* @return array
*/
public function getServerOptions()
{
return $this->serverOptions;
}

/**
* @param mixed $queryParameter
* @return $this
*/
public function setQueryParameter($queryParameter)
{
$this->queryParameter = $queryParameter;
return $this;
}

/**
* @return mixed
*/
public function getQueryParameter()
{
return $this->queryParameter;
}

/**
* @param array $server
*
* @return array
*/
public function setServer($server)
{
$this->server = $server;
return $server;
}

/**
* @return array
*/
public function getServer()
{
return $this->server;
}
}
Loading