Completed
Push — master ( 07e932...701852 )
by Vasily
04:00
created

V0::sendFrame()   C

Complexity

Conditions 10
Paths 15

Size

Total Lines 48
Code Lines 29

Duplication

Lines 48
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 48
loc 48
rs 5.3455
cc 10
eloc 29
nc 15
nop 3

How to fix   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 View Code Duplication
	public function sendFrame($data, $type = null, $cb = null) {
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...
108
		if (!$this->handshaked) {
109
			return false;
110
		}
111
112
		if ($this->finished && $type !== 'CONNCLOSE') {
113
			return false;
114
		}
115
		if ($type === 'CONNCLOSE') {
116
			if ($cb !== null) {
117
				call_user_func($cb, $this);
118
				return true;
119
			}
120
		}
121
122
		$type = $this->getFrameType($type);
123
		// Binary
124
		if (($type & self::BINARY) === self::BINARY) {
125
			$n   = strlen($data);
126
			$len = '';
127
			$pos = 0;
128
129
			char:
130
131
			++$pos;
132
			$c = $n >> 0 & 0x7F;
133
			$n >>= 7;
134
135
			if ($pos !== 1) {
136
				$c += 0x80;
137
			}
138
139
			if ($c !== 0x80) {
140
				$len = chr($c) . $len;
141
				goto char;
142
			};
143
144
			$this->write(chr(self::BINARY) . $len . $data);
145
		}
146
		// String
147
		else {
148
			$this->write(chr(self::STRING) . $data . "\xFF");
149
		}
150
		if ($cb !== null) {
151
			$this->onWriteOnce($cb);
152
		}
153
		return true;
154
	}
155
156
	/**
157
	 * Called when new data received 
158
	 * @return void
159
	 */
160
	public function onRead() {
161
		if ($this->state === self::STATE_PREHANDSHAKE) {
162
			if ($this->getInputLength() < 8) {
163
				return;
164
			}
165
			$this->key = $this->readUnlimited();
166
			$this->handshake();
167
		}
168
		if ($this->state === self::STATE_HANDSHAKED) {
169 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...
170
				$hdr = $this->look(10);
171
				$frametype = ord(binarySubstr($hdr, 0, 1));
172
				if (($frametype & 0x80) === 0x80) {
173
					$len = 0;
174
					$i = 0;
175
					do {
176
						if ($buflen < $i + 1) {
177
							// not enough data yet
178
							return;
179
						}
180
						$b = ord(binarySubstr($hdr, ++$i, 1));
181
						$n = $b & 0x7F;
182
						$len *= 0x80;
183
						$len += $n;
184
					} while ($b > 0x80);
185
186
					if ($this->pool->maxAllowedPacket <= $len) {
187
						// Too big packet
188
						$this->finish();
189
						return;
190
					}
191
192
					if ($buflen < $len + $i + 1) {
193
						// not enough data yet
194
						return;
195
					}
196
					$this->drain($i + 1);
197
					$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...
198
				} else {
199
					if (($p = $this->search("\xFF")) !== false) {
200
						if ($this->pool->maxAllowedPacket <= $p - 1) {
201
							// Too big packet
202
							$this->finish();
203
							return;
204
						}
205
						$this->drain(1);
206
						$data = $this->read($p);
207
						$this->drain(1);
208
						$this->onFrame($data, 'STRING');
0 ignored issues
show
Security Bug introduced by
It seems like $data defined by $this->read($p) on line 206 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...
209
					} else {
210
						if ($this->pool->maxAllowedPacket < $buflen - 1) {
211
							// Too big packet
212
							$this->finish();
213
							return;
214
						}
215
						// not enough data yet
216
						return;
217
					}
218
				}
219
			}
220
		}
221
	}
222
}