|
1
|
|
|
<?php
|
|
2
|
|
|
|
|
3
|
|
|
/**
|
|
4
|
|
|
* This file is a part of Woketo package.
|
|
5
|
|
|
*
|
|
6
|
|
|
* (c) Nekland <[email protected]>
|
|
7
|
|
|
*
|
|
8
|
|
|
* For the full license, take a look to the LICENSE file
|
|
9
|
|
|
* on the root directory of this project
|
|
10
|
|
|
*/
|
|
11
|
|
|
|
|
12
|
|
|
namespace Nekland\Woketo\Rfc6455\Handshake;
|
|
13
|
|
|
use Nekland\Woketo\Exception\WebsocketException;
|
|
14
|
|
|
use Nekland\Woketo\Exception\WebsocketVersionException;
|
|
15
|
|
|
use Nekland\Woketo\Http\AbstractHttpMessage;
|
|
16
|
|
|
use Nekland\Woketo\Http\Request;
|
|
17
|
|
|
use Nekland\Woketo\Http\Response;
|
|
18
|
|
|
|
|
19
|
|
|
|
|
20
|
|
|
/**
|
|
21
|
|
|
* Class ServerHandshake
|
|
22
|
|
|
*
|
|
23
|
|
|
* This class is highly inspired by ratchetphp/RFC6455.
|
|
24
|
|
|
*/
|
|
25
|
|
|
class ServerHandshake implements HandshakeInterface
|
|
26
|
|
|
{
|
|
27
|
|
|
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
28
|
|
|
const SUPPORTED_VERSIONS = [13];
|
|
29
|
|
|
|
|
30
|
5 |
|
public function sign($key, Response $response = null)
|
|
31
|
|
|
{
|
|
32
|
5 |
|
if ($key instanceof Request) {
|
|
33
|
4 |
|
$key = $key->getHeader('Sec-WebSocket-Key');
|
|
34
|
|
|
}
|
|
35
|
|
|
|
|
36
|
5 |
|
$sign = \base64_encode(\sha1($key . ServerHandshake::GUID, true));
|
|
37
|
|
|
|
|
38
|
5 |
|
if (null !== $response) {
|
|
39
|
4 |
|
$response->addHeader('Sec-WebSocket-Accept', $sign);
|
|
40
|
|
|
}
|
|
41
|
|
|
|
|
42
|
5 |
|
return $sign;
|
|
43
|
|
|
}
|
|
44
|
|
|
|
|
45
|
10 |
|
public function verify($request)
|
|
46
|
|
|
{
|
|
47
|
10 |
|
if ($request->getHttpVersion() !== 'HTTP/1.1') {
|
|
48
|
1 |
|
throw new WebsocketException(
|
|
49
|
1 |
|
\sprintf('Wrong http version, HTTP/1.1 expected, "%s" received.', $request->getHttpVersion())
|
|
50
|
|
|
);
|
|
51
|
|
|
}
|
|
52
|
|
|
|
|
53
|
9 |
|
if ($request->getMethod() !== 'GET') {
|
|
54
|
1 |
|
throw new WebsocketException(
|
|
55
|
1 |
|
\sprintf('Wrong http method, GET expected, "%" received.', $request->getMethod())
|
|
56
|
|
|
);
|
|
57
|
|
|
}
|
|
58
|
|
|
|
|
59
|
8 |
|
$headers = $request->getHeaders();
|
|
60
|
8 |
|
if (empty($headers['Sec-WebSocket-Key'])) {
|
|
61
|
1 |
|
throw new WebsocketException(
|
|
62
|
1 |
|
\sprintf('Missing websocket key header.')
|
|
63
|
|
|
);
|
|
64
|
|
|
}
|
|
65
|
|
|
|
|
66
|
7 |
|
if (empty($headers['Upgrade']) || 'websocket' !== \strtolower($headers['Upgrade'])) {
|
|
67
|
1 |
|
throw new WebsocketException(
|
|
68
|
1 |
|
\sprintf('Wrong or missing upgrade header.')
|
|
69
|
|
|
);
|
|
70
|
|
|
}
|
|
71
|
|
|
|
|
72
|
6 |
|
$version = $headers->get('Sec-WebSocket-Version');
|
|
73
|
6 |
|
if (!\in_array($version, ServerHandshake::SUPPORTED_VERSIONS)) {
|
|
74
|
1 |
|
throw new WebsocketVersionException(sprintf('Version %s not supported by Woketo for now.', $version));
|
|
75
|
|
|
}
|
|
76
|
|
|
|
|
77
|
5 |
|
return true;
|
|
78
|
|
|
}
|
|
79
|
|
|
} |