Passed
Push — master ( f04fa5...2f7798 )
by Arthur
01:45
created

WebSocketServer::printException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
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
                        $this->handleMessagesWorkerException($cureentConn, $e);
269
                    }
270
271
                    // to avoid event leaks
272
                    unset($this->clients[array_search($sock, $this->clients)], $readSocks[$kSock]);
273
                    continue;
274
                }
275
276
                $isSupportedMethod = empty(self::MAP_EVENT_TYPE_TO_METHODS[$dataType]) === false
277
                    && method_exists($this->handler, self::MAP_EVENT_TYPE_TO_METHODS[$dataType]);
278
                if ($isSupportedMethod) {
279
                    try {
280
                        // dynamic call: onMessage, onPing, onPong
281
                        $this->handler->{self::MAP_EVENT_TYPE_TO_METHODS[$dataType]}($cureentConn, $dataPayload);
282
                    } catch (WebSocketException $e) {
283
                        $this->handleMessagesWorkerException($cureentConn, $e);
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 '';
304
        }
305
306
        $key = $match[1];
307
        // sending header according to WebSocket Protocol
308
        $secWebSocketAccept = base64_encode(sha1(trim($key) . self::HEADER_WEBSOCKET_ACCEPT_HASH, true));
309
        $this->setHeadersUpgrade($secWebSocketAccept);
310
        $upgradeHeaders = $this->getHeadersUpgrade();
311
312
        fwrite($client, $upgradeHeaders);
313
314
        return $key;
315
    }
316
317
    /**
318
     * Sets an array of headers needed to upgrade server/client connection
319
     *
320
     * @param string $secWebSocketAccept base64 encoded Sec-WebSocket-Accept header
321
     */
322
    private function setHeadersUpgrade(string $secWebSocketAccept): void
323
    {
324
        $this->headersUpgrade = [
325
            self::HEADERS_UPGRADE_KEY => self::HEADERS_UPGRADE_VALUE,
326
            self::HEADERS_CONNECTION_KEY => self::HEADERS_CONNECTION_VALUE,
327
            self::HEADERS_SEC_WEBSOCKET_ACCEPT_KEY => ' ' . $secWebSocketAccept
328
            // the space before key is really important
329
        ];
330
    }
331
332
    /**
333
     * Retreives headers from an array of headers to upgrade server/client connection
334
     *
335
     * @return string   Headers to Upgrade communication connection
336
     * @throws ConnectionException
337
     */
338
    private function getHeadersUpgrade(): string
339
    {
340
        $handShakeHeaders = self::HEADER_HTTP1_1 . self::HEADERS_EOL;
341
        if (empty($this->headersUpgrade)) {
342
            throw new ConnectionException('Headers for upgrade handshake are not set' . PHP_EOL,
343
                CommonsContract::SERVER_HEADERS_NOT_SET);
344
        }
345
346
        foreach ($this->headersUpgrade as $key => $header) {
347
            $handShakeHeaders .= $key . ':' . $header . self::HEADERS_EOL;
348
            if ($key === self::HEADERS_SEC_WEBSOCKET_ACCEPT_KEY) { // add additional EOL fo Sec-WebSocket-Accept
349
                $handShakeHeaders .= self::HEADERS_EOL;
350
            }
351
        }
352
353
        return $handShakeHeaders;
354
    }
355
356
    /**
357
     * Parses parameters from GET on web-socket client connection before handshake
358
     *
359
     * @param string $headers
360
     */
361
    private function setPathParams(string $headers): void
362
    {
363
        if (empty($this->handler->pathParams) === false) {
364
            $matches = [];
365
            preg_match('/GET\s(.*?)\s/', $headers, $matches);
366
            $left = $matches[1];
367
368
            foreach ($this->handler->pathParams as $k => $param) {
369
                if (empty($this->handler->pathParams[$k + 1]) && strpos($left, '/', 1) === false) {
370
                    // do not eat last char if there is no / at the end
371
                    $this->handler->pathParams[$param] = substr($left, strpos($left, '/') + 1);
372
                } else {
373
                    // eat both slashes
374
                    $this->handler->pathParams[$param] = substr($left, strpos($left, '/') + 1,
375
                        strpos($left, '/', 1) - 1);
376
                }
377
378
                // clear the declaration of parsed param
379
                unset($this->handler->pathParams[array_search($param, $this->handler->pathParams, false)]);
380
                $left = substr($left, strpos($left, '/', 1));
381
            }
382
        }
383
    }
384
385
    /**
386
     * Manage messagesWorker Exceptions
387
     *
388
     * @param Connection $connection
389
     * @param WebSocketException $e
390
     */
391
    private function handleMessagesWorkerException(Connection $connection, WebSocketException $e): void
392
    {
393
        $this->handler->onError($connection, $e);
394
395
        if ($this->printException) {
396
            $e->printStack();
397
        }
398
    }
399
}
400