Completed
Push — master ( c2c781...2acdcd )
by Vasily
02:43
created

V13::onRead()   F

Complexity

Conditions 19
Paths 315

Size

Total Lines 80
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 19
eloc 56
c 1
b 0
f 0
nc 315
nop 0
dl 0
loc 80
rs 3.8268

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace PHPDaemon\Servers\WebSocket\Protocols;
3
4
use PHPDaemon\Core\Daemon;
5
use PHPDaemon\Servers\WebSocket\Connection;
6
use PHPDaemon\Utils\Binary;
7
8
/**
9
 * Websocket protocol 13
10
 * @see    http://datatracker.ietf.org/doc/rfc6455/?include_text=1
11
 */
12
class V13 extends Connection
13
{
14
    const CONTINUATION = 0;
15
    const STRING = 0x1;
16
    const BINARY = 0x2;
17
    const CONNCLOSE = 0x8;
18
    const PING = 0x9;
19
    const PONG = 0xA;
20
    protected static $opcodes = [
21
        0 => 'CONTINUATION',
22
        0x1 => 'STRING',
23
        0x2 => 'BINARY',
24
        0x8 => 'CONNCLOSE',
25
        0x9 => 'PING',
26
        0xA => 'PONG',
27
    ];
28
    protected $outgoingCompression = 0;
29
30
    protected $framebuf = '';
31
32
    protected $firstFrameOpcodeName;
33
34
    /**
35
     * Sends a handshake message reply
36
     * @param string Received data (no use in this class)
37
     * @return boolean OK?
38
     */
39
    public function sendHandshakeReply($extraHeaders = '')
40
    {
41
        if (!isset($this->server['HTTP_SEC_WEBSOCKET_KEY']) || !isset($this->server['HTTP_SEC_WEBSOCKET_VERSION'])) {
42
            return false;
43
        }
44
        if ($this->server['HTTP_SEC_WEBSOCKET_VERSION'] !== '13' && $this->server['HTTP_SEC_WEBSOCKET_VERSION'] !== '8') {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
45
            return false;
46
        }
47
48
        if (isset($this->server['HTTP_ORIGIN'])) {
49
            $this->server['HTTP_SEC_WEBSOCKET_ORIGIN'] = $this->server['HTTP_ORIGIN'];
50
        }
51
        if (!isset($this->server['HTTP_SEC_WEBSOCKET_ORIGIN'])) {
52
            $this->server['HTTP_SEC_WEBSOCKET_ORIGIN'] = '';
53
        }
54
        $this->write(
55
            "HTTP/1.1 101 Switching Protocols\r\n"
56
            . "Upgrade: WebSocket\r\n"
57
            . "Connection: Upgrade\r\n"
58
            . "Date: " . date('r') . "\r\n"
59
            . "Sec-WebSocket-Origin: " . $this->server['HTTP_SEC_WEBSOCKET_ORIGIN'] . "\r\n"
60
            . "Sec-WebSocket-Location: ws://" . $this->server['HTTP_HOST'] . $this->server['REQUEST_URI'] . "\r\n"
61
            . "Sec-WebSocket-Accept: "
62
            . base64_encode(
63
                sha1(
64
                    trim(
65
                        $this->server['HTTP_SEC_WEBSOCKET_KEY']
66
                    )
67
                    . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
68
                    true
69
                )
70
            ) . "\r\n"
71
        );
72
        if (isset($this->server['HTTP_SEC_WEBSOCKET_PROTOCOL'])) {
73
            $this->writeln("Sec-WebSocket-Protocol: " . $this->server['HTTP_SEC_WEBSOCKET_PROTOCOL']);
74
        }
75
76
        if ($this->pool->config->expose->value) {
77
            $this->writeln('X-Powered-By: phpDaemon/' . Daemon::$version);
78
        }
79
80
        $this->writeln($extraHeaders);
81
82
        return true;
83
    }
84
85
86
    /**
87
     * Sends a frame.
88
     * @param  string $data Frame's data.
89
     * @param  string $type Frame's type. ("STRING" OR "BINARY")
0 ignored issues
show
Documentation introduced by
Should the type for parameter $type not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
90
     * @param  callable $cb Optional. Callback called when the frame is received by client.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cb not be callable|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
91
     * @callback $cb ( )
92
     * @return boolean         Success.
93
     */
94
    public function sendFrame($data, $type = null, $cb = null)
95
    {
96
        if (!$this->handshaked) {
97
            return false;
98
        }
99
100
        if ($this->finished && $type !== 'CONNCLOSE') {
101
            return false;
102
        }
103
104
        /*if (in_array($type, ['STRING', 'BINARY']) && ($this->outgoingCompression > 0) && in_array('deflate-frame', $this->extensions)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 138 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
105
            //$data = gzcompress($data, $this->outgoingCompression);
106
            //$rsv1 = 1;
107
        }*/
108
109
        $fin = 1;
110
        $rsv1 = 0;
111
        $rsv2 = 0;
112
        $rsv3 = 0;
113
        $this->write(
114
            chr(
115
                bindec(
116
                    $fin . $rsv1 . $rsv2 . $rsv3
117
                    . str_pad(
118
                        decbin(
119
                            $this->getFrameType($type)
120
                        ),
121
                        4,
122
                        '0',
123
                        STR_PAD_LEFT
124
                    )
125
                )
126
            )
127
        );
128
        $dataLength = mb_orig_strlen($data);
129
        $isMasked = false;
130
        $isMaskedInt = $isMasked ? 128 : 0;
131
        if ($dataLength <= 125) {
132
            $this->write(chr($dataLength + $isMaskedInt));
133
        } elseif ($dataLength <= 65535) {
134
            $this->write(chr(126 + $isMaskedInt) . // 126 + 128
135
                chr($dataLength >> 8) .
136
                chr($dataLength & 0xFF));
137 View Code Duplication
        } else {
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...
138
            $this->write(chr(127 + $isMaskedInt) . // 127 + 128
139
                chr($dataLength >> 56) .
140
                chr($dataLength >> 48) .
141
                chr($dataLength >> 40) .
142
                chr($dataLength >> 32) .
143
                chr($dataLength >> 24) .
144
                chr($dataLength >> 16) .
145
                chr($dataLength >> 8) .
146
                chr($dataLength & 0xFF));
147
        }
148 View Code Duplication
        if ($isMasked) {
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...
149
            $mask = chr(mt_rand(0, 0xFF)) .
150
                chr(mt_rand(0, 0xFF)) .
151
                chr(mt_rand(0, 0xFF)) .
152
                chr(mt_rand(0, 0xFF));
153
            $this->write($mask . $this->mask($data, $mask));
154
        } else {
155
            $this->write($data);
156
        }
157
        if ($cb !== null) {
158
            $this->onWriteOnce($cb);
159
        }
160
        return true;
161
    }
162
163
    /**
164
     * Apply mask
165
     * @param $data
166
     * @param string|false $mask
167
     * @return mixed
168
     */
169
    public function mask($data, $mask)
170
    {
171
        for ($i = 0, $l = mb_orig_strlen($data), $ml = mb_orig_strlen($mask); $i < $l; $i++) {
0 ignored issues
show
Bug introduced by
It seems like $mask defined by parameter $mask on line 169 can also be of type false; however, mb_orig_strlen() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
172
            $data[$i] = $data[$i] ^ $mask[$i % $ml];
173
        }
174
        return $data;
175
    }
176
177
    /**
178
     * Called when new data received
179
     * @see http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10#page-16
180
     * @return void
181
     */
182
    public function onRead()
183
    {
184
        if ($this->state === self::STATE_PREHANDSHAKE) {
185
            if (!$this->handshake()) {
186
                return;
187
            }
188
        }
189
        if ($this->state === self::STATE_HANDSHAKED) {
190
            while (($buflen = $this->getInputLength()) >= 2) {
191
                $first = ord($this->look(1)); // first byte integer (fin, opcode)
192
                $firstBits = decbin($first);
193
                $opcode = (int)bindec(substr($firstBits, 4, 4));
194
                if ($opcode === 0x8) { // CLOSE
195
                    $this->finish();
196
                    return;
197
                }
198
                $opcodeName = isset(static::$opcodes[$opcode]) ? static::$opcodes[$opcode] : false;
199
                if (!$opcodeName) {
200
                    Daemon::log(get_class($this) . ': Undefined opcode ' . $opcode);
201
                    $this->finish();
202
                    return;
203
                }
204
                if ($this->firstFrameOpcodeName === null) {
205
                    $this->firstFrameOpcodeName = $opcodeName;
206
                }
207
                $second = ord($this->look(1, 1)); // second byte integer (masked, payload length)
208
                $fin = (bool)($first >> 7);
209
                $isMasked = (bool)($second >> 7);
210
                $dataLength = $second & 0x7f;
211
                $p = 2;
212
                if ($dataLength === 0x7e) { // 2 bytes-length
213
                    if ($buflen < $p + 2) {
214
                        return; // not enough data yet
215
                    }
216
                    $dataLength = Binary::bytes2int($this->look(2, $p), false);
0 ignored issues
show
Security Bug introduced by
It seems like $this->look(2, $p) targeting PHPDaemon\Network\IOStream::look() can also be of type false; however, PHPDaemon\Utils\Binary::bytes2int() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
217
                    $p += 2;
218
                } elseif ($dataLength === 0x7f) { // 8 bytes-length
219
                    if ($buflen < $p + 8) {
220
                        return; // not enough data yet
221
                    }
222
                    $dataLength = Binary::bytes2int($this->look(8, $p));
0 ignored issues
show
Security Bug introduced by
It seems like $this->look(8, $p) targeting PHPDaemon\Network\IOStream::look() can also be of type false; however, PHPDaemon\Utils\Binary::bytes2int() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
223
                    $p += 8;
224
                }
225
                if ($this->pool->maxAllowedPacket <= $dataLength) {
226
                    // Too big packet
227
                    Daemon::log(get_class($this) . ': MaxAllowedPacket limit exceeded. Packet size ' . $dataLength . ' bytes when limit ' . $this->pool->maxAllowedPacket . ' bytes');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 182 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
228
                    $this->finish();
229
                    return;
230
                }
231
                // Extend buffer size to accommodate all data
232
                $this->setWatermark(null, $dataLength + 100);
233
                if ($isMasked) {
234
                    if ($buflen < $p + 4) {
235
                        return; // not enough data yet
236
                    }
237
                    $mask = $this->look(4, $p);
238
                    $p += 4;
239
                }
240
                if ($buflen < $p + $dataLength) {
241
                    return; // not enough data yet
242
                }
243
                $this->drain($p);
244
                $data = $this->read($dataLength);
245
                if ($isMasked) {
246
                    $data = $this->mask($data, $mask);
0 ignored issues
show
Bug introduced by
The variable $mask does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
247
                }
248
                //Daemon::log(Debug::dump(array('ext' => $this->extensions, 'rsv1' => $firstBits[1], 'data' => Debug::exportBytes($data))));
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 140 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
249
                /*if ($firstBits[1] && in_array('deflate-frame', $this->extensions)) { // deflate frame
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
250
                    $data = gzuncompress($data, $this->pool->maxAllowedPacket);
251
                }*/
252
                if (!$fin) {
253
                    $this->framebuf .= $data;
254
                } else {
255
                    $this->onFrame($this->framebuf . $data, $this->firstFrameOpcodeName);
256
                    $this->firstFrameOpcodeName = null;
257
                    $this->framebuf = '';
258
                }
259
            }
260
        }
261
    }
262
}
263