|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Spike library |
|
4
|
|
|
* @author Tao <[email protected]> |
|
5
|
|
|
*/ |
|
6
|
|
|
namespace Spike\Server\TunnelServer; |
|
7
|
|
|
|
|
8
|
|
|
use GuzzleHttp\Psr7\Response; |
|
9
|
|
|
use GuzzleHttp\Psr7; |
|
10
|
|
|
use Spike\Parser\HttpHeaderParser; |
|
11
|
|
|
|
|
12
|
|
|
class HttpTunnelServer extends TunnelServer |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* {@inheritdoc} |
|
16
|
|
|
*/ |
|
17
|
|
|
public function handlePublicConnection(PublicConnection $publicConnection) |
|
18
|
|
|
{ |
|
19
|
|
|
$parser = new HttpHeaderParser(); |
|
20
|
|
|
$publicConnection->getConnection()->on('data', function($data) use ($parser, $publicConnection){ |
|
21
|
|
|
$parser->pushIncoming($data); |
|
22
|
|
|
$message = $parser->parseFirst(); |
|
23
|
|
|
echo $message; |
|
24
|
|
|
if ($message) { |
|
|
|
|
|
|
25
|
|
|
$psrRequest = Psr7\parse_request($message); |
|
26
|
|
|
$host = $psrRequest->getUri()->getHost(); |
|
27
|
|
|
if ($this->tunnel->supportProxyHost($host)) { |
|
|
|
|
|
|
28
|
|
|
$this->tunnel->setProxyHost($host); |
|
|
|
|
|
|
29
|
|
|
$httpMessage = $message . $parser->getRestData(); |
|
30
|
|
|
$publicConnection->setInitBuffer($httpMessage); |
|
31
|
|
|
parent::handlePublicConnection($publicConnection); |
|
32
|
|
|
} else { |
|
33
|
|
|
$body = sprintf('The host "%s" was not bound.', $host); |
|
34
|
|
|
$response = $this->makeErrorResponse(404, $body); |
|
35
|
|
|
$publicConnection->end(Psr7\str($response)); |
|
36
|
|
|
} |
|
37
|
|
|
} |
|
38
|
|
|
}); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Make an error psr7 response |
|
43
|
|
|
* @param int $code |
|
44
|
|
|
* @param string $message |
|
45
|
|
|
* @return Response |
|
46
|
|
|
*/ |
|
47
|
|
|
protected function makeErrorResponse($code, $message) |
|
48
|
|
|
{ |
|
49
|
|
|
$message = $message ?: 'Proxy error'; |
|
50
|
|
|
return new Response($code, [ |
|
51
|
|
|
'Content-Length' => strlen($message) |
|
52
|
|
|
], $message); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* {@inheritdoc} |
|
57
|
|
|
*/ |
|
58
|
|
|
public function closePublicConnection(PublicConnection $publicConnection, $message = null) |
|
59
|
|
|
{ |
|
60
|
|
|
$publicConnection->end(Psr7\str($this->makeErrorResponse(500, $message ?: 'Timeout'))); |
|
61
|
|
|
} |
|
62
|
|
|
} |
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
stringvalues, the empty string''is a special case, in particular the following results might be unexpected: