Connection::badRequest()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
nc 1
nop 1
1
<?php
2
namespace PHPDaemon\Servers\FastCGI;
3
4
use PHPDaemon\Core\Daemon;
5
use PHPDaemon\Request\IRequestUpstream;
6
7
/**
8
 * @package    NetworkServers
9
 * @subpackage Base
10
 * @author     Vasily Zorin <[email protected]>
11
 */
12
class Connection extends \PHPDaemon\Network\Connection implements IRequestUpstream
13
{
14
    const FCGI_BEGIN_REQUEST = 1;
15
    const FCGI_ABORT_REQUEST = 2;
16
    const FCGI_END_REQUEST = 3;
17
    const FCGI_PARAMS = 4;
18
    const FCGI_STDIN = 5;
19
    const FCGI_STDOUT = 6;
20
    const FCGI_STDERR = 7;
21
    const FCGI_DATA = 8;
22
    const FCGI_GET_VALUES = 9;
23
    const FCGI_GET_VALUES_RESULT = 10;
24
    const FCGI_UNKNOWN_TYPE = 11;
25
    const FCGI_RESPONDER = 1;
26
    const FCGI_AUTHORIZER = 2;
27
    const FCGI_FILTER = 3;
28
    const STATE_CONTENT = 1;
29
    const STATE_PADDING = 2;
30
    protected static $roles = [
31
        self::FCGI_RESPONDER => 'FCGI_RESPONDER',
32
        self::FCGI_AUTHORIZER => 'FCGI_AUTHORIZER',
33
        self::FCGI_FILTER => 'FCGI_FILTER',
34
    ];
35
    protected static $requestTypes = [
36
        self::FCGI_BEGIN_REQUEST => 'FCGI_BEGIN_REQUEST',
37
        self::FCGI_ABORT_REQUEST => 'FCGI_ABORT_REQUEST',
38
        self::FCGI_END_REQUEST => 'FCGI_END_REQUEST',
39
        self::FCGI_PARAMS => 'FCGI_PARAMS',
40
        self::FCGI_STDIN => 'FCGI_STDIN',
41
        self::FCGI_STDOUT => 'FCGI_STDOUT',
42
        self::FCGI_STDERR => 'FCGI_STDERR',
43
        self::FCGI_DATA => 'FCGI_DATA',
44
        self::FCGI_GET_VALUES => 'FCGI_GET_VALUES',
45
        self::FCGI_GET_VALUES_RESULT => 'FCGI_GET_VALUES_RESULT',
46
        self::FCGI_UNKNOWN_TYPE => 'FCGI_UNKNOWN_TYPE',
47
    ];
48
    public $timeout = 180;
49
    /**
50
     * @var integer initial value of the minimal amout of bytes in buffer
51
     */
52
    protected $lowMark = 8;
53
    /**
54
     * @var integer initial value of the maximum amout of bytes in buffer
55
     */
56
    protected $highMark = 0xFFFFFF;
57
    protected $requests = [];
58
    protected $header;
59
    protected $content;
60
61
    /**
62
     * Is this upstream suitable for sendfile()?
63
     * @return bool
64
     */
65
    public function checkSendfileCap()
66
    {
67
        // @todo DISCUSS
68
        return false;
69
    }
70
71
    /**
72
     * Is this upstream suitable for chunked encoding?
73
     * @return bool
74
     */
75
    public function checkChunkedEncCap()
76
    {
77
        // @todo DISCUSS
78
        return false;
79
    }
80
81
    /**
82
     * @TODO
83
     * @return integer
84
     */
85
    public function getKeepaliveTimeout()
86
    {
87
        return $this->pool->config->keepalive->value;
88
    }
89
90
    /**
91
     * Called when new data received
92
     * @return void
93
     */
94
    public function onRead()
95
    {
96
        start:
97
        if ($this->state === self::STATE_ROOT) {
98
            $header = $this->readExact(8);
99
100
            if ($header === false) {
101
                return;
102
            }
103
104
            $this->header = unpack('Cver/Ctype/nreqid/nconlen/Cpadlen/Creserved', $header);
105
106
            if ($this->header['conlen'] > 0) {
107
                $this->setWatermark($this->header['conlen'], $this->header['conlen']);
108
            }
109
            $type = $this->header['type'];
110
            $this->header['ttype'] = isset(self::$requestTypes[$type]) ? self::$requestTypes[$type] : $type;
111
            $rid = $this->header['reqid'];
112
            $this->state = self::STATE_CONTENT;
113
        } else {
114
            $type = $this->header['type'];
115
            $rid = $this->header['reqid'];
116
        }
117
        if ($this->state === self::STATE_CONTENT) {
118
            $this->content = $this->readExact($this->header['conlen']);
119
120
            if ($this->content === false) {
121
                $this->setWatermark($this->header['conlen'], $this->header['conlen']);
122
                return;
123
            }
124
125
            if ($this->header['padlen'] > 0) {
126
                $this->setWatermark($this->header['padlen'], $this->header['padlen']);
127
            }
128
129
            $this->state = self::STATE_PADDING;
130
        }
131
132
        if ($this->state === self::STATE_PADDING) {
133
            $pad = $this->readExact($this->header['padlen']);
134
135
            if ($pad === false) {
136
                return;
137
            }
138
        }
139
        $this->setWatermark(8, 0xFFFFFF);
140
        $this->state = self::STATE_ROOT;
141
142
//        /*Daemon::log('[DEBUG] FastCGI-record ' . $this->header['ttype'] . '). Request ID: ' . $rid
143
//                . '. Content length: ' . $this->header['conlen'] . ' (' . mb_orig_strlen($this->content) . ') Padding length: ' . $this->header['padlen']
144
//                . ' (' . mb_orig_strlen($pad) . ')');*/
145
146
        if ($type === self::FCGI_BEGIN_REQUEST) {
147
            $u = unpack('nrole/Cflags', $this->content);
148
149
            $req = new \stdClass();
150
            $req->attrs = new \stdClass;
151
            $req->attrs->request = [];
152
            $req->attrs->get = [];
153
            $req->attrs->post = [];
154
            $req->attrs->cookie = [];
155
            $req->attrs->server = [];
156
            $req->attrs->files = [];
157
            $req->attrs->session = null;
158
            $req->attrs->role = self::$roles[$u['role']];
159
            $req->attrs->flags = $u['flags'];
160
            $req->attrs->id = $this->header['reqid'];
161
            $req->attrs->paramsDone = false;
162
            $req->attrs->inputDone = false;
163
            $req->attrs->input = new \PHPDaemon\HTTPRequest\Input();
164
            $req->attrs->chunked = false;
165
            $req->attrs->noHttpVer = true;
166
            $req->queueId = $rid;
167
            $this->requests[$rid] = $req;
168
        } elseif (isset($this->requests[$rid])) {
169
            $req = $this->requests[$rid];
170
        } else {
171
            Daemon::log('Unexpected FastCGI-record #' . $this->header['type'] . ' (' . $this->header['ttype'] . '). Request ID: ' . $rid . '.');
172
            return;
173
        }
174
175
        if ($type === self::FCGI_ABORT_REQUEST) {
176
            $req->abort();
177
        } elseif ($type === self::FCGI_PARAMS) {
178
            if ($this->content === '') {
179
                if (!isset($req->attrs->server['REQUEST_TIME'])) {
180
                    $req->attrs->server['REQUEST_TIME'] = time();
181
                }
182
                if (!isset($req->attrs->server['REQUEST_TIME_FLOAT'])) {
183
                    $req->attrs->server['REQUEST_TIME_FLOAT'] = microtime(true);
184
                }
185
                $req->attrs->paramsDone = true;
186
187
                $req = Daemon::$appResolver->getRequest($req, $this);
188
189
                if ($req instanceof \stdClass) {
190
                    $this->endRequest($req, 0, 0);
191
                    unset($this->requests[$rid]);
192
                } else {
193
                    if ($this->pool->config->sendfile->value
194
                        && (
195
                            !$this->pool->config->sendfileonlybycommand->value
196
                            || isset($req->attrs->server['USE_SENDFILE'])
197
                        )
198
                        && !isset($req->attrs->server['DONT_USE_SENDFILE'])
199
                    ) {
200
                        $fn = tempnam(
201
                            $this->pool->config->sendfiledir->value,
202
                            $this->pool->config->sendfileprefix->value
203
                        );
204
205
                        $req->sendfp = fopen($fn, 'wb');
206
                        $req->header('X-Sendfile: ' . $fn);
207
                    }
208
209
                    $this->requests[$rid] = $req;
210
211
                    $req->callInit();
212
                }
213
            } else {
214
                $p = 0;
215
216
                while ($p < $this->header['conlen']) {
217 View Code Duplication
                    if (($namelen = ord($this->content{$p})) < 128) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
218
                        ++$p;
219
                    } else {
220
                        $u = unpack(
221
                            'Nlen',
222
                            chr(ord($this->content{$p}) & 0x7f) . mb_orig_substr($this->content, $p + 1, 3)
223
                        );
224
                        $namelen = $u['len'];
225
                        $p += 4;
226
                    }
227
228 View Code Duplication
                    if (($vlen = ord($this->content{$p})) < 128) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
229
                        ++$p;
230
                    } else {
231
                        $u = unpack(
232
                            'Nlen',
233
                            chr(ord($this->content{$p}) & 0x7f) . mb_orig_substr($this->content, $p + 1, 3)
234
                        );
235
                        $vlen = $u['len'];
236
                        $p += 4;
237
                    }
238
239
                    $req->attrs->server[mb_orig_substr($this->content, $p, $namelen)] = mb_orig_substr(
240
                        $this->content,
241
                        $p + $namelen,
242
                        $vlen
243
                    );
244
                    $p += $namelen + $vlen;
245
                }
246
            }
247
        } elseif ($type === self::FCGI_STDIN) {
248
            if (!$req->attrs->input) {
249
                goto start;
250
            }
251
            if ($this->content === '') {
252
                $req->attrs->input->sendEOF();
253
            } else {
254
                $req->attrs->input->readFromString($this->content);
255
            }
256
        }
257
258
        if ($req->attrs->inputDone && $req->attrs->paramsDone) {
259
            $order = $this->pool->variablesOrder ?: 'GPC';
260
            for ($i = 0, $s = mb_orig_strlen($order); $i < $s; ++$i) {
261
                $char = $order[$i];
262
263
                if ($char === 'G' && is_array($req->attrs->get)) {
264
                    $req->attrs->request += $req->attrs->get;
265
                } elseif ($char === 'P' && is_array($req->attrs->post)) {
266
                    $req->attrs->request += $req->attrs->post;
267
                } elseif ($char === 'C' && is_array($req->attrs->cookie)) {
268
                    $req->attrs->request += $req->attrs->cookie;
269
                }
270
            }
271
272
            Daemon::$process->timeLastActivity = time();
273
        }
274
        goto start;
275
    }
276
277
    /**
278
     * Handles the output from downstream requests
279
     * @param  object $req
280
     * @param  string $appStatus
281
     * @param  string $protoStatus
282
     * @return void
283
     */
284
    public function endRequest($req, $appStatus, $protoStatus)
285
    {
286
        $c = pack('NC', $appStatus, $protoStatus) // app status, protocol status
287
            . "\x00\x00\x00";
288
289
        $this->write(
290
            "\x01" // protocol version
291
            . "\x03" // record type (END_REQUEST)
292
            . pack('nn', $req->attrs->id, mb_orig_strlen($c)) // id, content length
293
            . "\x00" // padding length
294
            . "\x00" // reserved
295
            . $c // content
296
        );
297
298
        if ($protoStatus === -1) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $protoStatus (string) and -1 (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
299
            $this->close();
300
        } elseif (!$this->pool->config->keepalive->value) {
301
            $this->finish();
302
        }
303
    }
304
305
    /**
306
     * Handles the output from downstream requests
307
     * @param  object $req Request
308
     * @param  string $out The output
309
     * @return boolean      Success
310
     */
311
    public function requestOut($req, $out)
312
    {
313
        $cs = $this->pool->config->chunksize->value;
314
        if (mb_orig_strlen($out) > $cs) {
315
            while (($ol = mb_orig_strlen($out)) > 0) {
316
                $l = min($cs, $ol);
317
                if ($this->sendChunk($req, mb_orig_substr($out, 0, $l)) === false) {
318
                    $req->abort();
319
                    return false;
320
                }
321
                $out = mb_orig_substr($out, $l);
322
            }
323
        } elseif ($this->sendChunk($req, $out) === false) {
324
            $req->abort();
325
            return false;
326
        }
327
        return true;
328
    }
329
330
    /**
331
     * Sends a chunk
332
     * @param  object $req Request
333
     * @param  string $chunk Data
334
     * @return bool
335
     */
336
    public function sendChunk($req, $chunk)
337
    {
338
        $packet = "\x01" // protocol version
339
            . "\x06" // record type (STDOUT)
340
            . pack(
341
                'nn',
342
                $req->attrs->id,
343
                mb_orig_strlen($chunk)
344
            ) // id, content length
345
            . "\x00" // padding length
346
            . "\x00";// reserved
347
348
        return $this->write($packet) && $this->write($chunk); // content
349
    }
350
351
    /**
352
     * Frees request
353
     * @param  object $req
354
     */
355
    public function freeRequest($req)
356
    {
357
        $req->attrs->input = null;
358
        unset($this->requests[$req->attrs->id]);
359
    }
360
361
    /**
362
     * Send Bad request
363
     * @param  object $req
364
     * @return void
365
     */
366
    public function badRequest($req)
367
    {
368
        // @TODO: Implement badRequest() method.
369
    }
370
}
371