4
4
5
5
use Evenement \EventEmitter ;
6
6
use Psr \Http \Message \ServerRequestInterface ;
7
+ use React \EventLoop \LoopInterface ;
7
8
use React \Http \Message \Response ;
8
9
use React \Http \Message \ServerRequest ;
9
10
use React \Socket \ConnectionInterface ;
@@ -24,12 +25,51 @@ class RequestHeaderParser extends EventEmitter
24
25
{
25
26
private $ maxSize = 8192 ;
26
27
27
- public function handle (ConnectionInterface $ conn )
28
+ /**
29
+ * @var LoopInterface
30
+ */
31
+ private $ loop ;
32
+
33
+ /**
34
+ * @var float
35
+ */
36
+ private $ idleConnectionTimeout ;
37
+
38
+ /**
39
+ * @param LoopInterface $loop
40
+ * @param float $idleConnectionTimeout
41
+ */
42
+ public function __construct (LoopInterface $ loop , $ idleConnectionTimeout )
28
43
{
44
+ $ this ->loop = $ loop ;
45
+ $ this ->idleConnectionTimeout = $ idleConnectionTimeout ;
46
+ }
47
+
48
+ /**
49
+ * @param bool $firstRequest
50
+ */
51
+ public function handle (ConnectionInterface $ conn , $ firstRequest = true )
52
+ {
53
+ $ loop = $ this ->loop ;
54
+ $ idleConnectionTimeout = $ this ->idleConnectionTimeout ;
55
+ $ createTimer = function () use ($ conn , $ loop , $ idleConnectionTimeout , $ firstRequest ) {
56
+ return $ loop ->addTimer ($ idleConnectionTimeout , function () use ($ conn , $ firstRequest ) {
57
+ if ($ firstRequest ) {
58
+ $ conn ->write ("HTTP/1.0 " . Response::STATUS_REQUEST_TIMEOUT . " Request Timed Out \r\n" );
59
+ }
60
+ $ conn ->close ();
61
+ });
62
+ };
63
+ $ timer = $ createTimer ();
64
+ $ conn ->on ('close ' , function () use ($ loop , $ timer ) {
65
+ $ loop ->cancelTimer ($ timer );
66
+ });
29
67
$ buffer = '' ;
30
68
$ maxSize = $ this ->maxSize ;
31
69
$ that = $ this ;
32
- $ conn ->on ('data ' , $ fn = function ($ data ) use (&$ buffer , &$ fn , $ conn , $ maxSize , $ that ) {
70
+ $ conn ->on ('data ' , $ fn = function ($ data ) use (&$ buffer , &$ fn , $ conn , $ maxSize , $ that , $ loop , &$ timer , $ createTimer ) {
71
+ $ loop ->cancelTimer ($ timer );
72
+ $ timer = $ createTimer ();
33
73
// append chunk of data to buffer and look for end of request headers
34
74
$ buffer .= $ data ;
35
75
$ endOfHeader = \strpos ($ buffer , "\r\n\r\n" );
@@ -43,6 +83,7 @@ public function handle(ConnectionInterface $conn)
43
83
new \OverflowException ("Maximum header size of {$ maxSize } exceeded. " , Response::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE ),
44
84
$ conn
45
85
));
86
+ $ loop ->cancelTimer ($ timer );
46
87
return ;
47
88
}
48
89
@@ -67,6 +108,7 @@ public function handle(ConnectionInterface $conn)
67
108
$ exception ,
68
109
$ conn
69
110
));
111
+ $ loop ->cancelTimer ($ timer );
70
112
return ;
71
113
}
72
114
@@ -105,6 +147,7 @@ public function handle(ConnectionInterface $conn)
105
147
if ($ contentLength === 0 ) {
106
148
$ stream ->emit ('end ' );
107
149
$ stream ->close ();
150
+ $ loop ->cancelTimer ($ timer );
108
151
}
109
152
});
110
153
}
0 commit comments