This repository has been archived by the owner on Aug 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathVersion1X.php
317 lines (252 loc) · 9.06 KB
/
Version1X.php
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
<?php
/**
* This file is part of the Elephant.io package
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*
* @copyright Wisembly
* @license http://www.opensource.org/licenses/MIT-License MIT License
*/
namespace ElephantIO\Engine\SocketIO;
use InvalidArgumentException;
use UnexpectedValueException;
use ElephantIO\EngineInterface;
use ElephantIO\Payload\Encoder;
use ElephantIO\Engine\AbstractSocketIO;
use ElephantIO\Exception\SocketException;
use ElephantIO\Exception\UnsupportedTransportException;
use ElephantIO\Exception\ServerConnectionFailureException;
/**
* Implements the dialog with Socket.IO version 1.x
*
* Based on the work of Mathieu Lallemand (@lalmat)
*
* @author Baptiste Clavié <baptiste@wisembly.com>
* @link https://tools.ietf.org/html/rfc6455#section-5.2 Websocket's RFC
*/
class Version1X extends AbstractSocketIO
{
const TRANSPORT_POLLING = 'polling';
const TRANSPORT_WEBSOCKET = 'websocket';
/** {@inheritDoc} */
public function connect()
{
if (\is_resource($this->stream)) {
return;
}
$this->handshake();
$protocol = 'http';
$errors = [null, null];
$host = \sprintf('%s:%d', $this->url['host'], $this->url['port']);
if (true === $this->url['secured']) {
$protocol = 'ssl';
$host = 'ssl://' . $host;
}
// add custom headers
if (isset($this->options['headers'])) {
$headers = isset($this->context[$protocol]['header']) ? $this->context[$protocol]['header'] : [];
$this->context[$protocol]['header'] = \array_merge($headers, $this->options['headers']);
}
$this->stream = \stream_socket_client(
$host,
$errors[0],
$errors[1],
$this->options['timeout'],
STREAM_CLIENT_CONNECT,
\stream_context_create($this->context)
);
if (!\is_resource($this->stream)) {
throw new SocketException($errors[0], $errors[1]);
}
\stream_set_timeout($this->stream, $this->options['timeout']);
$this->upgradeTransport();
}
/** {@inheritDoc} */
public function close()
{
if (!\is_resource($this->stream)) {
return;
}
$this->write(EngineInterface::CLOSE);
\fclose($this->stream);
$this->stream = null;
$this->session = null;
$this->cookies = [];
}
/** {@inheritDoc} */
public function emit($event, array $args)
{
$this->keepAlive();
$namespace = $this->namespace;
if ('' !== $namespace) {
$namespace .= ',';
}
return $this->write(EngineInterface::MESSAGE, static::EVENT . $namespace . \json_encode([$event, $args]));
}
/** {@inheritDoc} */
public function of($namespace)
{
$this->keepAlive();
parent::of($namespace);
$this->write(EngineInterface::MESSAGE, static::CONNECT . $namespace);
}
/** {@inheritDoc} */
public function write($code, $message = null)
{
if (!\is_resource($this->stream)) {
return;
}
if (!\is_int($code) || 0 > $code || 6 < $code) {
throw new InvalidArgumentException('Wrong message type when trying to write on the socket');
}
$payload = new Encoder($code . $message, Encoder::OPCODE_TEXT, true);
$bytes = @\fwrite($this->stream, (string) $payload);
if ($bytes === false){
throw new \Exception("Message was not delivered");
}
// wait a little bit of time after this message was sent
\usleep((int) $this->options['wait']);
return $bytes;
}
/** {@inheritDoc} */
public function getName()
{
return 'SocketIO Version 1.X';
}
/** {@inheritDoc} */
protected function getDefaultOptions()
{
$defaults = parent::getDefaultOptions();
$defaults['version'] = 2;
$defaults['use_b64'] = false;
$defaults['transport'] = static::TRANSPORT_POLLING;
return $defaults;
}
/** Does the handshake with the Socket.io server and populates the `session` value object */
protected function handshake()
{
if (null !== $this->session) {
return;
}
$query = ['use_b64' => $this->options['use_b64'],
'EIO' => $this->options['version'],
'transport' => $this->options['transport']];
if (isset($this->url['query'])) {
$query = \array_replace($query, $this->url['query']);
}
$context = $this->context;
$protocol = true === $this->url['secured'] ? 'ssl' : 'http';
if (!isset($context[$protocol])) {
$context[$protocol] = [];
}
// add customer headers
if (isset($this->options['headers'])) {
$headers = isset($context['http']['header']) ? $context['http']['header'] : [];
$context['http']['header'] = array_merge($headers, $this->options['headers']);
}
$url = \sprintf(
'%s://%s:%d/%s/?%s',
$this->url['scheme'],
$this->url['host'],
$this->url['port'],
\trim($this->url['path'], '/'),
\http_build_query($query)
);
$result = @\file_get_contents($url, false, \stream_context_create($context));
if (false === $result) {
$message = null;
$error = \error_get_last();
if (null !== $error && false !== \strpos($error['message'], 'file_get_contents()')) {
$message = $error['message'];
}
throw new ServerConnectionFailureException($message);
}
$open_curly_at = \strpos($result, '{');
$todecode = \substr($result, $open_curly_at, \strrpos($result, '}')-$open_curly_at+1);
$decoded = \json_decode($todecode, true);
if (!\in_array('websocket', $decoded['upgrades'])) {
throw new UnsupportedTransportException('websocket');
}
$cookies = [];
foreach ($http_response_header as $header) {
if (\preg_match('/^Set-Cookie:\s*([^;]*)/i', $header, $matches)) {
$cookies[] = $matches[1];
}
}
$this->cookies = $cookies;
$this->session = new Session(
$decoded['sid'],
$decoded['pingInterval'] / 1000,
$decoded['pingTimeout'] / 1000,
$decoded['upgrades']
);
}
/**
* Upgrades the transport to WebSocket
*
* FYI:
* Version "2" is used for the EIO param by socket.io v1
* Version "3" is used by socket.io v2
*/
protected function upgradeTransport()
{
$query = ['sid' => $this->session->id,
'EIO' => $this->options['version'],
'transport' => static::TRANSPORT_WEBSOCKET];
if ($this->options['version'] === 2) {
$query['use_b64'] = $this->options['use_b64'];
}
$url = \sprintf('/%s/?%s', \trim($this->url['path'], '/'), \http_build_query($query));
$hash = \sha1(\uniqid(\mt_rand(), true), true);
if ($this->options['version'] !== 2) {
$hash = \substr($hash, 0, 16);
}
$key = \base64_encode($hash);
$origin = '*';
$headers = isset($this->context['headers']) ? (array) $this->context['headers'] : [] ;
foreach ($headers as $header) {
$matches = [];
if (\preg_match('`^Origin:\s*(.+?)$`', $header, $matches)) {
$origin = $matches[1];
break;
}
}
$request = "GET {$url} HTTP/1.1\r\n"
. "Host: {$this->url['host']}:{$this->url['port']}\r\n"
. "Upgrade: WebSocket\r\n"
. "Connection: Upgrade\r\n"
. "Sec-WebSocket-Key: {$key}\r\n"
. "Sec-WebSocket-Version: 13\r\n"
. "Origin: {$origin}\r\n";
if (!empty($this->cookies)) {
$request .= "Cookie: " . \implode('; ', $this->cookies) . "\r\n";
}
$request .= "\r\n";
\fwrite($this->stream, $request);
$result = $this->readBytes(12);
if ('HTTP/1.1 101' !== $result) {
throw new UnexpectedValueException(
\sprintf('The server returned an unexpected value. Expected "HTTP/1.1 101", had "%s"', $result)
);
}
// cleaning up the stream
while ('' !== \trim(\fgets($this->stream)));
$this->write(EngineInterface::UPGRADE);
//remove message '40' from buffer, emmiting by socket.io after receiving EngineInterface::UPGRADE
if ($this->options['version'] === 2) {
if (stream_get_meta_data($this->stream)["unread_bytes"] !== 0) {
$this->read();
}
}
}
/**
* {@inheritDoc}
*/
public function keepAlive()
{
if ($this->session->needsHeartbeat()) {
$this->write(static::PING);
}
}
}