Passed
Branch master (32af5e)
by Arthur
06:54
created

WebSocketServer::looping()   C

Complexity

Conditions 12
Paths 81

Size

Total Lines 42
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
cc 12
eloc 24
nc 81
nop 1
dl 0
loc 42
rs 6.9666
c 8
b 0
f 0

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
     * set any template You need ex.: GET /subscription/messenger/token
36
     * @var array
37
     */
38
    private array $pathParams = [];
39
40
    /**
41
     * @var array
42
     */
43
    private array $handshakes = [];
44
45
    /**
46
     * @var array
47
     */
48
    private array $headersUpgrade = [];
49
50
    /**
51
     * @var int
52
     */
53
    private int $maxClients = 1;
54
55
    /**
56
     * @var WebSocket
57
     */
58
    private WebSocket $handler;
59
60
    /**
61
     * @var bool
62
     */
63
    private bool $stepRecursion = true;
64
65
    /**
66
     * WebSocketServer constructor.
67
     *
68
     * @param WebSocket $handler
69
     * @param ServerConfig $config
70
     */
71
    public function __construct(
72
        WebSocket $handler,
73
        ServerConfig $config
74
    )
75
    {
76
        ini_set('default_socket_timeout', 5); // this should be >= 5 sec, otherwise there will be broken pipe - tested
77
78
        $this->handler = $handler;
79
        $this->config = $config;
80
        $this->setIsPcntlLoaded(extension_loaded('pcntl'));
81
    }
82
83
    /**
84
     * Runs main process - Anscestor with server socket on TCP
85
     *
86
     * @throws WebSocketException
87
     * @throws ConnectionException
88
     */
89
    public function run(): void
90
    {
91
        $context = stream_context_create();
92
        $errno = null;
93
        $errorMessage = '';
94
95
        if ($this->config->isSsl() === true) {
96
            stream_context_set_option($context, 'ssl', 'allow_self_signed', $this->config->getAllowSelfSigned());
97
            stream_context_set_option($context, 'ssl', 'verify_peer', false);
98
99
            if (is_file($this->config->getLocalCert()) === false || is_file($this->config->getLocalPk()) === false) {
100
                throw new WebSocketException('SSL certificates must be valid pem files', CommonsContract::SERVER_INVALID_STREAM_CONTEXT);
101
            }
102
            $isLocalCertSet = stream_context_set_option($context, 'ssl', 'local_cert', $this->config->getLocalCert());
103
            $isLocalPkSet = stream_context_set_option($context, 'ssl', 'local_pk', $this->config->getLocalPk());
104
105
            if ($isLocalCertSet === false || $isLocalPkSet === false) {
106
                throw new WebSocketException('SSL certificates could not be set correctly', CommonsContract::SERVER_INVALID_STREAM_CONTEXT);
107
            }
108
        }
109
110
        $server = stream_socket_server("tcp://{$this->config->getHost()}:{$this->config->getPort()}", $errno,
111
            $errorMessage, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
112
113
        if ($server === false) {
114
            throw new WebSocketException('Could not bind to socket: ' . $errno . ' - ' . $errorMessage . PHP_EOL,
115
                CommonsContract::SERVER_COULD_NOT_BIND_TO_SOCKET);
116
        }
117
118
        @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

118
        /** @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...
119
        $this->eventLoop($server);
120
    }
121
122
    /**
123
     * Recursive event loop that input intu recusion by remainder = 0 - thus when N users,
124
     * and when forks equals true which prevents it from infinite recursive iterations
125
     *
126
     * @param resource $server server connection
127
     * @param bool $fork flag to fork or run event loop
128
     * @throws WebSocketException
129
     * @throws ConnectionException
130
     */
131
    private function eventLoop($server, bool $fork = false): void
132
    {
133
        if ($fork === true && $this->isPcntlLoaded()) {
134
            $pid = pcntl_fork();
135
136
            if ($pid) { // run eventLoop in parent        
137
                @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

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