-
Notifications
You must be signed in to change notification settings - Fork 0
/
wson.class.php
1152 lines (1072 loc) · 41 KB
/
wson.class.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* wson websocket server core
*
* @package wson
* @author Maxim Luzgin <[email protected]>
* @copyright 2018 Maxim Luzgin
* @license BSD 2-Clause
*/
class Wson
{
protected const CLOSING = 1;
protected const CLOSED = 2;
protected const HANDSHAKE = 4;
protected const READY = 8;
protected const ALIVE = 16;
protected const MAX_BUFFER_LEN = 16384;
protected const MAX_LEN_NO_HSK = 1024;
protected const MAX_C_BUFFER_LEN = 65536;
protected const WS_TOKEN_LIFETIME = 86400;
protected const ALIVE_INTERVAL = 15;
protected const AUTH_TOKEN_LEN = 32;
protected const MIN_HSK_FRAGMENT = 256;
protected const MAX_CONNS_PER_USER = 5;
protected $error = '';
protected $server_sockets;
protected $control_socket;
protected $pid_file;
protected $domains;
protected $secret;
protected $origins;
protected $server_els = [];
protected $control_el;
protected $servers_loads = [];
protected $e_buffers = [];
protected $r_buffers = [];
protected $relations = []; // tokens-descriptors
protected $subjections = []; // descriptors-users
protected $conn_states = [];
protected $ctrl_states = [];
protected $locked_dscs = [];
protected $broadcasts = [];
protected $current_bcast = 0;
protected $broadcast_ptr = 0;
protected $min_conn_descriptor = 0;
protected $max_conn_descriptor = 0;
protected function onStart()
{
}
protected function onHandshake($e_buffer, $descriptor)
{
}
protected function onTextMessage($e_buffer, $descriptor, &$message)
{
}
protected function onBinaryMessage($e_buffer, $descriptor, &$message)
{
}
/**
* constructor
*
* See config description in 'Configuration' section (README.md)
* You should set your own secret,
* otherwise all connections will be refused
*
* @param array $config initial parameters
*/
public function __construct($config)
{
if (!extension_loaded('event')) {
$this->error = 'The Event PECL extension required';
return;
}
$this->server_sockets =
empty($config['servers']) ? [''] : $config['servers'];
$this->control_socket =
empty($config['control']) ? '' : $config['control'];
$this->pid_file =
empty($config['pid']) ? '' : $config['pid'];
$this->domains =
empty($config['domains']) ? [] : $config['domains'];
$this->secret =
empty($config['secret']) ? random_bytes(16) : $config['secret'];
$this->origins =
empty($config['origins']) ? [] : $config['origins'];
foreach (array_merge($this->server_sockets,
[$this->control_socket, $this->pid_file]) as $path
) {
if ((substr($path, 0, 7) == 'unix://') ||
(substr($path, -4) == '.pid')
) {
$path = str_replace('unix://', '', $path);
$path = substr($path, 0, strrpos($path, '/'));
if (!file_exists($path) || !is_dir($path)) {
$this->error = "Directory {$path} does not exist";
return;
}
}
}
}
/**
* init servers and start eventbase infinite loop
*
* There is infinite loop here, but it can be broken by
* SIGTERM sended to process. Also it may not starts
* because of error in constructor.
*
* @return string error (empty, if all is correct)
*/
public function start()
{
if ($this->error) {
return $this->error;
}
$pid = file_exists($this->pid_file) ?
(int)file_get_contents($this->pid_file) : 0;
if ($pid && (posix_getpgid($pid) !== false)) {
return 'Server already started';
}
$error = $this->stop(true);
if ($error) {
return $error;
}
if (!file_put_contents($this->pid_file, posix_getpid())) {
return "Unable to write pid to {$this->pid_file}";
}
$servers = [];
foreach ($this->server_sockets as $serv_sock) {
$server = @stream_socket_server($serv_sock, $errno, $errstr);
if (!$server) {
return "Unable to create socket server {$serv_sock}\n"
."Error {$errno}".(empty($errstr) ? '' : ": {$errstr}");
}
if (!stream_set_blocking($server, false)) {
return "Unable to set blocking mode for {$serv_sock}";
}
$servers[] = $server;
}
$control = @stream_socket_server($this->control_socket, $errno, $errstr);
if (!$control) {
return "Unable to create socket server {$this->control_socket}\n"
."Error {$errno}".(empty($errstr) ? '' : ": {$errstr}");
}
if (!stream_set_blocking($control, false)) {
return "Unable to set blocking mode for {$this->control_socket}";
}
$base = new \EventBase();
foreach ($servers as $key => $server) {
$server_el = new \EventListener($base,
[$this, 'serverAccept'], $base,
\EventListener::OPT_CLOSE_ON_FREE |
\EventListener::OPT_REUSEABLE,
-1, $server
);
$this->server_els[$key] = $server_el;
$this->servers_loads[$server_el->fd] = 0;
}
$this->control_el = new \EventListener($base,
[$this, 'controlAccept'], $base,
\EventListener::OPT_CLOSE_ON_FREE | \EventListener::OPT_REUSEABLE,
-1, $control
);
$this->onStart();
if ($this->error) {
return $this->error;
}
echo date('Y-m-d H:i:s ')."Started successfully\n";
$base->dispatch(); // infinite loop
return $this->error;
}
/**
* stop server if started
*
* @param boolean $silent
* @return string error (empty, if all is correct)
*/
public function stop($silent = false)
{
if ($this->error) {
return $this->error;
}
$pid = file_exists($this->pid_file) ?
(int)file_get_contents($this->pid_file) : 0;
if (!$pid) {
return $silent ? '' : 'Server is not running';
}
$alive = (posix_getpgid($pid) !== false);
if ($alive && !posix_kill($pid, SIGTERM)) {
return 'Unable to send kill signal';
}
$alive = (posix_getpgid($pid) !== false);
if ($alive) {
echo date('Y-m-d H:i:s ');
echo 'Waiting for process termination (5s max)';
}
for ($i = 0; ($i < 20) && $alive; $i++) {
$alive = (posix_getpgid($pid) !== false);
if ($alive) {
usleep(250000);
}
if ($i % 4 == 3) {
echo '.';
}
}
if ($i) echo "\n";
if ($alive) {
return 'Unable to stop server';
}
if (!unlink($this->pid_file)) {
return 'Unable to unlink pid file';
}
foreach (array_merge($this->server_sockets,
[$this->control_socket]) as $chk_socket
) {
if (substr($chk_socket, 0, 7) == 'unix://') {
$chk_socket = substr($chk_socket, 7);
if (file_exists($chk_socket)) {
if (!unlink($chk_socket)) {
return "Unable to unlink socket {$chk_socket}";
}
}
}
}
echo date('Y-m-d H:i:s ')."Stopped successfully\n";
return '';
}
/**
* restart server
*
* @return string error (empty, if all is correct)
*/
public function restart()
{
if ($this->error) {
return $this->error;
}
$error = $this->stop(true);
if ($error) {
return $error;
}
$error = $this->start();
if ($error) {
return $error;
}
return '';
}
/**
* main server connection accept (new connection) callback
*
* @param EventListener $listener EventListener associated object
* @param integer $descriptor new connection associated file descriptor
* @param array $address IP (index 0) and port (index 1)
* @param EventBase $base EventBase associated object
*/
public function serverAccept($listener, $descriptor, $address, $base)
{
$this->servers_loads[$listener->fd]++;
if (!$this->min_conn_descriptor) {
$this->min_conn_descriptor = $descriptor;
}
if ($this->max_conn_descriptor < $descriptor) {
$this->max_conn_descriptor = $descriptor;
}
$e_buffer = new \EventBufferEvent($base, $descriptor,
\EventBufferEvent::OPT_CLOSE_ON_FREE,
[$this, 'serverRead'], [$this, 'serverWrite'],
[$this, 'serverEvent'], $listener->fd
);
$e_buffer->setTimeouts(5.0, 1.0);
$e_buffer->enable(\Event::READ | \Event::WRITE | \Event::PERSIST);
$this->e_buffers[$descriptor] = $e_buffer;
$this->r_buffers[$descriptor] = '';
$this->conn_states[$descriptor] = self::ALIVE;
}
/**
* main server connection error/close/timeout event callback
*
* @param EventBufferEvent $e_buffer EventBufferEvent associated object
* @param integer $mask logical disjunction of the Event class constants
* @param integer $listener_fd associated EventListener file descriptor
*/
public function serverEvent($e_buffer, $mask, $listener_fd)
{
$descriptor = $e_buffer->fd;
if ($mask & \EventBufferEvent::TIMEOUT) {
$state =& $this->conn_states[$descriptor];
if ((~$state) & (self::HANDSHAKE | self::ALIVE | self::READY)) {
$mask |= \EventBufferEvent::ERROR;
} else {
$state &= ~self::ALIVE;
$e_buffer->write("\x89\x00");
$e_buffer->enable(\Event::READ);
}
}
if ($mask & (\EventBufferEvent::ERROR | \EventBufferEvent::EOF)) {
$this->servers_loads[$listener_fd]--;
$e_buffer->disable(\Event::READ | \Event::WRITE);
unset($this->e_buffers[$descriptor]);
unset($this->r_buffers[$descriptor]);
unset($this->conn_states[$descriptor]);
unset($this->subjections[$descriptor]);
$relations =& $this->relations;
if (($relation = array_search($descriptor, $relations)) !== false) {
unset($relations[$relation]);
}
if ($descriptor == $this->max_conn_descriptor) {
$max_fd =& $this->max_conn_descriptor;
$min_fd =& $this->min_conn_descriptor;
$e_buffers =& $this->e_buffers;
while (!isset($e_buffers[$max_fd]) && ($max_fd > $min_fd))
{
$max_fd--;
}
}
}
}
/**
* main server connection 'write end' event callback
*
* @param EventBufferEvent $e_buffer EventBufferEvent associated object
* @param integer $listener_fd associated EventListener file descriptor
*/
public function serverWrite($e_buffer, $listener_fd)
{
$descriptor = $e_buffer->fd;
if ($this->conn_states[$descriptor] & self::CLOSED) {
// if conn isn't hsk'ed - it's bad! Feature is coming soon...
$this->serverEvent(
$e_buffer, \EventBufferEvent::ERROR, $listener_fd
);
}
if (!empty($this->broadcasts) &&
($this->broadcast_ptr == $descriptor)
) {
$conn_states =& $this->conn_states;
$bcast_ptr =& $this->broadcast_ptr;
do
{
do
{
$bcast_ptr++;
}
while (($bcast_ptr <= $this->max_conn_descriptor) &&
(!isset($conn_states[$bcast_ptr]) ||
!($conn_states[$bcast_ptr] & self::READY)
)
);
if ($bcast_ptr > $this->max_conn_descriptor) {
unset($this->broadcasts[$this->current_bcast++]);
$bcast_ptr = $this->min_conn_descriptor - 1;
} else {
break;
}
}
while (!empty($this->broadcasts));
if (!empty($this->broadcasts)) {
$message =& $this->broadcasts[$this->current_bcast];
$this->e_buffers[$bcast_ptr]->write($message);
}
}
}
/**
* main server connection 'ready-to-read' event callback
*
* @param EventBufferEvent $e_buffer EventBufferEvent associated object
* @param integer $listener_fd associated EventListener file descriptor
*/
public function serverRead($e_buffer, $listener_fd)
{
$descriptor = $e_buffer->fd;
$state =& $this->conn_states[$descriptor];
if (($state & self::CLOSING) &&
(time() - $state > self::ALIVE_INTERVAL)
) {
$this->serverEvent(
$e_buffer, \EventBufferEvent::ERROR, $listener_fd
);
return;
}
$buffer_limit = ($state & self::HANDSHAKE) ?
self::MAX_BUFFER_LEN : self::MAX_LEN_NO_HSK;
$r_buffer =& $this->r_buffers[$descriptor];
$len = strlen($r_buffer);
$diff_len = $len;
do
{
$data = $e_buffer->read($buffer_limit - $len);
$r_buffer .= $data;
$extracted = strlen($data);
$len += $extracted;
}
while ($extracted && ($len < $buffer_limit));
$diff_len = $len - $diff_len;
if ($len == $buffer_limit) {
$state |= self::CLOSED;
$state &= ~self::READY;
if ($state & self::HANDSHAKE) {
$e_buffer->write("\x88\x11\x03\xF1buffer overflow");
return;
}
$e_buffer->write(
"HTTP/1.1 400 Bad Request (Request Header Too Long)\r\n"
."Connection: close\r\n\r\n"
);
return;
}
// start handshake
if (!($state & self::HANDSHAKE)) {
if (substr($r_buffer, -4) !== "\r\n\r\n") {
if ($diff_len < self::MIN_HSK_FRAGMENT) {
$state |= self::CLOSED;
$e_buffer->write(
"HTTP/1.1 400 Bad Request (Fragment Too Small)\r\n"
."Connection: close\r\n\r\n"
);
}
return;
}
$headers = explode("\r\n", $r_buffer, 2);
$r_buffer = '';
$start_string = trim($headers[0]);
if (empty($headers[1]) ||
!preg_match('/^GET .+ HTTP\/[1-9]\.[0-9]$/', $start_string)
) {
$state |= self::CLOSED;
$e_buffer->write(
"HTTP/1.1 400 Bad Request\r\n"
."Connection: close\r\n\r\n"
);
return;
}
$headers = explode("\r\n", $headers[1]);
$h_len = count($headers);
$headers_normalized = [];
$headers_normalized[0] = trim($headers[0]);
for ($i = 1, $p = 0; $i < $h_len; $i++) {
if ($headers[$i] === '') continue;
if ($headers[$i][0] == "\t" || $headers[$i][0] == ' ') {
$headers_normalized[$p] .= trim($headers[$i]);
continue;
}
$headers_normalized[++$p] = $headers[$i];
}
$headers = [];
$cookies = [];
foreach ($headers_normalized as $header) {
$parts = explode(':', $header, 2);
if (!isset($parts[1])) {
$state |= self::CLOSED;
$e_buffer->write(
"HTTP/1.1 400 Bad Request\r\n"
."Connection: close\r\n\r\n"
);
return;
}
$headername = strtolower($parts[0]);
if (in_array($headername, [
'host', 'upgrade', 'connection', 'origin',
'sec-websocket-key', 'sec-websocket-version', 'cookie'
])) {
if ($headername != 'cookie') {
if ($headername != 'connection') {
$headers[$headername] = trim($parts[1]);
} else {
if (isset($headers['connection'])) {
$headers['connection'] .= ', '.trim($parts[1]);
} else {
$headers['connection'] = trim($parts[1]);
}
}
continue;
}
$pairs = explode('; ', trim($parts[1]));
foreach ($pairs as $cookie_pair) {
$pair = explode('=', trim($cookie_pair), 2);
if (!empty($pair[1]) && in_array($pair[0],
['token', 'user', 'time', 'digest']
)) {
$cookies[$pair[0]] = $pair[1];
}
}
}
}
if (!$this->authCheck($cookies)) {
$state |= self::CLOSED;
$e_buffer->write(
"HTTP/1.1 403 Forbidden\r\n"
."Connection: close\r\n\r\n"
);
return;
}
$relations =& $this->relations;
if (array_key_exists($cookies['token'], $relations)) {
$state |= self::CLOSED;
$e_buffer->write(
"HTTP/1.1 429 Too Many Requests\r\n"
."Retry-After: 15\r\n"
."Connection: close\r\n\r\n"
);
return;
}
if (empty($headers['host']) ||
!isset($headers['upgrade']) ||
($headers['upgrade'] !== 'websocket') ||
!isset($headers['connection']) ||
!in_array('Upgrade', explode(', ', $headers['connection'])) ||
!isset($headers['origin']) ||
!$this->originCheck($headers['origin']) ||
empty($headers['sec-websocket-key']) ||
!isset($headers['sec-websocket-version']) ||
($headers['sec-websocket-version'] !== '13')
) {
$state |= self::CLOSED;
$e_buffer->write(
"HTTP/1.1 400 Bad Request\r\n"
."Connection: close\r\n\r\n"
);
return;
}
$users =& $this->subjections;
if (count(array_keys($users, $cookies['user'])) ==
self::MAX_CONNS_PER_USER
) {
echo date('Y-m-d H:i:s ')."User {$cookies['user']} "
."has presumably violated MAX_CONNS_PER_USER limit\n";
$state |= self::CLOSED;
$e_buffer->write(
"HTTP/1.1 429 Too Many Requests\r\n"
."Connection: close\r\n\r\n"
);
return;
}
$accept = base64_encode(
pack('H*', sha1($headers['sec-websocket-key']
.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))
);
$state |= self::HANDSHAKE | self::READY;
$e_buffer->setTimeouts(self::ALIVE_INTERVAL, 1.0);
$e_buffer->write(
"HTTP/1.1 101 Switching Protocols\r\n"
."Upgrade: websocket\r\n"
."Connection: Upgrade\r\n"
."Sec-WebSocket-Accept: {$accept}\r\n\r\n"
);
$state |= ((int)$cookies['time'] + self::WS_TOKEN_LIFETIME) & ~0x1F;
$relations[$cookies['token']] = $descriptor;
$users[$descriptor] = $cookies['user'];
$this->onHandshake($e_buffer, $descriptor);
return;
}
// end handshake
// start lifetime check
if (($state < time()) &&
!($state & self::CLOSING)
) {
$state |= self::CLOSING;
$state &= ~self::READY;
$e_buffer->write("\x88\x09\x03\xE8expired");
}
// end lifetime check
// start decode
$messages = [];
$opcodes = [];
$msg_pointer = 0;
$offset = 0;
$msg_len = 0;
do
{
$frame_len = 2;
if ($frame_len > $len - $offset) break;
$first_of_frame = ord($r_buffer[$offset]);
$second_of_frame = ord($r_buffer[$offset + 1]);
$payload_len = $second_of_frame & 0x7F;
if ($payload_len > 125) {
if ($payload_len == 127) {
$frame_len += 8;
if ($frame_len > $len - $offset) break;
$payload_len =
unpack('J', substr($r_buffer, $offset + 2, 8))[1];
} else {
$frame_len += 2;
if ($frame_len > $len - $offset) break;
$payload_len =
unpack('n', substr($r_buffer, $offset + 2, 2))[1];
}
}
if ($second_of_frame & 0x80) {
$frame_len += 4;
if ($frame_len > $len - $offset) break;
}
$frame_len += $payload_len;
if ($frame_len > $len - $offset) break;
$offset += $frame_len;
if (!($first_of_frame & 0x80)) continue;
$pointer = $msg_pointer;
$messages[$msg_len] = '';
$opcodes[$msg_len] = ord($r_buffer[$pointer]) & 0x0F;
do
{
$pointer++;
$second_of_frame = ord($r_buffer[$pointer++]);
$payload_len = $second_of_frame & 0x7F;
if (!$payload_len) {
if ($second_of_frame & 0x80) $pointer += 4;
continue;
}
if ($payload_len > 125) {
if ($payload_len == 127) {
$payload_len =
unpack('J', substr($r_buffer, $pointer, 8))[1];
$pointer += 8;
} else {
$payload_len =
unpack('n', substr($r_buffer, $pointer, 2))[1];
$pointer += 2;
}
}
$mask = 0;
if ($second_of_frame & 0x80) {
$mask = unpack('N',
substr($r_buffer, $pointer, 4)
)[1];
$pointer += 4;
} else {
$this->serverEvent(
$e_buffer, \EventBufferEvent::ERROR, $listener_fd
);
return;
}
$appendix_len = (4 - ($payload_len % 4)) % 4;
$appendix = str_repeat("\0", $appendix_len);
$data = unpack('N*',
substr($r_buffer, $pointer, $payload_len).$appendix
);
$data_len = ($payload_len + $appendix_len) / 4;
for ($i = 1; $i <= $data_len; $i++) {
$data[$i] ^= $mask;
}
$messages[$msg_len] .=
substr(pack('N*', ...$data), 0, $payload_len);
$pointer += $payload_len;
}
while ($pointer != $offset);
$msg_pointer = $offset;
$msg_len++;
}
while ($offset < $len);
if ($msg_pointer) {
$r_buffer = substr($r_buffer, $msg_pointer);
}
// end decode
// start protocol dependencies
for ($i = 0; $i < $msg_len; $i++) {
switch ($opcodes[$i])
{
case 1:
$this->onTextMessage(
$e_buffer, $descriptor, $messages[$i]
);
break;
case 2:
$this->onBinaryMessage(
$e_buffer, $descriptor, $messages[$i]
);
break;
case 8:
if ($state & self::CLOSING) {
$this->serverEvent(
$e_buffer, \EventBufferEvent::ERROR, $listener_fd
);
return;
}
$state |= self::CLOSED;
if (strlen($messages[$i]) > 1) {
$close_code = substr($messages[$i], 0, 2);
$e_buffer->write("\x88\x02{$close_code}");
} else {
$e_buffer->write("\x88\x00");
}
break;
case 9:
$ping_len = strlen($messages[$i]);
if ($ping_len > 125) {
if ($ping_len > 65535) {
$e_buffer->write(
"\x8A\x7F".pack('J', $ping_len).$messages[$i]
);
} else {
$e_buffer->write(
"\x8A\x7E".pack('n', $ping_len).$messages[$i]
);
}
} else {
$e_buffer->write("\x8A".chr($ping_len).$messages[$i]);
}
break;
case 10:
$state |= self::ALIVE;
break;
}
}
// end protocol dependencies
}
/**
* authentication with cookies
*
* @param array $cookies
* @return boolean permission
*/
protected function authCheck(&$cookies)
{
return !(empty($cookies['token']) ||
empty($cookies['digest']) ||
empty($cookies['user']) ||
empty($cookies['time']) ||
(time() - (int)$cookies['time'] > self::WS_TOKEN_LIFETIME) ||
($cookies['digest'] != md5("{$this->secret}{$cookies['user']}"
."{$cookies['token']}{$cookies['time']}"))
);
}
/**
* origin check
*
* @param string $origin
* @return boolean permission
*/
protected function originCheck($origin)
{
return in_array($origin, $this->origins);
}
/**
* control server connection accept (new connection) callback
*
* @param EventListener $listener EventListener associated object
* @param integer $descriptor associated file descriptor
* @param array $address array with IP (index 0) and port (index 1)
* @param EventBase $base EventBase object associated with event
*/
public function controlAccept($listener, $descriptor, $address, $base)
{
$e_buffer = new \EventBufferEvent($base, $descriptor,
\EventBufferEvent::OPT_CLOSE_ON_FREE,
[$this, 'controlRead'], [$this, 'controlWrite'],
[$this, 'controlEvent'], $descriptor
);
$e_buffer->setTimeouts(1.0, 1.0);
$e_buffer->enable(\Event::READ | \Event::WRITE | \Event::PERSIST);
$this->e_buffers[$descriptor] = $e_buffer;
$this->r_buffers[$descriptor] = '';
$this->ctrl_states[$descriptor] = self::ALIVE;
}
/**
* control server connection error/close/timeout event callback
*
* @param EventBufferEvent $e_buffer EventBufferEvent associated object
* @param integer $mask logical disjunction of the Event class constants
* @param integer $descriptor associated file descriptor
*/
public function controlEvent($e_buffer, $mask, $descriptor)
{
$state =& $this->ctrl_states[$descriptor];
if ($mask & \EventBufferEvent::TIMEOUT) {
if ($state & self::ALIVE) {
$state &= ~self::ALIVE;
$e_buffer->write('0p'); // send ping
$e_buffer->enable(\Event::READ);
} else {
$mask |= \EventBufferEvent::ERROR;
}
}
if ($mask & (\EventBufferEvent::ERROR | \EventBufferEvent::EOF)) {
$e_buffer->disable(\Event::READ | \Event::WRITE);
unset($this->e_buffers[$descriptor]);
unset($this->r_buffers[$descriptor]);
unset($this->ctrl_states[$descriptor]);
$locked_dscs =& $this->locked_dscs;
if (isset($locked_dscs[$descriptor])) {
$relations =& $this->relations;
if (isset($relations[$locked_dscs[$descriptor]])) {
$related_ws = $relations[$locked_dscs[$descriptor]];
// now close related locked websocket
$this->conn_states[$related_ws] |= self::CLOSING;
$this->e_buffers[$related_ws]->write(
"\x88\x12\x03\xF3framesource lost"
);
}
unset($locked_dscs[$descriptor]);
}
}
}
/**
* control server connection 'write ends' event callback
*
* @param EventBufferEvent $e_buffer EventBufferEvent associated object
* @param integer $descriptor associated file descriptor
*/
public function controlWrite($e_buffer, $descriptor)
{
if (!($this->ctrl_states[$descriptor] & self::CLOSED)) return;
$this->controlEvent($e_buffer, \EventBufferEvent::ERROR, $descriptor);
}
/**
* control server connection 'ready-to-read' event callback
*
* @param EventBufferEvent $e_buffer EventBufferEvent associated object
* @param integer $descriptor associated file descriptor
*/
public function controlRead($e_buffer, $descriptor)
{
$state =& $this->ctrl_states[$descriptor];
$r_buffer =& $this->r_buffers[$descriptor];
$len = strlen($r_buffer);
do
{
$data = $e_buffer->read(self::MAX_C_BUFFER_LEN - $len);
$r_buffer .= $data;
$extracted = strlen($data);
$len += $extracted;
}
while ($extracted && ($len < self::MAX_C_BUFFER_LEN));
if ($len == self::MAX_C_BUFFER_LEN) {
$e_buffer->write('0E'); // buffer overflow
$state |= self::CLOSED;
return;
}
$offset = 0;
do
{
$pack_len = (string)((int)substr($r_buffer, $offset));
$head_len = strlen($pack_len);
$offset = strpos($r_buffer, $pack_len, $offset);
if ($offset === false) {
if (!$pack_len) break;
$e_buffer->write('0E'); // protocol error
$state |= self::CLOSED;
return;
}
$pack_len = (int)$pack_len;
if ($head_len + $pack_len + $offset + 1 > $len) break;
$offset += $head_len;
$command = substr($r_buffer, $offset, 1);
$offset++;
switch ($command)
{
case 'b': // broadcast no-framed short text
case 'B': // broadcast no-framed short binary
$this->sendBroadcast(
substr($r_buffer, $offset, $pack_len), $command == 'B'
);
break;
case 'c': // confirmed addressed no-framed short text
case 'C': // confirmed addressed no-framed short binary
case 'd': // unconfirmed addressed no-framed short text
case 'D': // unconfirmed addressed no-framed short binary
$confirm = ($command == 'c' || $command == 'C');
if ($pack_len < self::AUTH_TOKEN_LEN) {
$e_buffer->write('0E'); // protocol error
$state |= self::CLOSED;
return;
}
$token = substr($r_buffer, $offset, self::AUTH_TOKEN_LEN);
$destination =
isset($this->relations[$token]) ?
$this->relations[$token] : 0;
$success = ($destination &&
($this->conn_states[$destination] & self::READY));
$offset += self::AUTH_TOKEN_LEN;
$pack_len -= self::AUTH_TOKEN_LEN;
if (!$pack_len || !$success) {
if ($confirm) { // (N)ACK ~ it can be conn status check
$e_buffer->write(self::AUTH_TOKEN_LEN
.($success ? 'A' : 'N').$token
);
}
break;
}
$success = $this->sendDirect(
substr($r_buffer, $offset, $pack_len),
$destination,
($command == 'C' || $command == 'D')
);
if ($confirm) {
$e_buffer->write(self::AUTH_TOKEN_LEN
.($success ? 'A' : 'N').$token
);
}
break;
case 'l': // lock client for fragmented send
if ($pack_len != self::AUTH_TOKEN_LEN) {
$e_buffer->write('0E'); // protocol error
$state |= self::CLOSED;
return;
}
$token = substr($r_buffer, $offset, self::AUTH_TOKEN_LEN);
$destination =
isset($this->relations[$token]) ?
$this->relations[$token] : 0;
if ($destination &&
($this->conn_states[$destination] & self::READY)
) { // lock it (clear READY flag)
$this->conn_states[$destination] &= ~self::READY;
$this->locked_dscs[$descriptor] = $token;
$e_buffer->write(self::AUTH_TOKEN_LEN."A{$token}");
} else { // unable to lock
$e_buffer->write(self::AUTH_TOKEN_LEN."N{$token}");
}
break;
case 'f': // addressed text frame (the first, not FIN)
case 'F': // addressed binary frame (the first, not FIN)
case 'i': // addressed text frame (intermediate, not FIN)
case 'I': // addressed binary frame (intermediate, not FIN)
case 's': // addressed text frame (the last, FIN)
case 'S': // addressed binary frame (the last, FIN)
$token = (isset($this->locked_dscs[$descriptor]) ?
$this->locked_dscs[$descriptor] : '');
$destination =
$token && isset($this->relations[$token]) ?
$this->relations[$token] : 0;
if (!$destination) {
unset($this->locked_dscs[$descriptor]);
$e_buffer->write('0n'); // NACK
break;
}
switch ($command)