forked from reactphp/http
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.php
More file actions
196 lines (174 loc) · 7.01 KB
/
Server.php
File metadata and controls
196 lines (174 loc) · 7.01 KB
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
<?php
namespace React\Http;
use Evenement\EventEmitter;
use React\Socket\ServerInterface as SocketServerInterface;
use React\Socket\ConnectionInterface;
use Psr\Http\Message\RequestInterface;
/**
* The `Server` class is responsible for handling incoming connections and then
* emit a `request` event for each incoming HTTP request.
*
* ```php
* $socket = new React\Socket\Server(8080, $loop);
*
* $http = new React\Http\Server($socket);
* ```
*
* For each incoming connection, it emits a `request` event with the respective
* [`Request`](#request) and [`Response`](#response) objects:
*
* ```php
* $http->on('request', function (Request $request, Response $response) {
* $response->writeHead(200, array('Content-Type' => 'text/plain'));
* $response->end("Hello World!\n");
* });
* ```
*
* See also [`Request`](#request) and [`Response`](#response) for more details.
*
* > Note that you SHOULD always listen for the `request` event.
* Failing to do so will result in the server parsing the incoming request,
* but never sending a response back to the client.
*
* The `Server` supports both HTTP/1.1 and HTTP/1.0 request messages.
* If a client sends an invalid request message or uses an invalid HTTP protocol
* version, it will emit an `error` event, send an HTTP error response to the
* client and close the connection:
*
* ```php
* $http->on('error', function (Exception $e) {
* echo 'Error: ' . $e->getMessage() . PHP_EOL;
* });
* ```
*
* @see Request
* @see Response
*/
class Server extends EventEmitter
{
/**
* Creates a HTTP server that accepts connections from the given socket.
*
* It attaches itself to an instance of `React\Socket\ServerInterface` which
* emits underlying streaming connections in order to then parse incoming data
* as HTTP:
*
* ```php
* $socket = new React\Socket\Server(8080, $loop);
*
* $http = new React\Http\Server($socket);
* ```
*
* Similarly, you can also attach this to a
* [`React\Socket\SecureServer`](https://github.com/reactphp/socket#secureserver)
* in order to start a secure HTTPS server like this:
*
* ```php
* $socket = new Server(8080, $loop);
* $socket = new SecureServer($socket, $loop, array(
* 'local_cert' => __DIR__ . '/localhost.pem'
* ));
*
* $http = new React\Http\Server($socket);
* ```
*
* @param \React\Socket\ServerInterface $io
*/
public function __construct(SocketServerInterface $io)
{
$io->on('connection', array($this, 'handleConnection'));
}
/** @internal */
public function handleConnection(ConnectionInterface $conn)
{
$that = $this;
$parser = new RequestHeaderParser();
$listener = array($parser, 'feed');
$parser->on('headers', function (RequestInterface $request, $bodyBuffer) use ($conn, $listener, $parser, $that) {
// parsing request completed => stop feeding parser
$conn->removeListener('data', $listener);
$that->handleRequest($conn, $request);
if ($bodyBuffer !== '') {
$conn->emit('data', array($bodyBuffer));
}
});
$conn->on('data', $listener);
$parser->on('error', function(\Exception $e) use ($conn, $listener, $that) {
$conn->removeListener('data', $listener);
$that->emit('error', array($e));
$that->writeError(
$conn,
($e instanceof \OverflowException) ? 431 : 400
);
});
}
/** @internal */
public function handleRequest(ConnectionInterface $conn, RequestInterface $request)
{
// only support HTTP/1.1 and HTTP/1.0 requests
if ($request->getProtocolVersion() !== '1.1' && $request->getProtocolVersion() !== '1.0') {
$this->emit('error', array(new \InvalidArgumentException('Received request with invalid protocol version')));
return $this->writeError($conn, 505);
}
// HTTP/1.1 requests MUST include a valid host header (host and optional port)
// https://tools.ietf.org/html/rfc7230#section-5.4
if ($request->getProtocolVersion() === '1.1') {
$parts = parse_url('http://' . $request->getHeaderLine('Host'));
// make sure value contains valid host component (IP or hostname)
if (!$parts || !isset($parts['scheme'], $parts['host'])) {
$parts = false;
}
// make sure value does not contain any other URI component
unset($parts['scheme'], $parts['host'], $parts['port']);
if ($parts === false || $parts) {
$this->emit('error', array(new \InvalidArgumentException('Invalid Host header for HTTP/1.1 request')));
return $this->writeError($conn, 400);
}
}
$response = new Response($conn, $request->getProtocolVersion());
$stream = new CloseProtectionStream($conn);
if ($request->hasHeader('Transfer-Encoding')) {
$transferEncodingHeader = $request->getHeader('Transfer-Encoding');
// 'chunked' must always be the final value of 'Transfer-Encoding' according to: https://tools.ietf.org/html/rfc7230#section-3.3.1
if (strtolower(end($transferEncodingHeader)) === 'chunked') {
$stream = new ChunkedDecoder($stream);
}
} elseif ($request->hasHeader('Content-Length')) {
$string = $request->getHeaderLine('Content-Length');
$contentLength = (int)$string;
if ((string)$contentLength !== (string)$string) {
// Content-Length value is not an integer or not a single integer
$this->emit('error', array(new \InvalidArgumentException('The value of `Content-Length` is not valid')));
return $this->writeError($conn, 400);
}
$stream = new LengthLimitedStream($stream, $contentLength);
}
$request = new Request($request, $stream);
// attach remote ip to the request as metadata
$request->remoteAddress = trim(
parse_url('tcp://' . $conn->getRemoteAddress(), PHP_URL_HOST),
'[]'
);
$this->emit('request', array($request, $response));
if ($stream instanceof LengthLimitedStream && $contentLength === 0) {
// Content-Length is 0 and won't emit further data,
// 'handleData' from LengthLimitedStream won't be called anymore
$stream->emit('end');
$stream->close();
}
}
/** @internal */
public function writeError(ConnectionInterface $conn, $code)
{
$message = 'Error ' . $code;
if (isset(ResponseCodes::$statusTexts[$code])) {
$message .= ': ' . ResponseCodes::$statusTexts[$code];
}
$response = new Response($conn);
$response->writeHead($code, array(
'Content-Length' => strlen($message),
'Content-Type' => 'text/plain'
));
$response->end($message);
}
}