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 \ServerRequest ;
8
9
use React \Socket \ConnectionInterface ;
9
10
use Exception ;
@@ -23,12 +24,48 @@ class RequestHeaderParser extends EventEmitter
23
24
{
24
25
private $ maxSize = 8192 ;
25
26
27
+ /**
28
+ * @var LoopInterface
29
+ */
30
+ private $ loop ;
31
+
32
+ /**
33
+ * @var float
34
+ */
35
+ private $ idleConnectionTimeout ;
36
+
37
+ /**
38
+ * @param LoopInterface $loop
39
+ * @param float $idleConnectionTimeout
40
+ */
41
+ public function __construct (LoopInterface $ loop , $ idleConnectionTimeout )
42
+ {
43
+ $ this ->loop = $ loop ;
44
+ $ this ->idleConnectionTimeout = $ idleConnectionTimeout ;
45
+ }
46
+
26
47
public function handle (ConnectionInterface $ conn )
27
48
{
49
+ $ loop = $ this ->loop ;
50
+ $ idleConnectionTimeout = $ this ->idleConnectionTimeout ;
51
+ $ createTimer = function () use ($ conn , $ loop , $ idleConnectionTimeout ) {
52
+ return $ loop ->addTimer ($ idleConnectionTimeout , function () use ($ conn ) {
53
+ $ conn ->close ();
54
+ });
55
+ };
56
+ $ timer = $ createTimer ();
57
+ $ conn ->on ('end ' , function () use ($ loop , $ timer ) {
58
+ $ loop ->cancelTimer ($ timer );
59
+ });
60
+ $ conn ->on ('close ' , function () use ($ loop , $ timer ) {
61
+ $ loop ->cancelTimer ($ timer );
62
+ });
28
63
$ buffer = '' ;
29
64
$ maxSize = $ this ->maxSize ;
30
65
$ that = $ this ;
31
- $ conn ->on ('data ' , $ fn = function ($ data ) use (&$ buffer , &$ fn , $ conn , $ maxSize , $ that ) {
66
+ $ conn ->on ('data ' , $ fn = function ($ data ) use (&$ buffer , &$ fn , $ conn , $ maxSize , $ that , $ loop , &$ timer , $ createTimer ) {
67
+ $ loop ->cancelTimer ($ timer );
68
+ $ timer = $ createTimer ();
32
69
// append chunk of data to buffer and look for end of request headers
33
70
$ buffer .= $ data ;
34
71
$ endOfHeader = \strpos ($ buffer , "\r\n\r\n" );
@@ -42,6 +79,7 @@ public function handle(ConnectionInterface $conn)
42
79
new \OverflowException ("Maximum header size of {$ maxSize } exceeded. " , 431 ),
43
80
$ conn
44
81
));
82
+ $ loop ->cancelTimer ($ timer );
45
83
return ;
46
84
}
47
85
@@ -66,6 +104,7 @@ public function handle(ConnectionInterface $conn)
66
104
$ exception ,
67
105
$ conn
68
106
));
107
+ $ loop ->cancelTimer ($ timer );
69
108
return ;
70
109
}
71
110
@@ -104,6 +143,7 @@ public function handle(ConnectionInterface $conn)
104
143
if ($ contentLength === 0 ) {
105
144
$ stream ->emit ('end ' );
106
145
$ stream ->close ();
146
+ $ loop ->cancelTimer ($ timer );
107
147
}
108
148
});
109
149
}
0 commit comments