Passed
Pull Request — master (#81)
by Lito
01:37
created

WebSocketServer::messagesWorker()   C

Complexity

Conditions 12
Paths 24

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 0 Features 0
Metric Value
cc 12
eloc 25
c 9
b 0
f 0
nc 24
nop 1
dl 0
loc 38
rs 6.9666

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
3
namespace WSSC;
4
5
use WSSC\Components\Connection;
6
use WSSC\Components\OriginComponent;
7
use WSSC\Components\ServerConfig;
8
use WSSC\Components\WssMain;
9
use WSSC\Contracts\CommonsContract;
10
use WSSC\Contracts\WebSocket;
11
use WSSC\Contracts\WebSocketServerContract;
12
use WSSC\Exceptions\ConnectionException;
13
use WSSC\Exceptions\WebSocketException;
14
15
/**
16
 * Class WebSocketServer
17
 * @package WSSC
18
 */
19
class WebSocketServer extends WssMain implements WebSocketServerContract
20
{
21
    private const MAX_BYTES_READ = 8192;
22
    private const HEADER_BYTES_READ = 1024;
23
24
    /**
25
     * @var ServerConfig
26
     */
27
    protected ServerConfig $config;
28
29
    /**
30
     * @var array
31
     */
32
    private array $clients = [];
33
34
    /**
35
     * @var array
36
     */
37
    private array $headersUpgrade = [];
38
39
    /**
40
     * @var int
41
     */
42
    private int $maxClients = 1;
43
44
    /**
45
     * @var WebSocket
46
     */
47
    private WebSocket $handler;
48
49
    /**
50
     * @var bool
51
     */
52
    private bool $stepRecursion = true;
53
54
    /**
55
     * @var bool
56
     */
57
    private bool $printException = true;
58
59
    /**
60
     * WebSocketServer constructor.
61
     *
62
     * @param WebSocket $handler
63
     * @param ServerConfig $config
64
     */
65
    public function __construct(
66
        WebSocket $handler,
67
        ServerConfig $config
68
    )
69
    {
70
        ini_set('default_socket_timeout', 5); // this should be >= 5 sec, otherwise there will be broken pipe - tested
71
72
        $this->handler = $handler;
73
        $this->config = $config;
74
        $this->setIsPcntlLoaded(extension_loaded('pcntl'));
75
    }
76
77
    /**
78
     * Configure if error exceptions should be printed
79
     *
80
     * @return self
81
     */
82
    public function printException(bool $printException): self
83
    {
84
        $this->printException = $printException;
85
86
        return $this;
87
    }
88
89
    /**
90
     * Runs main process - Anscestor with server socket on TCP
91
     *
92
     * @throws WebSocketException
93
     * @throws ConnectionException
94
     */
95
    public function run(): void
96
    {
97
        $context = stream_context_create();
98
        $errno = null;
99
        $errorMessage = '';
100
101
        if ($this->config->isSsl() === true) {
102
            stream_context_set_option($context, 'ssl', 'allow_self_signed', $this->config->getAllowSelfSigned());
103
            stream_context_set_option($context, 'ssl', 'verify_peer', false);
104
105
            if (is_file($this->config->getLocalCert()) === false || is_file($this->config->getLocalPk()) === false) {
106
                throw new WebSocketException('SSL certificates must be valid pem files', CommonsContract::SERVER_INVALID_STREAM_CONTEXT);
107
            }
108
            $isLocalCertSet = stream_context_set_option($context, 'ssl', 'local_cert', $this->config->getLocalCert());
109
            $isLocalPkSet = stream_context_set_option($context, 'ssl', 'local_pk', $this->config->getLocalPk());
110
111
            if ($isLocalCertSet === false || $isLocalPkSet === false) {
112
                throw new WebSocketException('SSL certificates could not be set correctly', CommonsContract::SERVER_INVALID_STREAM_CONTEXT);
113
            }
114
        }
115
116
        $server = stream_socket_server("tcp://{$this->config->getHost()}:{$this->config->getPort()}", $errno,
117
            $errorMessage, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
118
119
        if ($server === false) {
120
            throw new WebSocketException('Could not bind to socket: ' . $errno . ' - ' . $errorMessage . PHP_EOL,
121
                CommonsContract::SERVER_COULD_NOT_BIND_TO_SOCKET);
122
        }
123
124
        @cli_set_process_title($this->config->getProcessName());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for cli_set_process_title(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

124
        /** @scrutinizer ignore-unhandled */ @cli_set_process_title($this->config->getProcessName());

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
125
        $this->eventLoop($server);
126
    }
127
128
    /**
129
     * Recursive event loop that input intu recusion by remainder = 0 - thus when N users,
130
     * and when forks equals true which prevents it from infinite recursive iterations
131
     *
132
     * @param resource $server server connection
133
     * @param bool $fork flag to fork or run event loop
134
     * @throws WebSocketException
135
     * @throws ConnectionException
136
     */
137
    private function eventLoop($server, bool $fork = false): void
138
    {
139
        if ($fork === true && $this->isPcntlLoaded()) {
140
            $pid = pcntl_fork();
141
142
            if ($pid) { // run eventLoop in parent        
143
                @cli_set_process_title($this->config->getProcessName());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for cli_set_process_title(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

143
                /** @scrutinizer ignore-unhandled */ @cli_set_process_title($this->config->getProcessName());

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
144
                $this->eventLoop($server);
145
            }
146
        } else {
147
            $this->looping($server);
148
        }
149
    }
150
151
    /**
152
     * @param resource $server
153
     * @throws WebSocketException
154
     * @throws ConnectionException
155
     */
156
    private function looping($server): void
157
    {
158
        while (true) {
159
            $totalClients = count($this->clients) + 1;
160
161
            // maxClients prevents process fork on count down
162
            if ($totalClients > $this->maxClients) {
163
                $this->maxClients = $totalClients;
164
            }
165
166
            $doFork = $this->config->isForking() === true
167
                && $totalClients !== 0 // avoid 0 process creation
168
                && $this->stepRecursion === true // only once
169
                && $this->maxClients === $totalClients // only if stack grows
170
                && $totalClients % $this->config->getClientsPerFork() === 0; // only when N is there
171
            if ($doFork) {
172
                $this->stepRecursion = false;
173
                $this->eventLoop($server, true);
174
            }
175
            $this->lessConnThanProc($totalClients, $this->maxClients);
176
177
            //prepare readable sockets
178
            $readSocks = $this->clients;
179
            $readSocks[] = $server;
180
            $this->cleanSocketResources($readSocks);
181
182
            //start reading and use a large timeout
183
            if (!stream_select($readSocks, $write, $except, $this->config->getStreamSelectTimeout())) {
184
                throw new WebSocketException('something went wrong while selecting',
185
                    CommonsContract::SERVER_SELECT_ERROR);
186
            }
187
188
            //new client
189
            if (in_array($server, $readSocks, false)) {
190
                $this->acceptNewClient($server, $readSocks);
191
                if ($this->config->isCheckOrigin() && $this->config->isOriginHeader() === false) {
192
                    continue;
193
                }
194
            }
195
196
            //message from existing client
197
            $this->messagesWorker($readSocks);
198
        }
199
    }
200
201
    /**
202
     * @param resource $server
203
     * @param array $readSocks
204
     * @throws ConnectionException
205
     */
206
    private function acceptNewClient($server, array &$readSocks): void
207
    {
208
        $newClient = stream_socket_accept($server, -1); // must be 0 to non-block
209
        if ($newClient) {
0 ignored issues
show
introduced by
$newClient is of type resource, thus it always evaluated to false.
Loading history...
210
            if ($this->config->isSsl() === true) {
211
                $isEnabled = stream_socket_enable_crypto($newClient, true, $this->config->getCryptoType());
212
                if ($isEnabled === false) { // couldn't enable crypto - let's try one more time
213
                    return;
214
                }
215
            }
216
217
            // important to read from headers here coz later client will change and there will be only msgs on pipe
218
            $headers = fread($newClient, self::HEADER_BYTES_READ);
219
            if ($this->config->isCheckOrigin()) {
220
                $hasOrigin = (new OriginComponent($this->config, $newClient))->checkOrigin($headers);
221
                $this->config->setOriginHeader($hasOrigin);
222
                if ($hasOrigin === false) {
223
                    return;
224
                }
225
            }
226
227
            if (empty($this->handler->pathParams[0]) === false) {
228
                $this->setPathParams($headers);
229
            }
230
231
            $this->clients[] = $newClient;
232
            $this->stepRecursion = true; // set on new client - remainder % is always 0
233
234
            // trigger OPEN event
235
            $this->handler->onOpen(new Connection($newClient, $this->clients));
236
            $this->handshake($newClient, $headers);
237
        }
238
239
        //delete the server socket from the read sockets
240
        unset($readSocks[array_search($server, $readSocks, false)]);
241
    }
242
243
    /**
244
     * @param array $readSocks
245
     * @uses onPing
246
     * @uses onPong
247
     * @uses onMessage
248
     */
249
    private function messagesWorker(array $readSocks): void
250
    {
251
        foreach ($readSocks as $kSock => $sock) {
252
            $data = $this->decode(fread($sock, self::MAX_BYTES_READ));
253
            if ($data !== null) {
254
                $dataType = null;
255
                $dataPayload = null;
256
                if ($data !== false) { // payload is too large - waiting for remained data
257
                    $dataType = $data['type'];
258
                    $dataPayload = $data['payload'];
259
                }
260
261
                // to manipulate connection through send/close methods via handler, specified in IConnection
262
                $cureentConn = new Connection($sock, $this->clients);
263
                if (empty($data) || $dataType === self::EVENT_TYPE_CLOSE) { // close event triggered from client - browser tab or close socket event
264
                    // trigger CLOSE event
265
                    try {
266
                        $this->handler->onClose($cureentConn);
267
                    } catch (WebSocketException $e) {
268
                        if ($this->printException) {
269
                            $e->printStack();
270
                        }
271
                    }
272
273
                    // to avoid event leaks
274
                    unset($this->clients[array_search($sock, $this->clients)], $readSocks[$kSock]);
275
                    continue;
276
                }
277
278
                $isSupportedMethod = empty(self::MAP_EVENT_TYPE_TO_METHODS[$dataType]) === false
279
                    && method_exists($this->handler, self::MAP_EVENT_TYPE_TO_METHODS[$dataType]);
280
                if ($isSupportedMethod) {
281
                    try {
282
                        // dynamic call: onMessage, onPing, onPong
283
                        $this->handler->{self::MAP_EVENT_TYPE_TO_METHODS[$dataType]}($cureentConn, $dataPayload);
284
                    } catch (WebSocketException $e) {
285
                        if ($this->printException) {
286
                            $e->printStack();
287
                        }
288
                    }
289
                }
290
            }
291
        }
292
    }
293
294
    /**
295
     * Handshakes/upgrade and key parse
296
     *
297
     * @param resource $client Source client socket to write
298
     * @param string $headers Headers that client has been sent
299
     * @return string   socket handshake key (Sec-WebSocket-Key)| false on parse error
300
     * @throws ConnectionException
301
     */
302
    private function handshake($client, string $headers): string
303
    {
304
        $match = [];
305
        preg_match(self::SEC_WEBSOCKET_KEY_PTRN, $headers, $match);
306
        if (empty($match[1])) {
307
            return '';
308
        }
309
310
        $key = $match[1];
311
        // sending header according to WebSocket Protocol
312
        $secWebSocketAccept = base64_encode(sha1(trim($key) . self::HEADER_WEBSOCKET_ACCEPT_HASH, true));
313
        $this->setHeadersUpgrade($secWebSocketAccept);
314
        $upgradeHeaders = $this->getHeadersUpgrade();
315
316
        fwrite($client, $upgradeHeaders);
317
318
        return $key;
319
    }
320
321
    /**
322
     * Sets an array of headers needed to upgrade server/client connection
323
     *
324
     * @param string $secWebSocketAccept base64 encoded Sec-WebSocket-Accept header
325
     */
326
    private function setHeadersUpgrade(string $secWebSocketAccept): void
327
    {
328
        $this->headersUpgrade = [
329
            self::HEADERS_UPGRADE_KEY => self::HEADERS_UPGRADE_VALUE,
330
            self::HEADERS_CONNECTION_KEY => self::HEADERS_CONNECTION_VALUE,
331
            self::HEADERS_SEC_WEBSOCKET_ACCEPT_KEY => ' ' . $secWebSocketAccept
332
            // the space before key is really important
333
        ];
334
    }
335
336
    /**
337
     * Retreives headers from an array of headers to upgrade server/client connection
338
     *
339
     * @return string   Headers to Upgrade communication connection
340
     * @throws ConnectionException
341
     */
342
    private function getHeadersUpgrade(): string
343
    {
344
        $handShakeHeaders = self::HEADER_HTTP1_1 . self::HEADERS_EOL;
345
        if (empty($this->headersUpgrade)) {
346
            throw new ConnectionException('Headers for upgrade handshake are not set' . PHP_EOL,
347
                CommonsContract::SERVER_HEADERS_NOT_SET);
348
        }
349
350
        foreach ($this->headersUpgrade as $key => $header) {
351
            $handShakeHeaders .= $key . ':' . $header . self::HEADERS_EOL;
352
            if ($key === self::HEADERS_SEC_WEBSOCKET_ACCEPT_KEY) { // add additional EOL fo Sec-WebSocket-Accept
353
                $handShakeHeaders .= self::HEADERS_EOL;
354
            }
355
        }
356
357
        return $handShakeHeaders;
358
    }
359
360
    /**
361
     * Parses parameters from GET on web-socket client connection before handshake
362
     *
363
     * @param string $headers
364
     */
365
    private function setPathParams(string $headers): void
366
    {
367
        if (empty($this->handler->pathParams) === false) {
368
            $matches = [];
369
            preg_match('/GET\s(.*?)\s/', $headers, $matches);
370
            $left = $matches[1];
371
372
            foreach ($this->handler->pathParams as $k => $param) {
373
                if (empty($this->handler->pathParams[$k + 1]) && strpos($left, '/', 1) === false) {
374
                    // do not eat last char if there is no / at the end
375
                    $this->handler->pathParams[$param] = substr($left, strpos($left, '/') + 1);
376
                } else {
377
                    // eat both slashes
378
                    $this->handler->pathParams[$param] = substr($left, strpos($left, '/') + 1,
379
                        strpos($left, '/', 1) - 1);
380
                }
381
382
                // clear the declaration of parsed param
383
                unset($this->handler->pathParams[array_search($param, $this->handler->pathParams, false)]);
384
                $left = substr($left, strpos($left, '/', 1));
385
            }
386
        }
387
    }
388
}
389