Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/Api/Parser/DecodingEventStreamIterator.php

raw symbols SCIP
1 <?php
2
3 namespace Aws\Api\Parser;
4
5 use \Iterator;
6 use Aws\Api\DateTimeResult;
7 use GuzzleHttp\Psr7;
8 use Psr\Http\Message\StreamInterface;
9 use Aws\Api\Parser\Exception\ParserException;
10
11 /**
12 * @internal Implements a decoder for a binary encoded event stream that will
13 * decode, validate, and provide individual events from the stream.
14 */
15 class DecodingEventStreamIterator implements Iterator
16 {
17 const HEADERS = 'headers';
18 const PAYLOAD = 'payload';
19
20 const LENGTH_TOTAL = 'total_length';
21 const LENGTH_HEADERS = 'headers_length';
22
23 const CRC_PRELUDE = 'prelude_crc';
24
25 const BYTES_PRELUDE = 12;
26 const BYTES_TRAILING = 4;
27
28 private static $preludeFormat = [
29 self::LENGTH_TOTAL => 'decodeUint32',
30 self::LENGTH_HEADERS => 'decodeUint32',
31 self::CRC_PRELUDE => 'decodeUint32',
32 ];
33
34 private static $lengthFormatMap = [
35 1 => 'decodeUint8',
36 2 => 'decodeUint16',
37 4 => 'decodeUint32',
38 8 => 'decodeUint64',
39 ];
40
41 private static $headerTypeMap = [
42 0 => 'decodeBooleanTrue',
43 1 => 'decodeBooleanFalse',
44 2 => 'decodeInt8',
45 3 => 'decodeInt16',
46 4 => 'decodeInt32',
47 5 => 'decodeInt64',
48 6 => 'decodeBytes',
49 7 => 'decodeString',
50 8 => 'decodeTimestamp',
51 9 => 'decodeUuid',
52 ];
53
54 /** @var StreamInterface Stream of eventstream shape to parse. */
55 protected $stream;
56
57 /** @var array Currently parsed event. */
58 protected $currentEvent;
59
60 /** @var int Current in-order event key. */
61 protected $key;
62
63 /** @var resource|\HashContext CRC32 hash context for event validation */
64 protected $hashContext;
65
66 /** @var int $currentPosition */
67 protected $currentPosition;
68
69 /**
70 * DecodingEventStreamIterator constructor.
71 *
72 * @param StreamInterface $stream
73 */
74 public function __construct(StreamInterface $stream)
75 {
76 $this->stream = $stream;
77 $this->rewind();
78 }
79
80 protected function parseHeaders($headerBytes)
81 {
82 $headers = [];
83 $bytesRead = 0;
84
85 while ($bytesRead < $headerBytes) {
86 list($key, $numBytes) = $this->decodeString(1);
87 $bytesRead += $numBytes;
88
89 list($type, $numBytes) = $this->decodeUint8();
90 $bytesRead += $numBytes;
91
92 $f = self::$headerTypeMap[$type];
93 list($value, $numBytes) = $this->{$f}();
94 $bytesRead += $numBytes;
95
96 if (isset($headers[$key])) {
97 throw new ParserException('Duplicate key in event headers.');
98 }
99 $headers[$key] = $value;
100 }
101
102 return [$headers, $bytesRead];
103 }
104
105 protected function parsePrelude()
106 {
107 $prelude = [];
108 $bytesRead = 0;
109
110 $calculatedCrc = null;
111 foreach (self::$preludeFormat as $key => $decodeFunction) {
112 if ($key === self::CRC_PRELUDE) {
113 $hashCopy = hash_copy($this->hashContext);
114 $calculatedCrc = hash_final($this->hashContext, true);
115 $this->hashContext = $hashCopy;
116 }
117 list($value, $numBytes) = $this->{$decodeFunction}();
118 $bytesRead += $numBytes;
119
120 $prelude[$key] = $value;
121 }
122
123 if (unpack('N', $calculatedCrc)[1] !== $prelude[self::CRC_PRELUDE]) {
124 throw new ParserException('Prelude checksum mismatch.');
125 }
126
127 return [$prelude, $bytesRead];
128 }
129
130 /**
131 * This method decodes an event from the stream.
132 *
133 * @return array
134 */
135 protected function parseEvent()
136 {
137 $event = [];
138
139 if ($this->stream->tell() < $this->stream->getSize()) {
140 $this->hashContext = hash_init('crc32b');
141
142 $bytesLeft = $this->stream->getSize() - $this->stream->tell();
143 list($prelude, $numBytes) = $this->parsePrelude();
144 if ($prelude[self::LENGTH_TOTAL] > $bytesLeft) {
145 throw new ParserException('Message length too long.');
146 }
147 $bytesLeft -= $numBytes;
148
149 if ($prelude[self::LENGTH_HEADERS] > $bytesLeft) {
150 throw new ParserException('Headers length too long.');
151 }
152
153 list(
154 $event[self::HEADERS],
155 $numBytes
156 ) = $this->parseHeaders($prelude[self::LENGTH_HEADERS]);
157
158 $event[self::PAYLOAD] = Psr7\Utils::streamFor(
159 $this->readAndHashBytes(
160 $prelude[self::LENGTH_TOTAL] - self::BYTES_PRELUDE
161 - $numBytes - self::BYTES_TRAILING
162 )
163 );
164
165 $calculatedCrc = hash_final($this->hashContext, true);
166 $messageCrc = $this->stream->read(4);
167 if ($calculatedCrc !== $messageCrc) {
168 throw new ParserException('Message checksum mismatch.');
169 }
170 }
171
172 return $event;
173 }
174
175 // Iterator Functionality
176
177 /**
178 * @return array
179 */
180 #[\ReturnTypeWillChange]
181 public function current()
182 {
183 return $this->currentEvent;
184 }
185
186 /**
187 * @return int
188 */
189 #[\ReturnTypeWillChange]
190 public function key()
191 {
192 return $this->key;
193 }
194
195 /**
196 * @return void
197 */
198 #[\ReturnTypeWillChange]
199 public function next()
200 {
201 $this->currentPosition = $this->stream->tell();
202 if ($this->valid()) {
203 $this->key++;
204 $this->currentEvent = $this->parseEvent();
205 }
206 }
207
208 /**
209 * @return void
210 */
211 #[\ReturnTypeWillChange]
212 public function rewind()
213 {
214 $this->stream->rewind();
215 $this->key = 0;
216 $this->currentPosition = 0;
217 $this->currentEvent = $this->parseEvent();
218 }
219
220 /**
221 * @return bool
222 */
223 #[\ReturnTypeWillChange]
224 public function valid()
225 {
226 return $this->currentPosition < $this->stream->getSize();
227 }
228
229 // Decoding Utilities
230
231 protected function readAndHashBytes($num)
232 {
233 $bytes = $this->stream->read($num);
234 hash_update($this->hashContext, $bytes);
235 return $bytes;
236 }
237
238 private function decodeBooleanTrue()
239 {
240 return [true, 0];
241 }
242
243 private function decodeBooleanFalse()
244 {
245 return [false, 0];
246 }
247
248 private function uintToInt($val, $size)
249 {
250 $signedCap = pow(2, $size - 1);
251 if ($val > $signedCap) {
252 $val -= (2 * $signedCap);
253 }
254 return $val;
255 }
256
257 private function decodeInt8()
258 {
259 $val = (int)unpack('C', $this->readAndHashBytes(1))[1];
260 return [$this->uintToInt($val, 8), 1];
261 }
262
263 private function decodeUint8()
264 {
265 return [unpack('C', $this->readAndHashBytes(1))[1], 1];
266 }
267
268 private function decodeInt16()
269 {
270 $val = (int)unpack('n', $this->readAndHashBytes(2))[1];
271 return [$this->uintToInt($val, 16), 2];
272 }
273
274 private function decodeUint16()
275 {
276 return [unpack('n', $this->readAndHashBytes(2))[1], 2];
277 }
278
279 private function decodeInt32()
280 {
281 $val = (int)unpack('N', $this->readAndHashBytes(4))[1];
282 return [$this->uintToInt($val, 32), 4];
283 }
284
285 private function decodeUint32()
286 {
287 return [unpack('N', $this->readAndHashBytes(4))[1], 4];
288 }
289
290 private function decodeInt64()
291 {
292 $val = $this->unpackInt64($this->readAndHashBytes(8))[1];
293 return [$this->uintToInt($val, 64), 8];
294 }
295
296 private function decodeUint64()
297 {
298 return [$this->unpackInt64($this->readAndHashBytes(8))[1], 8];
299 }
300
301 private function unpackInt64($bytes)
302 {
303 return unpack('J', $bytes);
304 }
305
306 private function decodeBytes($lengthBytes=2)
307 {
308 if (!isset(self::$lengthFormatMap[$lengthBytes])) {
309 throw new ParserException('Undefined variable length format.');
310 }
311 $f = self::$lengthFormatMap[$lengthBytes];
312 list($len, $bytes) = $this->{$f}();
313 return [$this->readAndHashBytes($len), $len + $bytes];
314 }
315
316 private function decodeString($lengthBytes=2)
317 {
318 if (!isset(self::$lengthFormatMap[$lengthBytes])) {
319 throw new ParserException('Undefined variable length format.');
320 }
321 $f = self::$lengthFormatMap[$lengthBytes];
322 list($len, $bytes) = $this->{$f}();
323 return [$this->readAndHashBytes($len), $len + $bytes];
324 }
325
326 private function decodeTimestamp()
327 {
328 list($val, $bytes) = $this->decodeInt64();
329 return [
330 DateTimeResult::createFromFormat('U.u', $val / 1000),
331 $bytes
332 ];
333 }
334
335 private function decodeUuid()
336 {
337 $val = unpack('H32', $this->readAndHashBytes(16))[1];
338 return [
339 substr($val, 0, 8) . '-'
340 . substr($val, 8, 4) . '-'
341 . substr($val, 12, 4) . '-'
342 . substr($val, 16, 4) . '-'
343 . substr($val, 20, 12),
344 16
345 ];
346 }
347 }