You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MultipartRequestParser.php 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2021, Louis Chemineau <louis@chmn.me>
  4. *
  5. * @author Louis Chemineau <louis@chmn.me>
  6. *
  7. * @license AGPL-3.0
  8. *
  9. * This code is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License, version 3,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License, version 3,
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>
  20. *
  21. */
  22. namespace OCA\DAV\BulkUpload;
  23. use OCP\AppFramework\Http;
  24. use Sabre\DAV\Exception;
  25. use Sabre\DAV\Exception\BadRequest;
  26. use Sabre\DAV\Exception\LengthRequired;
  27. use Sabre\HTTP\RequestInterface;
  28. class MultipartRequestParser {
  29. /** @var resource */
  30. private $stream;
  31. /** @var string */
  32. private $boundary = "";
  33. /** @var string */
  34. private $lastBoundary = "";
  35. /**
  36. * @throws BadRequest
  37. */
  38. public function __construct(RequestInterface $request) {
  39. $stream = $request->getBody();
  40. $contentType = $request->getHeader('Content-Type');
  41. if (!is_resource($stream)) {
  42. throw new BadRequest('Body should be of type resource');
  43. }
  44. if ($contentType === null) {
  45. throw new BadRequest("Content-Type can not be null");
  46. }
  47. $this->stream = $stream;
  48. $boundary = $this->parseBoundaryFromHeaders($contentType);
  49. $this->boundary = '--'.$boundary."\r\n";
  50. $this->lastBoundary = '--'.$boundary."--\r\n";
  51. }
  52. /**
  53. * Parse the boundary from the Content-Type header.
  54. * Example: Content-Type: "multipart/related; boundary=boundary_bf38b9b4b10a303a28ed075624db3978"
  55. *
  56. * @throws BadRequest
  57. */
  58. private function parseBoundaryFromHeaders(string $contentType): string {
  59. try {
  60. [$mimeType, $boundary] = explode(';', $contentType);
  61. [$boundaryKey, $boundaryValue] = explode('=', $boundary);
  62. } catch (\Exception $e) {
  63. throw new BadRequest("Error while parsing boundary in Content-Type header.", Http::STATUS_BAD_REQUEST, $e);
  64. }
  65. $boundaryValue = trim($boundaryValue);
  66. // Remove potential quotes around boundary value.
  67. if (substr($boundaryValue, 0, 1) == '"' && substr($boundaryValue, -1) == '"') {
  68. $boundaryValue = substr($boundaryValue, 1, -1);
  69. }
  70. if (trim($mimeType) !== 'multipart/related') {
  71. throw new BadRequest('Content-Type must be multipart/related');
  72. }
  73. if (trim($boundaryKey) !== 'boundary') {
  74. throw new BadRequest('Boundary is invalid');
  75. }
  76. return $boundaryValue;
  77. }
  78. /**
  79. * Check whether the stream's cursor is sitting right before the provided string.
  80. *
  81. * @throws Exception
  82. */
  83. private function isAt(string $expectedContent): bool {
  84. $expectedContentLength = strlen($expectedContent);
  85. $content = fread($this->stream, $expectedContentLength);
  86. if ($content === false) {
  87. throw new Exception('An error occurred while checking content');
  88. }
  89. $seekBackResult = fseek($this->stream, -$expectedContentLength, SEEK_CUR);
  90. if ($seekBackResult === -1) {
  91. throw new Exception("Unknown error while seeking content", Http::STATUS_INTERNAL_SERVER_ERROR);
  92. }
  93. return $expectedContent === $content;
  94. }
  95. /**
  96. * Check whether the stream's cursor is sitting right before the boundary.
  97. */
  98. private function isAtBoundary(): bool {
  99. return $this->isAt($this->boundary);
  100. }
  101. /**
  102. * Check whether the stream's cursor is sitting right before the last boundary.
  103. */
  104. public function isAtLastBoundary(): bool {
  105. return $this->isAt($this->lastBoundary);
  106. }
  107. /**
  108. * Parse and return the next part of the multipart headers.
  109. *
  110. * Example:
  111. * --boundary_azertyuiop
  112. * Header1: value
  113. * Header2: value
  114. *
  115. * Content of
  116. * the part
  117. *
  118. */
  119. public function parseNextPart(): array {
  120. $this->readBoundary();
  121. $headers = $this->readPartHeaders();
  122. $content = $this->readPartContent($headers["content-length"], $headers["x-file-md5"]);
  123. return [$headers, $content];
  124. }
  125. /**
  126. * Read the boundary and check its content.
  127. *
  128. * @throws BadRequest
  129. */
  130. private function readBoundary(): string {
  131. if (!$this->isAtBoundary()) {
  132. throw new BadRequest("Boundary not found where it should be.");
  133. }
  134. return fread($this->stream, strlen($this->boundary));
  135. }
  136. /**
  137. * Return the headers of a part of the multipart body.
  138. *
  139. * @throws Exception
  140. * @throws BadRequest
  141. * @throws LengthRequired
  142. */
  143. private function readPartHeaders(): array {
  144. $headers = [];
  145. while (($line = fgets($this->stream)) !== "\r\n") {
  146. if ($line === false) {
  147. throw new Exception('An error occurred while reading headers of a part');
  148. }
  149. try {
  150. [$key, $value] = explode(':', $line, 2);
  151. $headers[strtolower(trim($key))] = trim($value);
  152. } catch (\Exception $e) {
  153. throw new BadRequest('An error occurred while parsing headers of a part', Http::STATUS_BAD_REQUEST, $e);
  154. }
  155. }
  156. if (!isset($headers["content-length"])) {
  157. throw new LengthRequired("The Content-Length header must not be null.");
  158. }
  159. if (!isset($headers["x-file-md5"])) {
  160. throw new BadRequest("The X-File-MD5 header must not be null.");
  161. }
  162. return $headers;
  163. }
  164. /**
  165. * Return the content of a part of the multipart body.
  166. *
  167. * @throws Exception
  168. * @throws BadRequest
  169. */
  170. private function readPartContent(int $length, string $md5): string {
  171. $computedMd5 = $this->computeMd5Hash($length);
  172. if ($md5 !== $computedMd5) {
  173. throw new BadRequest("Computed md5 hash is incorrect.");
  174. }
  175. if ($length === 0) {
  176. $content = '';
  177. } else {
  178. $content = stream_get_line($this->stream, $length);
  179. }
  180. if ($content === false) {
  181. throw new Exception("Fail to read part's content.");
  182. }
  183. if ($length !== 0 && feof($this->stream)) {
  184. throw new Exception("Unexpected EOF while reading stream.");
  185. }
  186. // Read '\r\n'.
  187. stream_get_contents($this->stream, 2);
  188. return $content;
  189. }
  190. /**
  191. * Compute the MD5 hash of the next x bytes.
  192. */
  193. private function computeMd5Hash(int $length): string {
  194. $context = hash_init('md5');
  195. hash_update_stream($context, $this->stream, $length);
  196. fseek($this->stream, -$length, SEEK_CUR);
  197. return hash_final($context);
  198. }
  199. }