Completed
Push — master ( c55d2b...07e932 )
by Vasily
03:55
created

V0::onRead()   C

Complexity

Conditions 13
Paths 21

Size

Total Lines 62
Code Lines 42

Duplication

Lines 51
Ratio 82.26 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 51
loc 62
rs 6.1884
cc 13
eloc 42
nc 21
nop 0

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
7
/**
8
 * WebSocket protocol hixie-76
9
 * @see    http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
10
 */
11
12
class V0 extends Connection {
13
14
	const STRING = 0x00;
15
	const BINARY = 0x80;
16
17
	protected $key;
18
19
	/**
20
	 * Sends a handshake message reply
21
	 * @param string Received data (no use in this class)
22
	 * @return boolean OK?
23
	 */
24
	public function sendHandshakeReply($extraHeaders = '') {
25 View Code Duplication
		if (!isset($this->server['HTTP_SEC_WEBSOCKET_KEY1']) || !isset($this->server['HTTP_SEC_WEBSOCKET_KEY2'])) {
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...
26
			return false;
27
		}
28
		$final_key = $this->_computeFinalKey($this->server['HTTP_SEC_WEBSOCKET_KEY1'], $this->server['HTTP_SEC_WEBSOCKET_KEY2'], $this->key);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 135 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...
29
		$this->key = null;
30
31
		if (!$final_key) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $final_key of type false|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
32
			return false;
33
		}
34
35
		if (!isset($this->server['HTTP_SEC_WEBSOCKET_ORIGIN'])) {
36
			$this->server['HTTP_SEC_WEBSOCKET_ORIGIN'] = '';
37
		}
38
39
		$this->write("HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
40
				. "Upgrade: WebSocket\r\n"
41
				. "Connection: Upgrade\r\n"
42
				. "Sec-WebSocket-Origin: " . $this->server['HTTP_ORIGIN'] . "\r\n"
43
				. "Sec-WebSocket-Location: ws://" . $this->server['HTTP_HOST'] . $this->server['REQUEST_URI'] . "\r\n");
44
		if ($this->pool->config->expose->value) {
45
			$this->writeln('X-Powered-By: phpDaemon/' . Daemon::$version);
46
		}
47
		if (isset($this->server['HTTP_SEC_WEBSOCKET_PROTOCOL'])) {
48
			$this->writeln("Sec-WebSocket-Protocol: " . $this->server['HTTP_SEC_WEBSOCKET_PROTOCOL']);
49
		}
50
		$this->write($extraHeaders . "\r\n" . $final_key);
51
		return true;
52
	}
53
54
	/**
55
	 * Computes final key for Sec-WebSocket.
56
	 * @param string Key1
57
	 * @param string Key2
58
	 * @param string Data
59
	 * @return string Result
0 ignored issues
show
Documentation introduced by
Should the return type not be false|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
60
	 */
61
	protected function _computeFinalKey($key1, $key2, $data) {
62
		if (strlen($data) < 8) {
63
			Daemon::$process->log(get_class($this) . '::' . __METHOD__ . ' : Invalid handshake data for client "' . $this->addr . '"');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 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...
64
			return false;
65
		}
66
		return md5($this->_computeKey($key1) . $this->_computeKey($key2) . binarySubstr($data, 0, 8), true);
67
	}
68
69
	/**
70
	 * Computes key for Sec-WebSocket.
71
	 * @param string Key
72
	 * @return string Result
73
	 */
74 View Code Duplication
	protected function _computeKey($key) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
75
		$spaces = 0;
76
		$digits = '';
77
78
		for ($i = 0, $s = strlen($key); $i < $s; ++$i) {
79
			$c = binarySubstr($key, $i, 1);
80
81
			if ($c === "\x20") {
82
				++$spaces;
83
			}
84
			elseif (ctype_digit($c)) {
85
				$digits .= $c;
86
			}
87
		}
88
89
		if ($spaces > 0) {
90
			$result = (float)floor($digits / $spaces);
91
		}
92
		else {
93
			$result = (float)$digits;
94
		}
95
96
		return pack('N', $result);
97
	}
98
99
	/**
100
	 * Sends a frame.
101
	 * @param  string   $data  Frame's data.
102
	 * @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...
103
	 * @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...
104
	 * @callback $cb ( )
105
	 * @return boolean         Success.
106
	 */
107
	public function sendFrame($data, $type = null, $cb = null) {
108
		// Binary
109
		$type = $this->getFrameType($type);
110 View Code Duplication
		if (($type & self::BINARY) === self::BINARY) {
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...
111
			$n   = strlen($data);
112
			$len = '';
113
			$pos = 0;
114
115
			char:
116
117
			++$pos;
118
			$c = $n >> 0 & 0x7F;
119
			$n >>= 7;
120
121
			if ($pos !== 1) {
122
				$c += 0x80;
123
			}
124
125
			if ($c !== 0x80) {
126
				$len = chr($c) . $len;
127
				goto char;
128
			};
129
130
			$this->write(chr(self::BINARY) . $len . $data);
131
		}
132
		// String
133
		else {
134
			$this->write(chr(self::STRING) . $data . "\xFF");
135
		}
136
		if ($cb !== null) {
137
			$this->onWriteOnce($cb);
138
		}
139
		return true;
140
	}
141
142
	/**
143
	 * Called when new data received 
144
	 * @return void
145
	 */
146
	public function onRead() {
147
		if ($this->state === self::STATE_PREHANDSHAKE) {
148
			if ($this->getInputLength() < 8) {
149
				return;
150
			}
151
			$this->key = $this->readUnlimited();
152
			$this->handshake();
153
		}
154
		if ($this->state === self::STATE_HANDSHAKED) {
155 View Code Duplication
			while (($buflen = $this->getInputLength()) >= 2) {
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...
156
				$hdr = $this->look(10);
157
				$frametype = ord(binarySubstr($hdr, 0, 1));
158
				if (($frametype & 0x80) === 0x80) {
159
					$len = 0;
160
					$i = 0;
161
					do {
162
						if ($buflen < $i + 1) {
163
							// not enough data yet
164
							return;
165
						}
166
						$b = ord(binarySubstr($hdr, ++$i, 1));
167
						$n = $b & 0x7F;
168
						$len *= 0x80;
169
						$len += $n;
170
					} while ($b > 0x80);
171
172
					if ($this->pool->maxAllowedPacket <= $len) {
173
						// Too big packet
174
						$this->finish();
175
						return;
176
					}
177
178
					if ($buflen < $len + $i + 1) {
179
						// not enough data yet
180
						return;
181
					}
182
					$this->drain($i + 1);
183
					$this->onFrame($this->read($len), 'BINARY');
0 ignored issues
show
Security Bug introduced by
It seems like $this->read($len) targeting PHPDaemon\Network\IOStream::read() can also be of type false; however, PHPDaemon\Servers\WebSocket\Connection::onFrame() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
184
				} else {
185
					if (($p = $this->search("\xFF")) !== false) {
186
						if ($this->pool->maxAllowedPacket <= $p - 1) {
187
							// Too big packet
188
							$this->finish();
189
							return;
190
						}
191
						$this->drain(1);
192
						$data = $this->read($p);
193
						$this->drain(1);
194
						$this->onFrame($data, 'STRING');
0 ignored issues
show
Security Bug introduced by
It seems like $data defined by $this->read($p) on line 192 can also be of type false; however, PHPDaemon\Servers\WebSocket\Connection::onFrame() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
195
					} else {
196
						if ($this->pool->maxAllowedPacket < $buflen - 1) {
197
							// Too big packet
198
							$this->finish();
199
							return;
200
						}
201
						// not enough data yet
202
						return;
203
					}
204
				}
205
			}
206
		}
207
	}
208
}