summaryrefslogtreecommitdiff
path: root/vendor/aws/aws-sdk-php/src/Api/Parser/DecodingEventStreamIterator.php
blob: 7ad03bf87b1acb31cfe0bcc33b99000df7d14d2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php

namespace Aws\Api\Parser;

use \Iterator;
use Aws\Api\DateTimeResult;
use GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
use Aws\Api\Parser\Exception\ParserException;

/**
 * @internal Implements a decoder for a binary encoded event stream that will
 * decode, validate, and provide individual events from the stream.
 */
class DecodingEventStreamIterator implements Iterator
{
    const HEADERS = 'headers';
    const PAYLOAD = 'payload';

    const LENGTH_TOTAL = 'total_length';
    const LENGTH_HEADERS = 'headers_length';

    const CRC_PRELUDE = 'prelude_crc';

    const BYTES_PRELUDE = 12;
    const BYTES_TRAILING = 4;

    private static $preludeFormat = [
        self::LENGTH_TOTAL => 'decodeUint32',
        self::LENGTH_HEADERS => 'decodeUint32',
        self::CRC_PRELUDE => 'decodeUint32',
    ];

    private static $lengthFormatMap = [
        1 => 'decodeUint8',
        2 => 'decodeUint16',
        4 => 'decodeUint32',
        8 => 'decodeUint64',
    ];

    private static $headerTypeMap = [
        0 => 'decodeBooleanTrue',
        1 => 'decodeBooleanFalse',
        2 => 'decodeInt8',
        3 => 'decodeInt16',
        4 => 'decodeInt32',
        5 => 'decodeInt64',
        6 => 'decodeBytes',
        7 => 'decodeString',
        8 => 'decodeTimestamp',
        9 => 'decodeUuid',
    ];

    /** @var StreamInterface Stream of eventstream shape to parse. */
    private $stream;

    /** @var array Currently parsed event. */
    private $currentEvent;

    /** @var int Current in-order event key. */
    private $key;

    /** @var resource|\HashContext CRC32 hash context for event validation */
    private $hashContext;

    /** @var int $currentPosition */
    private $currentPosition;

    /**
     * DecodingEventStreamIterator constructor.
     *
     * @param StreamInterface $stream
     */
    public function __construct(StreamInterface $stream)
    {
        $this->stream = $stream;
        $this->rewind();
    }

    private function parseHeaders($headerBytes)
    {
        $headers = [];
        $bytesRead = 0;

        while ($bytesRead < $headerBytes) {
            list($key, $numBytes) = $this->decodeString(1);
            $bytesRead += $numBytes;

            list($type, $numBytes) = $this->decodeUint8();
            $bytesRead += $numBytes;

            $f = self::$headerTypeMap[$type];
            list($value, $numBytes) = $this->{$f}();
            $bytesRead += $numBytes;

            if (isset($headers[$key])) {
                throw new ParserException('Duplicate key in event headers.');
            }
            $headers[$key] = $value;
        }

        return [$headers, $bytesRead];
    }

    private function parsePrelude()
    {
        $prelude = [];
        $bytesRead = 0;

        $calculatedCrc = null;
        foreach (self::$preludeFormat as $key => $decodeFunction) {
            if ($key === self::CRC_PRELUDE) {
                $hashCopy = hash_copy($this->hashContext);
                $calculatedCrc = hash_final($this->hashContext, true);
                $this->hashContext = $hashCopy;
            }
            list($value, $numBytes) = $this->{$decodeFunction}();
            $bytesRead += $numBytes;

            $prelude[$key] = $value;
        }

        if (unpack('N', $calculatedCrc)[1] !== $prelude[self::CRC_PRELUDE]) {
            throw new ParserException('Prelude checksum mismatch.');
        }

        return [$prelude, $bytesRead];
    }

    private function parseEvent()
    {
        $event = [];

        if ($this->stream->tell() < $this->stream->getSize()) {
            $this->hashContext = hash_init('crc32b');

            $bytesLeft = $this->stream->getSize() - $this->stream->tell();
            list($prelude, $numBytes) = $this->parsePrelude();
            if ($prelude[self::LENGTH_TOTAL] > $bytesLeft) {
                throw new ParserException('Message length too long.');
            }
            $bytesLeft -= $numBytes;

            if ($prelude[self::LENGTH_HEADERS] > $bytesLeft) {
                throw new ParserException('Headers length too long.');
            }

            list(
                $event[self::HEADERS],
                $numBytes
            ) = $this->parseHeaders($prelude[self::LENGTH_HEADERS]);

            $event[self::PAYLOAD] = Psr7\Utils::streamFor(
                $this->readAndHashBytes(
                    $prelude[self::LENGTH_TOTAL] - self::BYTES_PRELUDE
                    - $numBytes - self::BYTES_TRAILING
                )
            );

            $calculatedCrc = hash_final($this->hashContext, true);
            $messageCrc = $this->stream->read(4);
            if ($calculatedCrc !== $messageCrc) {
                throw new ParserException('Message checksum mismatch.');
            }
        }

        return $event;
    }

    // Iterator Functionality

    /**
     * @return array
     */
    #[\ReturnTypeWillChange]
    public function current()
    {
        return $this->currentEvent;
    }

    /**
     * @return int
     */
    #[\ReturnTypeWillChange]
    public function key()
    {
        return $this->key;
    }

    #[\ReturnTypeWillChange]
    public function next()
    {
        $this->currentPosition = $this->stream->tell();
        if ($this->valid()) {
            $this->key++;
            $this->currentEvent = $this->parseEvent();
        }
    }

    #[\ReturnTypeWillChange]
    public function rewind()
    {
        $this->stream->rewind();
        $this->key = 0;
        $this->currentPosition = 0;
        $this->currentEvent = $this->parseEvent();
    }

    /**
     * @return bool
     */
    #[\ReturnTypeWillChange]
    public function valid()
    {
        return $this->currentPosition < $this->stream->getSize();
    }

    // Decoding Utilities

    private function readAndHashBytes($num)
    {
        $bytes = $this->stream->read($num);
        hash_update($this->hashContext, $bytes);
        return $bytes;
    }

    private function decodeBooleanTrue()
    {
        return [true, 0];
    }

    private function decodeBooleanFalse()
    {
        return [false, 0];
    }

    private function uintToInt($val, $size)
    {
        $signedCap = pow(2, $size - 1);
        if ($val > $signedCap) {
            $val -= (2 * $signedCap);
        }
        return $val;
    }

    private function decodeInt8()
    {
        $val = (int)unpack('C', $this->readAndHashBytes(1))[1];
        return [$this->uintToInt($val, 8), 1];
    }

    private function decodeUint8()
    {
        return [unpack('C', $this->readAndHashBytes(1))[1], 1];
    }

    private function decodeInt16()
    {
        $val = (int)unpack('n', $this->readAndHashBytes(2))[1];
        return [$this->uintToInt($val, 16), 2];
    }

    private function decodeUint16()
    {
        return [unpack('n', $this->readAndHashBytes(2))[1], 2];
    }

    private function decodeInt32()
    {
        $val = (int)unpack('N', $this->readAndHashBytes(4))[1];
        return [$this->uintToInt($val, 32), 4];
    }

    private function decodeUint32()
    {
        return [unpack('N', $this->readAndHashBytes(4))[1], 4];
    }

    private function decodeInt64()
    {
        $val = $this->unpackInt64($this->readAndHashBytes(8))[1];
        return [$this->uintToInt($val, 64), 8];
    }

    private function decodeUint64()
    {
        return [$this->unpackInt64($this->readAndHashBytes(8))[1], 8];
    }

    private function unpackInt64($bytes)
    {
        if (version_compare(PHP_VERSION, '5.6.3', '<')) {
            $d = unpack('N2', $bytes);
            return [1 => $d[1] << 32 | $d[2]];
        }
        return unpack('J', $bytes);
    }

    private function decodeBytes($lengthBytes=2)
    {
        if (!isset(self::$lengthFormatMap[$lengthBytes])) {
            throw new ParserException('Undefined variable length format.');
        }
        $f = self::$lengthFormatMap[$lengthBytes];
        list($len, $bytes) = $this->{$f}();
        return [$this->readAndHashBytes($len), $len + $bytes];
    }

    private function decodeString($lengthBytes=2)
    {
        if (!isset(self::$lengthFormatMap[$lengthBytes])) {
            throw new ParserException('Undefined variable length format.');
        }
        $f = self::$lengthFormatMap[$lengthBytes];
        list($len, $bytes) = $this->{$f}();
        return [$this->readAndHashBytes($len), $len + $bytes];
    }

    private function decodeTimestamp()
    {
        list($val, $bytes) = $this->decodeInt64();
        return [
            DateTimeResult::createFromFormat('U.u', $val / 1000),
            $bytes
        ];
    }

    private function decodeUuid()
    {
        $val = unpack('H32', $this->readAndHashBytes(16))[1];
        return [
            substr($val, 0, 8) . '-'
            . substr($val, 8, 4) . '-'
            . substr($val, 12, 4) . '-'
            . substr($val, 16, 4) . '-'
            . substr($val, 20, 12),
            16
        ];
    }
}