Completed
Pull Request — master (#243)
by Дмитрий
05:05
created

V13::sendFrame()   C

Complexity

Conditions 9
Paths 26

Size

Total Lines 69
Code Lines 49

Duplication

Lines 21
Ratio 30.43 %

Importance

Changes 3
Bugs 2 Features 0
Metric Value
cc 9
eloc 49
c 3
b 2
f 0
nc 26
nop 3
dl 21
loc 69
rs 6.2192

How to fix   Long Method   

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
    /**
33
     * Sends a handshake message reply
34
     * @param string Received data (no use in this class)
35
     * @return boolean OK?
36
     */
37
    public function sendHandshakeReply($extraHeaders = '')
38
    {
39
        if (!isset($this->server['HTTP_SEC_WEBSOCKET_KEY']) || !isset($this->server['HTTP_SEC_WEBSOCKET_VERSION'])) {
40
            return false;
41
        }
42
        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...
43
            return false;
44
        }
45
46
        if (isset($this->server['HTTP_ORIGIN'])) {
47
            $this->server['HTTP_SEC_WEBSOCKET_ORIGIN'] = $this->server['HTTP_ORIGIN'];
48
        }
49
        if (!isset($this->server['HTTP_SEC_WEBSOCKET_ORIGIN'])) {
50
            $this->server['HTTP_SEC_WEBSOCKET_ORIGIN'] = '';
51
        }
52
        $this->write(
53
            "HTTP/1.1 101 Switching Protocols\r\n"
54
            . "Upgrade: WebSocket\r\n"
55
            . "Connection: Upgrade\r\n"
56
            . "Date: " . date('r') . "\r\n"
57
            . "Sec-WebSocket-Origin: " . $this->server['HTTP_SEC_WEBSOCKET_ORIGIN'] . "\r\n"
58
            . "Sec-WebSocket-Location: ws://" . $this->server['HTTP_HOST'] . $this->server['REQUEST_URI'] . "\r\n"
59
            . "Sec-WebSocket-Accept: "
60
            . base64_encode(
61
                sha1(
62
                    trim(
63
                        $this->server['HTTP_SEC_WEBSOCKET_KEY']
64
                    )
65
                    . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
66
                    true
67
                )
68
            ) . "\r\n"
69
        );
70
        if (isset($this->server['HTTP_SEC_WEBSOCKET_PROTOCOL'])) {
71
            $this->writeln("Sec-WebSocket-Protocol: " . $this->server['HTTP_SEC_WEBSOCKET_PROTOCOL']);
72
        }
73
74
        if ($this->pool->config->expose->value) {
75
            $this->writeln('X-Powered-By: phpDaemon/' . Daemon::$version);
76
        }
77
78
        $this->writeln($extraHeaders);
79
80
        return true;
81
    }
82
83
84
    /**
85
     * Sends a frame.
86
     * @param  string $data Frame's data.
87
     * @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...
88
     * @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...
89
     * @callback $cb ( )
90
     * @return boolean         Success.
91
     */
92
    public function sendFrame($data, $type = null, $cb = null)
93
    {
94
        if (!$this->handshaked) {
95
            return false;
96
        }
97
98
        if ($this->finished && $type !== 'CONNCLOSE') {
99
            return false;
100
        }
101
102
        /*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...
103
            //$data = gzcompress($data, $this->outgoingCompression);
104
            //$rsv1 = 1;
105
        }*/
106
107
        $fin = 1;
108
        $rsv1 = 0;
109
        $rsv2 = 0;
110
        $rsv3 = 0;
111
        $this->write(
112
            chr(
113
                bindec(
114
                    $fin . $rsv1 . $rsv2 . $rsv3
115
                    . str_pad(
116
                        decbin(
117
                            $this->getFrameType($type)
118
                        ),
119
                        4,
120
                        '0',
121
                        STR_PAD_LEFT
122
                    )
123
                )
124
            )
125
        )
126
        ;
127
        $dataLength = mb_orig_strlen($data);
128
        $isMasked = false;
129
        $isMaskedInt = $isMasked ? 128 : 0;
130
        if ($dataLength <= 125) {
131
            $this->write(chr($dataLength + $isMaskedInt));
132
        } elseif ($dataLength <= 65535) {
133
            $this->write(chr(126 + $isMaskedInt) . // 126 + 128
134
                chr($dataLength >> 8) .
135
                chr($dataLength & 0xFF));
136 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...
137
            $this->write(chr(127 + $isMaskedInt) . // 127 + 128
138
                chr($dataLength >> 56) .
139
                chr($dataLength >> 48) .
140
                chr($dataLength >> 40) .
141
                chr($dataLength >> 32) .
142
                chr($dataLength >> 24) .
143
                chr($dataLength >> 16) .
144
                chr($dataLength >> 8) .
145
                chr($dataLength & 0xFF));
146
        }
147 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...
148
            $mask = chr(mt_rand(0, 0xFF)) .
149
                chr(mt_rand(0, 0xFF)) .
150
                chr(mt_rand(0, 0xFF)) .
151
                chr(mt_rand(0, 0xFF));
152
            $this->write($mask . $this->mask($data, $mask));
153
        } else {
154
            $this->write($data);
155
        }
156
        if ($cb !== null) {
157
            $this->onWriteOnce($cb);
158
        }
159
        return true;
160
    }
161
162
    /**
163
     * Apply mask
164
     * @param $data
165
     * @param string|false $mask
166
     * @return mixed
167
     */
168
    public function mask($data, $mask)
169
    {
170
        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 168 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...
171
            $data[$i] = $data[$i] ^ $mask[$i % $ml];
172
        }
173
        return $data;
174
    }
175
176
    /**
177
     * Called when new data received
178
     * @see http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10#page-16
179
     * @return void
180
     */
181
    public function onRead()
182
    {
183
        if ($this->state === self::STATE_PREHANDSHAKE) {
184
            if (!$this->handshake()) {
185
                return;
186
            }
187
        }
188
        if ($this->state === self::STATE_HANDSHAKED) {
189
            while (($buflen = $this->getInputLength()) >= 2) {
190
                $first = ord($this->look(1)); // first byte integer (fin, opcode)
191
                $firstBits = decbin($first);
192
                $opcode = (int)bindec(substr($firstBits, 4, 4));
193
                if ($opcode === 0x8) { // CLOSE
194
                    $this->finish();
195
                    return;
196
                }
197
                $opcodeName = isset(static::$opcodes[$opcode]) ? static::$opcodes[$opcode] : false;
198
                if (!$opcodeName) {
199
                    Daemon::log(get_class($this) . ': Undefined opcode ' . $opcode);
200
                    $this->finish();
201
                    return;
202
                }
203
                $second = ord($this->look(1, 1)); // second byte integer (masked, payload length)
204
                $fin = (bool)($first >> 7);
205
                $isMasked = (bool)($second >> 7);
206
                $dataLength = $second & 0x7f;
207
                $p = 2;
208
                if ($dataLength === 0x7e) { // 2 bytes-length
209
                    if ($buflen < $p + 2) {
210
                        return; // not enough data yet
211
                    }
212
                    $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...
213
                    $p += 2;
214
                } elseif ($dataLength === 0x7f) { // 8 bytes-length
215
                    if ($buflen < $p + 8) {
216
                        return; // not enough data yet
217
                    }
218
                    $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...
219
                    $p += 8;
220
                }
221
                if ($this->pool->maxAllowedPacket <= $dataLength) {
222
                    // Too big packet
223
                    $this->finish();
224
                    return;
225
                }
226
                if ($isMasked) {
227
                    if ($buflen < $p + 4) {
228
                        return; // not enough data yet
229
                    }
230
                    $mask = $this->look(4, $p);
231
                    $p += 4;
232
                }
233
                if ($buflen < $p + $dataLength) {
234
                    return; // not enough data yet
235
                }
236
                $this->drain($p);
237
                $data = $this->read($dataLength);
238
                if ($isMasked) {
239
                    $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...
240
                }
241
                //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...
242
                /*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...
243
                    $data = gzuncompress($data, $this->pool->maxAllowedPacket);
244
                }*/
245
                if (!$fin) {
246
                    $this->framebuf .= $data;
247
                } else {
248
                    $this->onFrame($this->framebuf . $data, $opcodeName);
249
                    $this->framebuf = '';
250
                }
251
            }
252
        }
253
    }
254
}
255