1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace SamIT\Proxy; |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
use React\EventLoop\LoopInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* This class wraps an existing connection and add support for the proxy protocol. |
11
|
|
|
* @package SamIT\Proxy |
12
|
|
|
*/ |
13
|
|
|
class ProxyConnection extends PortConnection implements PortConnectionInterface |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var Header; |
18
|
|
|
*/ |
19
|
|
|
protected $header; |
20
|
|
|
|
21
|
3 |
|
public function __construct($stream, LoopInterface $loop) |
22
|
|
|
{ |
23
|
3 |
|
parent::__construct($stream, $loop, true); |
24
|
3 |
|
} |
25
|
|
|
|
26
|
1 |
|
public function handleData($stream) |
27
|
|
|
{ |
28
|
|
|
// Socket is raw, not using fread as it's interceptable by filters |
29
|
|
|
// See issues #192, #209, and #240 |
30
|
1 |
|
$data = stream_socket_recvfrom($stream, $this->bufferSize); |
31
|
1 |
|
if ('' !== $data && false !== $data) { |
32
|
1 |
|
if (!isset($this->header)) { |
33
|
1 |
|
$data = $this->readProxyHeader($data); |
34
|
1 |
|
} |
35
|
1 |
|
if ('' !== $data && false !== $data) { |
36
|
|
|
$this->emit('data', array($data, $this)); |
37
|
|
|
} |
38
|
1 |
|
} elseif ('' === $data || false === $data || feof($stream)) { |
39
|
|
|
$this->end(); |
40
|
|
|
} |
41
|
1 |
|
} |
42
|
|
|
|
43
|
1 |
|
public function readProxyHeader($data) |
44
|
|
|
{ |
45
|
|
|
// Read the data, emit the rest. |
46
|
1 |
|
$header = Header::parseHeader($data); |
47
|
1 |
|
if ($header instanceof Header) { |
48
|
1 |
|
$this->header = $header; |
49
|
1 |
|
$this->emit('init', [$this]); |
50
|
1 |
|
} else { |
51
|
|
|
$this->header = false; |
52
|
|
|
throw new \RuntimeException("Invalid proxy header received."); |
53
|
|
|
} |
54
|
1 |
|
return $data; |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
public function getHeader() |
58
|
|
|
{ |
59
|
1 |
|
if (!isset($this->header)) { |
60
|
|
|
throw new \RuntimeException("Cannot use connection until a proxy header has been received."); |
61
|
|
|
} |
62
|
1 |
|
return $this->header; |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
public function getRemoteAddress() |
66
|
|
|
{ |
67
|
1 |
|
return $this->getHeader()->sourceAddress; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return int The remote port for this connection. |
72
|
|
|
*/ |
73
|
1 |
|
public function getRemotePort() |
74
|
|
|
{ |
75
|
1 |
|
return $this->getHeader()->sourcePort; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @return int The target port for this connection. |
80
|
|
|
*/ |
81
|
1 |
|
public function getTargetPort() |
82
|
|
|
{ |
83
|
1 |
|
return $this->getHeader()->targetPort; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* @return string The target address for this connection. |
88
|
|
|
*/ |
89
|
1 |
|
public function getTargetAddress() |
90
|
|
|
{ |
91
|
1 |
|
return $this->getHeader()->targetAddress; |
92
|
|
|
} |
93
|
|
|
} |