Streamer.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author szaimen <szaimen@e.mail.de>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC;
  30. use OC\Files\Filesystem;
  31. use OCP\Files\File;
  32. use OCP\Files\Folder;
  33. use OCP\Files\InvalidPathException;
  34. use OCP\Files\NotFoundException;
  35. use OCP\Files\NotPermittedException;
  36. use OCP\IRequest;
  37. use ownCloud\TarStreamer\TarStreamer;
  38. use Psr\Log\LoggerInterface;
  39. use ZipStreamer\ZipStreamer;
  40. class Streamer {
  41. // array of regexp. Matching user agents will get tar instead of zip
  42. private array $preferTarFor = [ '/macintosh|mac os x/i' ];
  43. // streamer instance
  44. private $streamerInstance;
  45. /**
  46. * Streamer constructor.
  47. *
  48. * @param IRequest $request
  49. * @param int|float $size The size of the files in bytes
  50. * @param int $numberOfFiles The number of files (and directories) that will
  51. * be included in the streamed file
  52. */
  53. public function __construct(IRequest $request, int|float $size, int $numberOfFiles) {
  54. /**
  55. * zip32 constraints for a basic (without compression, volumes nor
  56. * encryption) zip file according to the Zip specification:
  57. * - No file size is larger than 4 bytes (file size < 4294967296); see
  58. * 4.4.9 uncompressed size
  59. * - The size of all files plus their local headers is not larger than
  60. * 4 bytes; see 4.4.16 relative offset of local header and 4.4.24
  61. * offset of start of central directory with respect to the starting
  62. * disk number
  63. * - The total number of entries (files and directories) in the zip file
  64. * is not larger than 2 bytes (number of entries < 65536); see 4.4.22
  65. * total number of entries in the central dir
  66. * - The size of the central directory is not larger than 4 bytes; see
  67. * 4.4.23 size of the central directory
  68. *
  69. * Due to all that, zip32 is used if the size is below 4GB and there are
  70. * less than 65536 files; the margin between 4*1000^3 and 4*1024^3
  71. * should give enough room for the extra zip metadata. Technically, it
  72. * would still be possible to create an invalid zip32 file (for example,
  73. * a zip file from files smaller than 4GB with a central directory
  74. * larger than 4GiB), but it should not happen in the real world.
  75. *
  76. * We also have to check for a size above 0. As negative sizes could be
  77. * from not fully scanned external storage. And then things fall apart
  78. * if somebody tries to package to much.
  79. */
  80. if ($size > 0 && $size < 4 * 1000 * 1000 * 1000 && $numberOfFiles < 65536) {
  81. $this->streamerInstance = new ZipStreamer(['zip64' => false]);
  82. } elseif ($request->isUserAgent($this->preferTarFor)) {
  83. $this->streamerInstance = new TarStreamer();
  84. } else {
  85. $this->streamerInstance = new ZipStreamer(['zip64' => PHP_INT_SIZE !== 4]);
  86. }
  87. }
  88. /**
  89. * Send HTTP headers
  90. * @param string $name
  91. */
  92. public function sendHeaders($name) {
  93. header('X-Accel-Buffering: no');
  94. $extension = $this->streamerInstance instanceof ZipStreamer ? '.zip' : '.tar';
  95. $fullName = $name . $extension;
  96. $this->streamerInstance->sendHeaders($fullName);
  97. }
  98. /**
  99. * Stream directory recursively
  100. *
  101. * @throws NotFoundException
  102. * @throws NotPermittedException
  103. * @throws InvalidPathException
  104. */
  105. public function addDirRecursive(string $dir, string $internalDir = ''): void {
  106. $dirname = basename($dir);
  107. $rootDir = $internalDir . $dirname;
  108. if (!empty($rootDir)) {
  109. $this->streamerInstance->addEmptyDir($rootDir);
  110. }
  111. $internalDir .= $dirname . '/';
  112. // prevent absolute dirs
  113. $internalDir = ltrim($internalDir, '/');
  114. $userFolder = \OC::$server->getRootFolder()->get(Filesystem::getRoot());
  115. /** @var Folder $dirNode */
  116. $dirNode = $userFolder->get($dir);
  117. $files = $dirNode->getDirectoryListing();
  118. /** @var LoggerInterface $logger */
  119. $logger = \OC::$server->query(LoggerInterface::class);
  120. foreach ($files as $file) {
  121. if ($file instanceof File) {
  122. try {
  123. $fh = $file->fopen('r');
  124. if ($fh === false) {
  125. $logger->error('Unable to open file for stream: ' . print_r($file, true));
  126. continue;
  127. }
  128. } catch (NotPermittedException $e) {
  129. continue;
  130. }
  131. $this->addFileFromStream(
  132. $fh,
  133. $internalDir . $file->getName(),
  134. $file->getSize(),
  135. $file->getMTime()
  136. );
  137. fclose($fh);
  138. } elseif ($file instanceof Folder) {
  139. if ($file->isReadable()) {
  140. $this->addDirRecursive($dir . '/' . $file->getName(), $internalDir);
  141. }
  142. }
  143. }
  144. }
  145. /**
  146. * Add a file to the archive at the specified location and file name.
  147. *
  148. * @param resource $stream Stream to read data from
  149. * @param string $internalName Filepath and name to be used in the archive.
  150. * @param int|float $size Filesize
  151. * @param int|false $time File mtime as int, or false
  152. * @return bool $success
  153. */
  154. public function addFileFromStream($stream, string $internalName, int|float $size, $time): bool {
  155. $options = [];
  156. if ($time) {
  157. $options = [
  158. 'timestamp' => $time
  159. ];
  160. }
  161. if ($this->streamerInstance instanceof ZipStreamer) {
  162. return $this->streamerInstance->addFileFromStream($stream, $internalName, $options);
  163. } else {
  164. return $this->streamerInstance->addFileFromStream($stream, $internalName, $size, $options);
  165. }
  166. }
  167. /**
  168. * Add an empty directory entry to the archive.
  169. *
  170. * @param string $dirName Directory Path and name to be added to the archive.
  171. * @return bool $success
  172. */
  173. public function addEmptyDir($dirName) {
  174. return $this->streamerInstance->addEmptyDir($dirName);
  175. }
  176. /**
  177. * Close the archive.
  178. * A closed archive can no longer have new files added to it. After
  179. * closing, the file is completely written to the output stream.
  180. * @return bool $success
  181. */
  182. public function finalize() {
  183. return $this->streamerInstance->finalize();
  184. }
  185. }