forked from napengam/phpWebSocketServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebSocketServer.php
More file actions
535 lines (481 loc) · 20.2 KB
/
webSocketServer.php
File metadata and controls
535 lines (481 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
<?php
require __DIR__ . '/RFC_6455.php';
class webSocketServer {
use RFC_6455; // TRAIT to implement methods required by RFC6455
public
$logging = '',
$Sockets = [],
$bufferLength = 10 * 4096,
$bufferChunk = 8 * 1024, // client sends in chuncks of 6kBytes
$errorReport = E_ALL,
$timeLimit = 0,
$implicitFlush = true,
$Clients = [],
$clientIPs = [],
$maxPerIP = 0, // maximum number of websocket connections from one IP 0=unlimited
$allowedIP = [], // ['127.0.0.1','::1']
$opcode = 1, // text frame
$pingInterval = 0, // seconds, 0=no pings
$maxChunks = 100, // avoid flooding during bufferON
$maxClients = 0, // 0=no limit
$fin;
protected
$token,
$Address,
$Port,
$socketMaster,
$allApps = [];
function __construct($Address, $logger, $certFile = '', $pkFile = '') {
$errno = 0;
$errstr = '';
$this->logging = $logger;
$this->token = bin2hex(random_bytes(8));
/*
* ***********************************************
* as of 2021-07-21 context is set with
* cert.pem and privkey.pem
* ***********************************************
*/
$usingSSL = '';
$context = stream_context_create();
$Port = '';
if ($this->isSecure($Address, $Port)) { // $Port will set by function
stream_context_set_option($context, 'ssl', 'local_cert', $certFile);
stream_context_set_option($context, 'ssl', 'local_pk', $pkFile);
stream_context_set_option($context, 'ssl', 'verify_peer', false);
$usingSSL = "ssl://";
}
$socket = stream_socket_server("$usingSSL$Address:$Port", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
$this->Log("Server initialized on " . PHP_OS . " $Address:$Port $usingSSL");
if (!$socket) {
$this->Log("Error $errno creating stream: $errstr", true);
openlog('websock', LOG_PID, LOG_USER);
syslog(LOG_ERR, "Error $errno creating stream: $errstr with $usingSSL$Address:$Port");
closelog();
exit;
}
$this->Sockets[intval($socket)] = $socket;
$this->socketMaster = $socket;
$this->allowedIP[] = gethostbyname($Address);
$this->allowedIP[] = '::1';
error_reporting($this->errorReport);
set_time_limit($this->timeLimit);
if ($this->implicitFlush) {
ob_implicit_flush();
}
}
private function isSecure(&$Address, &$port) {
$secure = false;
$arr = explode('://', $Address);
if (count($arr) > 1) {
if (strncasecmp($arr[0], 'ssl', 3) == 0 || strncasecmp($arr[0], 'wss', 3) == 0) {
$Address = $arr[1];
$secure = true;
$port = '443'; // default
} else {
$Address = $arr[1]; // just the host
$port = '80'; // default
}
}
/*
* ***********************************************
* extract port from $Address if given
* ***********************************************
*/
$arr = explode(':', $Address);
if (count($arr) > 1) {
$Address = $arr[0];
$port = $arr[1]; // overwrite default
}
return $secure;
}
public function Start() {
$this->Log("Starting server...");
foreach ($this->allApps as $appName => $class) {
$this->Log("Registered resource : $appName");
}
$a = true;
$socketArrayWrite = $socketArrayExceptions = NULL;
$startTime = time();
while ($a) {
$socketArrayRead = $this->Sockets;
$ncon = stream_select($socketArrayRead, $socketArrayWrite, $socketArrayExceptions, 1, 000);
if ($ncon === 0) {
/*
* ***********************************************
* no news after one second; we can do other tasks.
* Here we continue to wait for another second
* ***********************************************
*/
if ($this->pingInterval > 0 && time() - $startTime > $this->pingInterval) {
if ($this->pingClients()) {
$this->Log("Ping Clients");
}
$startTime = time();
}
continue;
}
foreach ($socketArrayRead as $Socket) {
$SocketID = intval($Socket);
if ($Socket === $this->socketMaster) {
/*
* ***********************************************
* new client
* ***********************************************
*/
$clientSocket = stream_socket_accept($Socket);
if (!is_resource($clientSocket)) {
$this->Log("$SocketID, Connection could not be established");
continue;
}
/*
* ***********************************************
* get IP:Port of client
* ***********************************************
*/
$ipport = stream_socket_get_name($clientSocket, true);
$ip = $this->extractIPort($ipport); // can be ipv4 or ipv6
$this->Log("Connecting from IP: $ip->ip");
$SocketID = intval($clientSocket);
$this->Clients[$SocketID] = (object) [
'ID' => $SocketID,
'uuid' => '',
'clientType' => null, // not part of RFC6455
'Handshake' => false,
'timeCreated' => time(), // not used yet
'bufferON' => false,
'fin' => true, // RFC6455 final fragment in message
'buffer' => [], // buffers message chunks
'app' => NULL,
'ip' => $ip->ip,
'fyi' => '',
'ident' => '', // id set from client not part of RFC6455
'expectPong' => false // is true if ping has been send
];
$this->Sockets[$SocketID] = $clientSocket;
$this->Log("New client connecting from $ipport on socket #$SocketID\r\n");
continue; // done so far for this new client
}
/*
* ***********************************************
* setting unbuffered read, could be dangerous
* because a client can send unlimited amount of
* data and block the server. Therefor I do not
* use this option. Client should send long messages
* in chunks.
* ***********************************************
*/
//stream_set_read_buffer($Socket, 0); // no buffering hgs 01.05.2021
$Client = $this->Clients[$SocketID];
if ($Client->Handshake) {
/*
* ***********************************************
* Handshake and checks have passsed.
* get message from client
* ***********************************************
*/
$message = $this->extractMessage($SocketID);
if ($message != '') {
/*
* ***********************************************
* route message to application class
* ***********************************************
*/
$Client->app->onData($SocketID, $message);
}
continue;
}
/*
* ***********************************************
* read data for handshake from socket and check
* ***********************************************
*/
$dataBuffer = fread($Socket, $this->bufferLength);
if ($dataBuffer === false ||
strlen($dataBuffer) == 0 ||
strlen($dataBuffer) >= $this->bufferChunk) { // to avoid malicious overload
$this->onError($SocketID, "Client disconnected by Server - TCP connection lost");
$this->Close($Socket);
continue;
}
/*
* ***********************************************
* handshake
* ***********************************************
*/
if ($this->Handshake($Socket, $dataBuffer) === false) {
continue; // something is wrong
}
/*
* ***********************************************
* handshake according RFC 6455 is ok .
* Now,for this client, check for apps and connections
* ***********************************************
*/
if ($this->specificChecks($SocketID) === false) {
continue; // something is wrong
}
/*
* ***********************************************
* all checks passed now let client work
* ***********************************************
*/
$this->Log("Telling Client to start on #$SocketID");
$uuid = $this->guidv4();
$msg = (object) ['opcode' => 'ready', 'uuid' => $uuid];
$this->Clients[$SocketID]->uuid = $uuid;
$this->Write($SocketID, json_encode($msg));
$Client->app->onOpen($SocketID);
}
}
}
public function Close($Socket) {
if (is_int($Socket)) {
$Socket = $this->Sockets[$Socket];
}
stream_socket_shutdown($Socket, STREAM_SHUT_RDWR);
$SocketID = intval($Socket);
$this->onClose($SocketID);
if ($this->maxPerIP > 0 && $this->Clients[$SocketID]->clientType == 'websocket') {
$ip = $this->Clients[$SocketID]->ip;
$this->clientIPs[$ip]->count--;
if ($this->clientIPs[$ip]->count <= 0) {
unset($this->clientIPs[$ip]);
}
}
unset($this->Clients[$SocketID]);
unset($this->Sockets[$SocketID]);
return $SocketID;
}
private function extractMessage($SocketID) {
$client = $this->Clients[$SocketID];
$message = $this->readDecode($SocketID);
$opcode = $this->opcode; // opcode within from current frame
$this->opcode = 1; // text , back to default;
if ($opcode == 10) { //pong
if ($client->expectPong == false) {
$this->log("Unsolicited Pong frame received from socket #$SocketID $message"); // just ignore
} else {
$this->log("Expected Pong frame received from socket #$SocketID"); // just ignore
$client->expectPong = false;
}
return '';
}
if ($opcode == 9) { //ping received
$this->log("Ping frame received from socket #$SocketID");
$this->opcode = 10; // pong
$this->Write($SocketID, $message);
$this->opcode = 1;
return '';
}
if ($opcode == 8) { //Connection Close Frame
$this->log("Connection Close frame received from socket #$SocketID");
$this->Close($SocketID);
return '';
}
$this->Write($SocketID, json_encode((object) [
'opcode' => 'next',
'fyi' => $this->Clients[$SocketID]->fyi]));
/*
* ***********************************************
* take care of buffering messages either because
* buffrerON===true or fin===false
* ***********************************************
*/
if ($this->serverCommand($client, $message)) {
return '';
}
if ($client->bufferON) {
if (count($client->buffer) <= $this->maxChunks) {
$client->buffer[] = $message;
} else {
$this->log("Too many chunks from socket #$SocketID");
$this->onClose($SocketID);
}
return '';
}
return $message;
}
public final function Write($SocketID, $message) {
$m = $this->Encode($message);
return fwrite($this->Sockets[$SocketID], $m, strlen($m));
}
public final function feedback($packet) {
foreach ($this->Clients as $client) {
if (($packet->uuid == $client->uuid && $client->clientType === 'websocket') ||
($packet->ident != '' && $packet->ident == $client->ident)) {
$this->Write($client->ID, json_encode($packet));
return;
}
}
}
public final function echo($sockid, $packet) {
$this->Write($sockid, json_encode($packet));
}
public final function broadCast($SocketID, $M) {
$ME = $this->Encode($M);
foreach ($this->Clients as &$client) {
if ($client->clientType === 'websocket') {
if ($SocketID == $client->ID) {
continue;
}
fwrite($this->Sockets[$client->ID], $ME, strlen($ME));
}
}
return;
}
public final function pingClients() {
$this->opcode = 9; // PING
$m = $this->Encode(json_encode((object) ['opcode' => 'PING']));
$this->opcode = 1;
$nw = false;
foreach ($this->Clients as &$client) {
if ($client->clientType === 'websocket') {
fwrite($this->Sockets[$client->ID], $m, strlen($m));
$client->expectPong = true;
$nw = true;
}
}
return $nw;
}
public final function registerResource($name, $app) {
$this->allApps[$name] = $app;
foreach (['registerServerMethods', 'onOpen', 'onData', 'onClose', 'onError'] as $method) {
if (!method_exists($app, $method)) {
$this->allApps[$name] = NULL;
return false;
}
}
$app->registerServerMethods($this);
return true;
}
private function specificChecks($SocketID) {
$Client = $this->Clients[$SocketID];
if ($Client->app === NULL) {
$this->Log("Application incomplete or does not exist);"
. " Telling Client to disconnect on #$SocketID");
$msg = (object) ['opcode' => 'close'];
$this->Write($SocketID, json_encode($msg));
$this->Close($SocketID);
return false;
}
if ($this->maxClients > 0 && count($this->Clients) > $this->maxClients) {
$msg = "To many connections ";
$this->Log("$SocketID, $msg");
$this->Write($SocketID, json_encode((object) ['opcode' => 'close', 'error' => $msg]));
$this->Close($SocketID);
return false;
}
if ($this->maxPerIP > 0 && $this->Clients[$SocketID]->clientType == 'websocket') {
/*
* ***********************************************
* track number of websocket connectins from this IP
* ***********************************************
*/
$ip = $Client->ip;
if (!isset($this->clientIPs[$ip])) {
$this->clientIPs[$ip] = (object) [
'SocketId' => $SocketID,
'count' => 1
];
} else {
$this->clientIPs[$ip]->count++;
if ($this->clientIPs[$ip]->count > $this->maxPerIP) {
$msg = "To many connections from: $ip";
$this->Log("$SocketID, $msg");
$this->Write($SocketID, json_encode((object) ['opcode' => 'close', 'error' => $msg]));
$this->Close($SocketID);
return false;
}
}
} else if (count($this->allowedIP) > 0 && $this->Clients[$SocketID]->clientType != 'websocket') {
/*
* ***********************************************
* check if tcp client connects from allowed host
* ***********************************************
*/
if (!in_array($Client->ip, $this->allowedIP)) {
$this->Close($SocketID);
$this->Log("$SocketID, No connection allowed from: " . $Client->ip);
return false;
}
}
return true;
}
private function serverCommand($client, &$message) {
if ($client->fin === true) { // no fragment
if ($message === 'bufferON') {
$client->bufferON = true;
$client->buffer = [];
$this->Log('Buffering ON');
return true;
}
if ($message === 'bufferOFF') {
$client->bufferON = false;
$message = implode('', $client->buffer);
$client->buffer = [];
$this->Log('Buffering OFF');
return false;
}
}
if ($client->bufferON === false) {
if ($client->fin === false && count($client->buffer) == 0) {
$this->Log("FIN=false ");
$client->buffer[] = $message; // a fragement
return true;
}
if ($client->fin === true && count($client->buffer) > 0) {
$client->buffer[] = $message; // last fragement
$message = implode('', $client->buffer);
$client->buffer = [];
$this->Log('FIN=true');
}
}
return false;
}
public final function Log($m) {
if ($this->logging) {
$this->logging->log($m);
}
}
public function guidv4() {
// from https://www.uuidgenerator.net/dev-corner/php
// Generate 16 bytes (128 bits) of random data or use the data passed into the function.
$data = random_bytes(16);
assert(strlen($data) == 16);
// Set version to 0100
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
// Set bits 6-7 to 10
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
// Output the 36 character UUID.
$unsecure = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
$token = ''; // generate whatever yo want
$hash = password_hash($unsecure . $token, PASSWORD_DEFAULT, ["cost" => 5]);
return $unsecure . $hash;
}
protected function verifyUUID($uuHash) {
$uns = mb_substr($uuHash, 0, 36);
$hash = mb_substr($uuHash, 36);
$token = ''; // generate whatever yo want
$f = password_verify($uns . $token, $hash);
return $f;
}
function onClose($SocketID) { // ...socket has been closed AND deleted
$this->Log("Connection closed to socket #$SocketID");
if ($this->Clients[$SocketID]->app == NULL) {
return;
}
if (method_exists($this->Clients[$SocketID]->app, 'onClose')) {
$this->Clients[$SocketID]->app->onClose($SocketID);
}
}
function onError($SocketID, $message) { // ...any connection-releated error
$this->Log("Socket $SocketID - " . $message);
if ($this->Clients[$SocketID]->app == NULL) {
return;
}
if (method_exists($this->Clients[$SocketID]->app, 'onError')) {
$this->Clients[$SocketID]->app->onError($SocketID, $message);
}
}
}