-
Notifications
You must be signed in to change notification settings - Fork 115
/
websocket_server.php
563 lines (445 loc) · 16.9 KB
/
websocket_server.php
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
<?php
// CubicleSoft PHP WebSocketServer class.
// (C) 2021 CubicleSoft. All Rights Reserved.
// Make sure PHP doesn't introduce weird limitations.
ini_set("memory_limit", "-1");
set_time_limit(0);
// Requires the CubicleSoft PHP WebSocket class.
class WebSocketServer
{
protected $fp, $clients, $nextclientid, $websocketclass, $origins;
protected $defaultclosemode, $defaultmaxreadframesize, $defaultmaxreadmessagesize, $defaultkeepalive, $lasttimeoutcheck;
public function __construct()
{
$this->Reset();
}
public function Reset()
{
if (!class_exists("WebSocket", false)) require_once str_replace("\\", "/", dirname(__FILE__)) . "/websocket.php";
$this->fp = false;
$this->clients = array();
$this->nextclientid = 1;
$this->websocketclass = "WebSocket";
$this->origins = false;
$this->defaultclosemode = WebSocket::CLOSE_IMMEDIATELY;
$this->defaultmaxreadframesize = 2000000;
$this->defaultmaxreadmessagesize = 10000000;
$this->defaultkeepalive = 30;
$this->lasttimeoutcheck = time();
}
public function __destruct()
{
$this->Stop();
}
public function SetWebSocketClass($newclass)
{
if (class_exists($newclass)) $this->websocketclass = $newclass;
}
public function SetAllowedOrigins($origins)
{
if (is_string($origins)) $origins = array($origins);
if (!is_array($origins)) $origins = false;
else if (isset($origins[0])) $origins = array_flip($origins);
$this->origins = $origins;
}
public function SetDefaultCloseMode($mode)
{
$this->defaultclosemode = $mode;
}
public function SetDefaultKeepAliveTimeout($keepalive)
{
$this->defaultkeepalive = (int)$keepalive;
}
public function SetDefaultMaxReadFrameSize($maxsize)
{
$this->defaultmaxreadframesize = (is_bool($maxsize) ? false : (int)$maxsize);
}
public function SetDefaultMaxReadMessageSize($maxsize)
{
$this->defaultmaxreadmessagesize = (is_bool($maxsize) ? false : (int)$maxsize);
}
// Starts the server on the host and port.
// $host is usually 0.0.0.0 or 127.0.0.1 for IPv4 and [::0] or [::1] for IPv6.
public function Start($host, $port)
{
$this->Stop();
$this->fp = stream_socket_server("tcp://" . $host . ":" . $port, $errornum, $errorstr);
if ($this->fp === false) return array("success" => false, "error" => self::WSTranslate("Bind() failed. Reason: %s (%d)", $errorstr, $errornum), "errorcode" => "bind_failed");
// Enable non-blocking mode.
stream_set_blocking($this->fp, 0);
return array("success" => true);
}
public function Stop()
{
foreach ($this->clients as $client)
{
if ($client->websocket !== false) $client->websocket->Disconnect();
else fclose($client->fp);
}
$this->clients = array();
if ($this->fp !== false)
{
fclose($this->fp);
$this->fp = false;
}
$this->nextclientid = 1;
}
// Dangerous but allows for stream_select() calls on multiple, separate stream handles.
public function GetStream()
{
return $this->fp;
}
// Return whatever response/headers are needed here.
protected function ProcessNewConnection($method, $path, $client)
{
$result = "";
if ($method !== "GET") $result .= "HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\n\r\n";
else if (!isset($client->headers["Host"]) || !isset($client->headers["Connection"]) || stripos($client->headers["Connection"], "upgrade") === false || !isset($client->headers["Upgrade"]) || stripos($client->headers["Upgrade"], "websocket") === false || !isset($client->headers["Sec-Websocket-Key"]))
{
$result .= "HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n";
}
else if (!isset($client->headers["Sec-Websocket-Version"]) || $client->headers["Sec-Websocket-Version"] != 13)
{
$result .= "HTTP/1.1 426 Upgrade Required\r\nSec-WebSocket-Version: 13\r\nConnection: close\r\n\r\n";
}
else if (!isset($client->headers["Origin"]) || ($this->origins !== false && !isset($this->origins[strtolower($client->headers["Origin"])])))
{
$result .= "HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n";
}
return $result;
}
// Return whatever additional HTTP headers are needed here.
protected function ProcessAcceptedConnection($method, $path, $client)
{
return "";
}
protected function InitNewClient($fp)
{
$client = new stdClass();
$client->id = $this->nextclientid;
$client->readdata = "";
$client->writedata = "";
$client->request = false;
$client->path = "";
$client->url = "";
$client->headers = array();
$client->lastheader = "";
$client->websocket = false;
$client->fp = $fp;
$client->ipaddr = stream_socket_get_name($fp, true);
// Intended for application storage.
$client->appdata = false;
$this->clients[$this->nextclientid] = $client;
$this->nextclientid++;
return $client;
}
private function ProcessInitialResponse($method, $path, $client)
{
// Let a derived class handle the new connection (e.g. processing Origin and Host).
// Since the 'websocketclass' is instantiated AFTER this function, it is possible to switch classes on the fly.
$client->writedata .= $this->ProcessNewConnection($method, $path, $client);
// If an error occurs, the connection will still terminate.
$client->websocket = new $this->websocketclass();
$client->websocket->SetCloseMode($this->defaultclosemode);
$client->websocket->SetKeepAliveTimeout($this->defaultkeepalive);
// If nothing was output, accept the connection.
if ($client->writedata === "")
{
$client->writedata .= "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n";
$client->writedata .= "Sec-WebSocket-Accept: " . base64_encode(sha1($client->headers["Sec-Websocket-Key"] . WebSocket::KEY_GUID, true)) . "\r\n";
$client->writedata .= $this->ProcessAcceptedConnection($method, $path, $client);
$client->writedata .= "\r\n";
// Finish class initialization.
$client->websocket->SetServerMode();
$client->websocket->SetMaxReadFrameSize($this->defaultmaxreadframesize);
$client->websocket->SetMaxReadMessageSize($this->defaultmaxreadmessagesize);
// Set the socket in the WebSocket class.
$client->websocket->Connect("", "", array("connected_fp" => $client->fp));
}
$this->UpdateClientState($client->id);
}
public function UpdateStreamsAndTimeout($prefix, &$timeout, &$readfps, &$writefps)
{
if ($this->fp !== false) $readfps[$prefix . "ws_s"] = $this->fp;
if ($timeout === false || $timeout > $this->defaultkeepalive) $timeout = $this->defaultkeepalive;
foreach ($this->clients as $id => $client)
{
if ($client->writedata === "") $readfps[$prefix . "ws_c_" . $id] = $client->fp;
if ($client->writedata !== "" || ($client->websocket !== false && $client->websocket->NeedsWrite())) $writefps[$prefix . "ws_c_" . $id] = $client->fp;
if ($client->websocket !== false)
{
$timeout2 = $client->websocket->GetKeepAliveTimeout();
if ($timeout > $timeout2) $timeout = $timeout2;
}
}
}
// Sometimes keyed arrays don't work properly.
public static function FixedStreamSelect(&$readfps, &$writefps, &$exceptfps, $timeout)
{
// In order to correctly detect bad outputs, no '0' integer key is allowed.
if (isset($readfps[0]) || isset($writefps[0]) || ($exceptfps !== NULL && isset($exceptfps[0]))) return false;
$origreadfps = $readfps;
$origwritefps = $writefps;
$origexceptfps = $exceptfps;
$result2 = @stream_select($readfps, $writefps, $exceptfps, $timeout);
if ($result2 === false) return false;
if (isset($readfps[0]))
{
$fps = array();
foreach ($origreadfps as $key => $fp) $fps[(int)$fp] = $key;
foreach ($readfps as $num => $fp)
{
$readfps[$fps[(int)$fp]] = $fp;
unset($readfps[$num]);
}
}
if (isset($writefps[0]))
{
$fps = array();
foreach ($origwritefps as $key => $fp) $fps[(int)$fp] = $key;
foreach ($writefps as $num => $fp)
{
$writefps[$fps[(int)$fp]] = $fp;
unset($writefps[$num]);
}
}
if ($exceptfps !== NULL && isset($exceptfps[0]))
{
$fps = array();
foreach ($origexceptfps as $key => $fp) $fps[(int)$fp] = $key;
foreach ($exceptfps as $num => $fp)
{
$exceptfps[$fps[(int)$fp]] = $fp;
unset($exceptfps[$num]);
}
}
return true;
}
// Handles new connections, the initial conversation, basic packet management, and timeouts.
// Can wait on more streams than just sockets and/or more sockets. Useful for waiting on other resources.
// 'ws_s' and the 'ws_c_' prefix are reserved.
// Returns an array of clients that may need more processing.
public function Wait($timeout = false, $readfps = array(), $writefps = array(), $exceptfps = NULL)
{
$this->UpdateStreamsAndTimeout("", $timeout, $readfps, $writefps);
$result = array("success" => true, "clients" => array(), "removed" => array(), "readfps" => array(), "writefps" => array(), "exceptfps" => array(), "accepted" => array(), "read" => array(), "write" => array());
if (!count($readfps) && !count($writefps)) return $result;
$result2 = self::FixedStreamSelect($readfps, $writefps, $exceptfps, $timeout);
if ($result2 === false) return array("success" => false, "error" => self::WSTranslate("Wait() failed due to stream_select() failure. Most likely cause: Connection failure."), "errorcode" => "stream_select_failed");
// Return handles that were being waited on.
$result["readfps"] = $readfps;
$result["writefps"] = $writefps;
$result["exceptfps"] = $exceptfps;
$this->ProcessWaitResult($result);
return $result;
}
protected function ProcessWaitResult(&$result)
{
// Handle new connections.
if (isset($result["readfps"]["ws_s"]))
{
while (($fp = @stream_socket_accept($this->fp, 0)) !== false)
{
// Enable non-blocking mode.
stream_set_blocking($fp, 0);
$client = $this->InitNewClient($fp);
$result["accepted"][$client->id] = $client;
}
unset($result["readfps"]["ws_s"]);
}
// Handle clients in the read queue.
foreach ($result["readfps"] as $cid => $fp)
{
if (!is_string($cid) || strlen($cid) < 6 || substr($cid, 0, 5) !== "ws_c_") continue;
$id = (int)substr($cid, 5);
if (!isset($this->clients[$id])) continue;
$client = $this->clients[$id];
$result["read"][$id] = $client;
if ($client->websocket !== false)
{
$this->ProcessClientQueuesAndTimeoutState($result, $id, true, isset($result["writefps"][$cid]));
// Remove active WebSocket clients from the write queue.
unset($result["writefps"][$cid]);
}
else
{
$result2 = @fread($fp, 8192);
if ($result2 === false || ($result2 === "" && feof($fp)))
{
@fclose($fp);
unset($this->clients[$id]);
}
else
{
$client->readdata .= $result2;
if (strlen($client->readdata) > 100000)
{
// Bad header size. Just kill the connection.
@fclose($fp);
unset($this->clients[$id]);
}
else
{
while (($pos = strpos($client->readdata, "\n")) !== false)
{
// Retrieve the next line of input.
$line = rtrim(substr($client->readdata, 0, $pos));
$client->readdata = (string)substr($client->readdata, $pos + 1);
if ($client->request === false) $client->request = trim($line);
else if ($line !== "")
{
// Process the header.
if ($client->lastheader != "" && (substr($line, 0, 1) == " " || substr($line, 0, 1) == "\t")) $client->headers[$client->lastheader] .= $header;
else
{
$pos = strpos($line, ":");
if ($pos === false) $pos = strlen($line);
$client->lastheader = self::HeaderNameCleanup(substr($line, 0, $pos));
$client->headers[$client->lastheader] = ltrim(substr($line, $pos + 1));
}
}
else
{
// Headers have all been received. Process the client request.
$request = $client->request;
$pos = strpos($request, " ");
if ($pos === false) $pos = strlen($request);
$method = (string)substr($request, 0, $pos);
$request = trim(substr($request, $pos));
$pos = strrpos($request, " ");
if ($pos === false) $pos = strlen($request);
$path = (string)substr($request, 0, $pos);
if ($path === "") $path = "/";
if (isset($client->headers["Host"])) $client->headers["Host"] = preg_replace('/[^a-z0-9.:\[\]_-]/', "", strtolower($client->headers["Host"]));
$client->path = $path;
$client->url = "ws://" . (isset($client->headers["Host"]) ? $client->headers["Host"] : "localhost") . $path;
$this->ProcessInitialResponse($method, $path, $client);
break;
}
}
}
}
}
unset($result["readfps"][$cid]);
}
// Handle remaining clients in the write queue.
foreach ($result["writefps"] as $cid => $fp)
{
if (!is_string($cid) || strlen($cid) < 6 || substr($cid, 0, 5) !== "ws_c_") continue;
$id = (int)substr($cid, 5);
if (!isset($this->clients[$id])) continue;
$client = $this->clients[$id];
$result["write"][$id] = $client;
if ($client->writedata === "") $this->ProcessClientQueuesAndTimeoutState($result, $id, false, true);
else
{
$result2 = @fwrite($fp, $client->writedata);
if ($result2 === false || ($result2 === "" && feof($fp)))
{
@fclose($fp);
unset($this->clients[$id]);
}
else if ($result2 === 0) $this->ProcessClientQueuesAndTimeoutState($result, $id, true, false, 1);
else
{
$client->writedata = (string)substr($client->writedata, $result2);
// Let the application know about the new client or close the connection if the WebSocket Upgrade request failed.
if ($client->writedata === "")
{
if ($client->websocket->GetStream() !== false) $result["clients"][$id] = $client;
else
{
@fclose($fp);
unset($this->clients[$id]);
}
}
}
}
unset($result["writefps"][$cid]);
}
// Handle client timeouts.
$ts = time();
if ($this->lasttimeoutcheck <= $ts - 5)
{
foreach ($this->clients as $id => $client)
{
if (!isset($result["clients"][$id]) && $client->writedata === "" && $client->websocket !== false)
{
$this->ProcessClientQueuesAndTimeoutState($result, $id, false, false);
}
}
$this->lasttimeoutcheck = $ts;
}
}
protected function ProcessClientQueuesAndTimeoutState(&$result, $id, $read, $write, $readsize = 65536)
{
$client = $this->clients[$id];
$result2 = $client->websocket->ProcessQueuesAndTimeoutState($read, $write, $readsize);
if ($result2["success"]) $result["clients"][$id] = $client;
else
{
$result["removed"][$id] = array("result" => $result2, "client" => $client);
$this->RemoveClient($id);
}
}
public function GetClients()
{
return $this->clients;
}
public function NumClients()
{
return count($this->clients);
}
public function UpdateClientState($id)
{
}
public function GetClient($id)
{
return (isset($this->clients[$id]) ? $this->clients[$id] : false);
}
public function RemoveClient($id)
{
if (isset($this->clients[$id]))
{
$client = $this->clients[$id];
// Remove the client.
if ($client->websocket->GetStream() !== false)
{
$client->websocket->Disconnect();
$client->websocket = false;
$client->fp = false;
}
if ($client->fp !== false) @fclose($client->fp);
unset($this->clients[$id]);
}
}
public function ProcessWebServerClientUpgrade($webserver, $client)
{
if (!($client instanceof WebServer_Client)) return false;
if (!$client->requestcomplete || $client->mode === "handle_response") return false;
if ($client->request["method"] !== "GET" || !isset($client->headers["Connection"]) || stripos($client->headers["Connection"], "upgrade") === false || !isset($client->headers["Upgrade"]) || stripos($client->headers["Upgrade"], "websocket") === false) return false;
// Create an equivalent WebSocket server client class.
$webserver->DetachClient($client->id);
$method = $client->request["method"];
$path = $client->request["path"];
$client2 = $this->InitNewClient($client->fp);
$client2->request = $client->request["line"];
$client2->headers = $client->headers;
$client2->path = $path;
$client2->url = "ws://" . (isset($client->headers["Host"]) ? $client->headers["Host"] : "localhost") . $path;
$client2->appdata = $client->appdata;
$this->ProcessInitialResponse($method, $path, $client2);
return $client2->id;
}
public static function HeaderNameCleanup($name)
{
return preg_replace('/\s+/', "-", ucwords(strtolower(trim(preg_replace('/[^A-Za-z0-9 ]/', " ", $name)))));
}
public static function WSTranslate()
{
$args = func_get_args();
if (!count($args)) return "";
return call_user_func_array((defined("CS_TRANSLATE_FUNC") && function_exists(CS_TRANSLATE_FUNC) ? CS_TRANSLATE_FUNC : "sprintf"), $args);
}
}
?>