|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
namespace SamIT\Proxy; |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
use React\Dns\Resolver\Factory; |
|
8
|
|
|
use React\Dns\Resolver\Resolver; |
|
9
|
|
|
use React\EventLoop\LoopInterface; |
|
10
|
|
|
use React\Socket\Connection; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Class Server |
|
14
|
|
|
* A server that receives proxy connections. |
|
15
|
|
|
* If no proxy header is received within 5 seconds after connection opening than the connection is closed. |
|
16
|
|
|
* The `connection` event is only triggered after receiving the header. |
|
17
|
|
|
* @package SamIT\Proxy |
|
18
|
|
|
* @event connection When an new connection has been fully set up (ie a proxy header was received). |
|
19
|
|
|
* @emits proxytimeout When a new connection failed to send a proxy header within 5 seconds after opening the connection. |
|
20
|
|
|
*/ |
|
21
|
|
|
class Server extends \React\Socket\Server |
|
22
|
|
|
{ |
|
23
|
|
|
private $loop; |
|
|
|
|
|
|
24
|
|
|
|
|
25
|
4 |
|
public function __construct(LoopInterface $loop) |
|
26
|
|
|
{ |
|
27
|
4 |
|
$this->loop = $loop; |
|
28
|
4 |
|
parent::__construct($loop); |
|
29
|
4 |
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Handle the connection. We only emit the connection event after the proper header was received. |
|
33
|
|
|
* @param $socket |
|
34
|
|
|
*/ |
|
35
|
2 |
|
public function handleConnection($socket) |
|
36
|
|
|
{ |
|
37
|
2 |
|
stream_set_blocking($socket, 0); |
|
38
|
2 |
|
$client = $this->createConnection($socket); |
|
39
|
|
|
|
|
40
|
|
|
$timer = $this->loop->addTimer(5, function() use ($client) { |
|
41
|
1 |
|
$client->removeAllListeners('init'); |
|
42
|
1 |
|
$client->end('Timeout waiting for PROXY header.'); |
|
43
|
|
|
|
|
44
|
1 |
|
$this->emit('proxytimeout', [new Connection($client->stream, $this->loop)]); |
|
45
|
2 |
|
}); |
|
46
|
|
|
|
|
47
|
2 |
|
$client->on('init', function($connection) use ($client, $timer) { |
|
48
|
1 |
|
$timer->cancel(); |
|
49
|
1 |
|
$this->emit('connection', [$connection]); |
|
50
|
2 |
|
}); |
|
51
|
2 |
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @param $socket |
|
55
|
|
|
* @return ProxyConnection |
|
56
|
|
|
*/ |
|
57
|
2 |
|
public function createConnection($socket) |
|
58
|
|
|
{ |
|
59
|
2 |
|
return new ProxyConnection($socket, $this->loop); |
|
60
|
|
|
} |
|
61
|
|
|
} |