| 1 |
<?php |
| 2 |
|
| 3 |
namespace Shellbox\Multipart; |
| 4 |
|
| 5 |
use Psr\Http\Message\StreamInterface; |
| 6 |
use Shellbox\Shellbox; |
| 7 |
|
| 8 |
/** |
| 9 |
* A streaming parser for multipart content |
| 10 |
* |
| 11 |
* Typical usage: |
| 12 |
* $reader = new MultipartReader( $stream, $boundary ); |
| 13 |
* $reader->readPrologue(); |
| 14 |
* while ( $headers = $reader->readPartHeaders() ) { |
| 15 |
* $contents = $reader->readPartAsString(); |
| 16 |
* } |
| 17 |
* $reader->readEpilogue(); |
| 18 |
*/ |
| 19 |
class MultipartReader { |
| 20 |
/** @var StreamInterface */ |
| 21 |
private $stream; |
| 22 |
/** @var string */ |
| 23 |
private $boundary; |
| 24 |
/** @var string */ |
| 25 |
private $startBoundary; |
| 26 |
/** @var string */ |
| 27 |
private $encapsulationBoundary; |
| 28 |
/** @var string */ |
| 29 |
private $closingBoundary; |
| 30 |
/** @var string */ |
| 31 |
private $buffer; |
| 32 |
/** @var \HashContext|null */ |
| 33 |
private $hashContext; |
| 34 |
/** @var string|null */ |
| 35 |
private $hash; |
| 36 |
/** |
| 37 |
* @var bool True when the body is complete and it is time to read the |
| 38 |
* headers of the next part |
| 39 |
*/ |
| 40 |
private $atPartEnd = false; |
| 41 |
/** @var bool True when we are reading the epilogue */ |
| 42 |
private $inEpilogue = false; |
| 43 |
/** @var bool True when we are at the start of the stream */ |
| 44 |
private $atStreamStart = true; |
| 45 |
/** @var bool True when EOF has been reached */ |
| 46 |
private $atStreamEnd = false; |
| 47 |
|
| 48 |
/** |
| 49 |
* @var int The number of bytes available in the buffer below which the |
| 50 |
* buffer is refilled. |
| 51 |
*/ |
| 52 |
private const MIN_BUFFER_SIZE = 16384; |
| 53 |
|
| 54 |
/** @var int The maximum number of bytes withdrawn from the buffer each time */ |
| 55 |
public const CHUNK_SIZE = 8192; |
| 56 |
|
| 57 |
/** |
| 58 |
* @param StreamInterface $stream |
| 59 |
* @param string $boundary |
| 60 |
* @param string|false $hmacKey |
| 61 |
*/ |
| 62 |
public function __construct( StreamInterface $stream, string $boundary, $hmacKey = false ) { |
| 63 |
$this->stream = $stream; |
| 64 |
$this->boundary = $boundary; |
| 65 |
$this->startBoundary = "--$boundary\r\n"; |
| 66 |
$this->encapsulationBoundary = "\r\n--$boundary\r\n"; |
| 67 |
$this->closingBoundary = "\r\n--$boundary--\r\n"; |
| 68 |
$this->buffer = ''; |
| 69 |
if ( $hmacKey !== false ) { |
| 70 |
$this->hashContext = hash_init( 'sha256', HASH_HMAC, $hmacKey ); |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* This must be called first on a new multipart stream, to discard any text |
| 76 |
* before the first boundary. |
| 77 |
* |
| 78 |
* @return string |
| 79 |
*/ |
| 80 |
public function readPreamble() { |
| 81 |
return $this->readPartAsString(); |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* Call this after the last part to read the epilogue, which runs from the |
| 86 |
* closing boundary to the end of the stream. |
| 87 |
*/ |
| 88 |
public function readEpilogue() { |
| 89 |
do { |
| 90 |
$this->buffer = ''; |
| 91 |
$this->refillBuffer(); |
| 92 |
// @phan-suppress-next-line PhanSuspiciousValueComparison |
| 93 |
} while ( $this->buffer !== '' ); |
| 94 |
$this->atStreamEnd = true; |
| 95 |
} |
| 96 |
|
| 97 |
/** |
| 98 |
* Read the part headers. |
| 99 |
* |
| 100 |
* The Content-Disposition header is decoded, and its value is an |
| 101 |
* associative array representing the header's parameters. Other headers |
| 102 |
* are returned as strings. |
| 103 |
* |
| 104 |
* The header names are converted to lower case. |
| 105 |
* |
| 106 |
* Following the HTTP convention, we don't support line continuation. |
| 107 |
* The writer we use (MultipartStream) doesn't use line continuation, so |
| 108 |
* this lack of compliance should be harmless. |
| 109 |
* |
| 110 |
* After reading the headers, the caller should call one of readPartAsString(), |
| 111 |
* copyPartToStream() or readPartAsJson(). |
| 112 |
* |
| 113 |
* @return array|bool Decoded headers, or false if the closing boundary was reached. |
| 114 |
* @throws MultipartError |
| 115 |
*/ |
| 116 |
public function readPartHeaders() { |
| 117 |
if ( $this->inEpilogue ) { |
| 118 |
return false; |
| 119 |
} |
| 120 |
$headers = []; |
| 121 |
while ( true ) { |
| 122 |
$line = $this->readLine(); |
| 123 |
if ( $line === '' ) { |
| 124 |
break; |
| 125 |
} |
| 126 |
$lineParts = explode( ':', $line, 2 ); |
| 127 |
if ( count( $lineParts ) !== 2 ) { |
| 128 |
$this->error( 'invalid part header' ); |
| 129 |
} |
| 130 |
if ( preg_match( '/^\s+/', $lineParts[0] ) ) { |
| 131 |
$this->error( 'line continuation is not supported' ); |
| 132 |
} |
| 133 |
$name = strtolower( $lineParts[0] ); |
| 134 |
$value = trim( $lineParts[1] ); |
| 135 |
if ( $name === 'content-disposition' ) { |
| 136 |
$structuredValue = []; |
| 137 |
$headerParts = explode( ';', $value, 2 ); |
| 138 |
$structuredValue['type'] = trim( $headerParts[0] ); |
| 139 |
if ( count( $headerParts ) > 1 ) { |
| 140 |
$structuredValue += MultipartUtils::decodeParameters( $headerParts[1] ); |
| 141 |
} |
| 142 |
$headers[$name] = $structuredValue; |
| 143 |
} else { |
| 144 |
$headers[$name] = $value; |
| 145 |
} |
| 146 |
} |
| 147 |
return $headers; |
| 148 |
} |
| 149 |
|
| 150 |
/** |
| 151 |
* Read a part to a string buffer. |
| 152 |
* |
| 153 |
* @return string |
| 154 |
*/ |
| 155 |
public function readPartAsString() { |
| 156 |
$result = ''; |
| 157 |
while ( !$this->atPartEnd ) { |
| 158 |
$chunk = $this->readChunk(); |
| 159 |
$result .= $chunk; |
| 160 |
} |
| 161 |
$this->nextPart(); |
| 162 |
return $result; |
| 163 |
} |
| 164 |
|
| 165 |
/** |
| 166 |
* Copy a part to the specified stream, which is open for writing. |
| 167 |
* |
| 168 |
* @param StreamInterface $outputStream |
| 169 |
*/ |
| 170 |
public function copyPartToStream( StreamInterface $outputStream ) { |
| 171 |
while ( !$this->atPartEnd ) { |
| 172 |
$chunk = $this->readChunk(); |
| 173 |
if ( strlen( $chunk ) ) { |
| 174 |
$outputStream->write( $chunk ); |
| 175 |
} |
| 176 |
} |
| 177 |
$this->nextPart(); |
| 178 |
} |
| 179 |
|
| 180 |
/** |
| 181 |
* Read a part to a string and decode the JSON found within. |
| 182 |
* |
| 183 |
* @param array $headers |
| 184 |
* @return mixed |
| 185 |
* @throws MultipartError |
| 186 |
*/ |
| 187 |
public function readPartAsJson( $headers ) { |
| 188 |
if ( ( $headers['content-type'] ?? '' ) !== 'application/json' ) { |
| 189 |
$this->error( 'part must be application/json' ); |
| 190 |
} |
| 191 |
$body = $this->readPartAsString(); |
| 192 |
return Shellbox::jsonDecode( $body ); |
| 193 |
} |
| 194 |
|
| 195 |
/** |
| 196 |
* Get the HMAC of all the content in the stream. This must be called after |
| 197 |
* the reader has reached the end of the input stream. |
| 198 |
* |
| 199 |
* @return string |
| 200 |
* @throws MultipartError |
| 201 |
*/ |
| 202 |
public function getHash() { |
| 203 |
if ( $this->hash === null ) { |
| 204 |
if ( !$this->hashContext ) { |
| 205 |
$this->error( 'cannot provide HMAC hash without key' ); |
| 206 |
} |
| 207 |
if ( !$this->atStreamEnd ) { |
| 208 |
// Allowing this would cause an error if another read is attempted |
| 209 |
$this->error( 'cannot finalise HMAC before the end of the stream' ); |
| 210 |
} |
| 211 |
$this->hash = hash_final( $this->hashContext ); |
| 212 |
} |
| 213 |
return $this->hash; |
| 214 |
} |
| 215 |
|
| 216 |
/** |
| 217 |
* Try to top up the buffer so that it has at least MIN_BUFFER_SIZE bytes. |
| 218 |
*/ |
| 219 |
private function refillBuffer() { |
| 220 |
if ( strlen( $this->buffer ) < self::MIN_BUFFER_SIZE && !$this->stream->eof() ) { |
| 221 |
$newBuffer = $this->stream->read( self::MIN_BUFFER_SIZE ); |
| 222 |
if ( $this->hashContext ) { |
| 223 |
hash_update( $this->hashContext, $newBuffer ); |
| 224 |
} |
| 225 |
$this->buffer .= $newBuffer; |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
/** |
| 230 |
* Read some bytes from the input stream, stopping if a boundary is reached. |
| 231 |
* Care must be taken in case a boundary straddles a read operation. We |
| 232 |
* refill the buffer with MIN_BUFFER_SIZE bytes, and check for a boundary |
| 233 |
* anywhere within that buffer, but we only withdraw CHUNK_SIZE bytes from |
| 234 |
* the buffer. The assumption is that as long as the boundary is shorter than |
| 235 |
* MIN_BUFFER_SIZE - CHUNK_SIZE, we will never split a boundary across a chunk |
| 236 |
* boundary. |
| 237 |
* |
| 238 |
* If a boundary is found, it is consumed, so that we are ready to read the |
| 239 |
* headers of the next part. atPartEnd is set to terminate the loop in the |
| 240 |
* caller. |
| 241 |
* |
| 242 |
* @return string |
| 243 |
*/ |
| 244 |
private function readChunk() { |
| 245 |
$this->refillBuffer(); |
| 246 |
|
| 247 |
if ( $this->buffer === '' ) { |
| 248 |
throw new MultipartError( 'unexpectedly reached the end of the ' . |
| 249 |
'stream while inside a part' ); |
| 250 |
} |
| 251 |
|
| 252 |
// Identify the first boundary |
| 253 |
$boundaries = [ |
| 254 |
'encapsulation' => $this->encapsulationBoundary, |
| 255 |
'closing' => $this->closingBoundary |
| 256 |
]; |
| 257 |
// An encapsulation boundary must be at the start of a line, which may |
| 258 |
// be either after a CRLF, or at the start of the stream. |
| 259 |
if ( $this->atStreamStart ) { |
| 260 |
$boundaries['start'] = $this->startBoundary; |
| 261 |
$this->atStreamStart = false; |
| 262 |
} |
| 263 |
$foundBoundaries = []; |
| 264 |
foreach ( $boundaries as $type => $boundary ) { |
| 265 |
$pos = strpos( $this->buffer, $boundary ); |
| 266 |
if ( $pos !== false ) { |
| 267 |
$foundBoundaries[$pos] = [ |
| 268 |
'type' => $type, |
| 269 |
'pos' => $pos, |
| 270 |
'length' => strlen( $boundary ) |
| 271 |
]; |
| 272 |
} |
| 273 |
} |
| 274 |
ksort( $foundBoundaries, SORT_NUMERIC ); |
| 275 |
$boundary = reset( $foundBoundaries ); |
| 276 |
|
| 277 |
// reset() returns false if the array is empty, but phan incorrectly |
| 278 |
// leaves this out of the union |
| 279 |
'@phan-var array|false $boundary'; |
| 280 |
|
| 281 |
$this->atPartEnd = false; |
| 282 |
if ( $boundary === false && strlen( $this->buffer ) <= self::CHUNK_SIZE ) { |
| 283 |
$chunk = $this->buffer; |
| 284 |
$this->buffer = ''; |
| 285 |
return $chunk; |
| 286 |
} elseif ( $boundary === false || $boundary['pos'] > self::CHUNK_SIZE ) { |
| 287 |
$chunk = substr( $this->buffer, 0, self::CHUNK_SIZE ); |
| 288 |
$this->buffer = substr( $this->buffer, self::CHUNK_SIZE ); |
| 289 |
return $chunk; |
| 290 |
} else { |
| 291 |
$chunk = substr( $this->buffer, 0, $boundary['pos'] ); |
| 292 |
// Consume boundary |
| 293 |
$this->buffer = substr( $this->buffer, $boundary['pos'] + $boundary['length'] ); |
| 294 |
$this->atPartEnd = true; |
| 295 |
if ( $boundary['type'] === 'closing' ) { |
| 296 |
$this->inEpilogue = true; |
| 297 |
} |
| 298 |
return $chunk; |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
/** |
| 303 |
* Read a line. This is used to read headers. Per RFC 1341, lines are |
| 304 |
* always terminated with CRLF, not LF. |
| 305 |
* |
| 306 |
* @return bool|string |
| 307 |
* @throws MultipartError |
| 308 |
*/ |
| 309 |
private function readLine() { |
| 310 |
$this->refillBuffer(); |
| 311 |
$breakPos = strpos( $this->buffer, "\r\n" ); |
| 312 |
if ( $breakPos === false ) { |
| 313 |
$this->error( "unexpectedly found the end of the input while " . |
| 314 |
"looking for the end of a line" ); |
| 315 |
} |
| 316 |
|
| 317 |
$line = substr( $this->buffer, 0, $breakPos ); |
| 318 |
$this->buffer = substr( $this->buffer, $breakPos + 2 ); |
| 319 |
return $line; |
| 320 |
} |
| 321 |
|
| 322 |
/** |
| 323 |
* Reset the atPartEnd flag so that we can read the next part. |
| 324 |
*/ |
| 325 |
private function nextPart() { |
| 326 |
if ( !$this->inEpilogue ) { |
| 327 |
$this->atPartEnd = false; |
| 328 |
} |
| 329 |
} |
| 330 |
|
| 331 |
/** |
| 332 |
* Throw an exception. |
| 333 |
* |
| 334 |
* @param string $message |
| 335 |
* @throws MultipartError |
| 336 |
* @return never |
| 337 |
*/ |
| 338 |
private function error( $message ) { |
| 339 |
throw new MultipartError( "Error reading multipart content: $message" ); |
| 340 |
} |
| 341 |
} |