-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathTcpConnection.php
More file actions
1270 lines (1157 loc) · 34.4 KB
/
Copy pathTcpConnection.php
File metadata and controls
1270 lines (1157 loc) · 34.4 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
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
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Workerman\Connection;
use JsonSerializable;
use RuntimeException;
use stdClass;
use Throwable;
use Workerman\Events\EventInterface;
use Workerman\Protocols\Http;
use Workerman\Protocols\Http\Request;
use Workerman\Timer;
use Workerman\Worker;
use function ceil;
use function count;
use function fclose;
use function feof;
use function fread;
use function function_exists;
use function fwrite;
use function is_object;
use function is_resource;
use function key;
use function method_exists;
use function posix_getpid;
use function restore_error_handler;
use function set_error_handler;
use function stream_set_blocking;
use function stream_set_read_buffer;
use function stream_socket_shutdown;
use function stream_socket_enable_crypto;
use function stream_socket_get_name;
use function strlen;
use function strrchr;
use function strrpos;
use function substr;
use function var_export;
use const PHP_INT_MAX;
use const STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
use const STREAM_CRYPTO_METHOD_SSLv23_SERVER;
use const STREAM_CRYPTO_METHOD_SSLv2_CLIENT;
use const STREAM_CRYPTO_METHOD_SSLv2_SERVER;
use const STREAM_SHUT_WR;
/**
* TcpConnection.
* @property string $websocketType
* @property string|null $websocketClientProtocol
* @property string|null $websocketOrigin
*/
class TcpConnection extends ConnectionInterface implements JsonSerializable
{
/**
* Read buffer size.
*
* @var int
*/
public const READ_BUFFER_SIZE = 87380;
/**
* Status initial.
*
* @var int
*/
public const STATUS_INITIAL = 0;
/**
* Status connecting.
*
* @var int
*/
public const STATUS_CONNECTING = 1;
/**
* Status connection established.
*
* @var int
*/
public const STATUS_ESTABLISHED = 2;
/**
* Status ending (graceful close: write -> FIN -> linger/drain -> close).
*
* @var int
*/
public const STATUS_ENDING = 4;
/**
* Status closing.
*
* @var int
*/
public const STATUS_CLOSING = 8;
/**
* Status closed.
*
* @var int
*/
public const STATUS_CLOSED = 16;
/**
* Maximum string length for cache
*
* @var int
*/
public const MAX_CACHE_STRING_LENGTH = 2048;
/**
* Maximum cache size.
*
* @var int
*/
public const MAX_CACHE_SIZE = 512;
/**
* Tcp keepalive interval.
*/
public const TCP_KEEPALIVE_INTERVAL = 55;
/**
* Emitted when socket connection is successfully established.
*
* @var ?callable
*/
public $onConnect = null;
/**
* Emitted before websocket handshake (Only called when protocol is ws).
*
* @var ?callable
*/
public $onWebSocketConnect = null;
/**
* Emitted after websocket handshake (Only called when protocol is ws).
*
* @var ?callable
*/
public $onWebSocketConnected = null;
/**
* Emitted when websocket connection is closed (Only called when protocol is ws).
*
* @var ?callable
*/
public $onWebSocketClose = null;
/**
* Emitted when data is received.
*
* @var ?callable
*/
public $onMessage = null;
/**
* Emitted when the other end of the socket sends a FIN packet.
*
* @var ?callable
*/
public $onClose = null;
/**
* Emitted when an error occurs with connection.
*
* @var ?callable
*/
public $onError = null;
/**
* Emitted when the send buffer becomes full.
*
* @var ?callable
*/
public $onBufferFull = null;
/**
* Emitted when send buffer becomes empty.
*
* @var ?callable
*/
public $onBufferDrain = null;
/**
* Transport (tcp/udp/unix/ssl).
*
* @var string
*/
public string $transport = 'tcp';
/**
* Which worker belong to.
*
* @var ?Worker
*/
public ?Worker $worker = null;
/**
* Bytes read.
*
* @var int
*/
public int $bytesRead = 0;
/**
* Bytes written.
*
* @var int
*/
public int $bytesWritten = 0;
/**
* Connection->id.
*
* @var int
*/
public int $id = 0;
/**
* A copy of $worker->id which used to clean up the connection in worker->connections
*
* @var int
*/
protected int $realId = 0;
/**
* Sets the maximum send buffer size for the current connection.
* OnBufferFull callback will be emitted When send buffer is full.
*
* @var int
*/
public int $maxSendBufferSize = 1048576;
/**
* Context.
*
* @var ?stdClass
*/
public ?stdClass $context = null;
/**
* Internal use only. Do not access or modify from application code.
*
* @internal Framework internal API
* @deprecated Do not set this property, use $response->header() or $response->widthHeaders() instead
* @var array
*/
public array $headers = [];
/**
* Is safe.
*
* @var bool
*/
protected bool $isSafe = true;
/**
* Default send buffer size.
*
* @var int
*/
public static int $defaultMaxSendBufferSize = 1048576;
/**
* Sets the maximum acceptable packet size for the current connection.
*
* @var int
*/
public int $maxPackageSize = 1048576;
/**
* Default maximum acceptable packet size.
*
* @var int
*/
public static int $defaultMaxPackageSize = 10485760;
/**
* Default linger timeout for graceful end (seconds).
*
* @var float
*/
public static float $defaultLingerTimeout = 1.0;
/**
* Linger timeout for graceful end (seconds).
*
* @var float
*/
public float $lingerTimeout = 1.0;
/**
* Id recorder.
*
* @var int
*/
protected static int $idRecorder = 1;
/**
* Socket
*
* @var resource
*/
protected $socket = null;
/**
* Send buffer.
*
* @var string
*/
protected string $sendBuffer = '';
/**
* Receive buffer.
*
* @var string
*/
protected string $recvBuffer = '';
/**
* Current package length.
*
* @var int
*/
protected int $currentPackageLength = 0;
/**
* Connection status.
*
* @var int
*/
protected int $status = self::STATUS_ESTABLISHED;
/**
* Linger timer id for end().
*
* @var int
*/
protected int $endLingerTimerId = 0;
/**
* Whether write side has been shutdown (FIN sent) during end().
*
* @var bool
*/
protected bool $endWriteShutdown = false;
/**
* Remote address.
*
* @var string
*/
protected string $remoteAddress = '';
/**
* Is paused.
*
* @var bool
*/
protected bool $isPaused = false;
/**
* SSL handshake completed or not.
*
* @var bool
*/
protected bool|int $sslHandshakeCompleted = false;
/**
* All connection instances.
*
* @var array
*/
public static array $connections = [];
/**
* Status to string.
*
* @var array
*/
public const STATUS_TO_STRING = [
self::STATUS_INITIAL => 'INITIAL',
self::STATUS_CONNECTING => 'CONNECTING',
self::STATUS_ESTABLISHED => 'ESTABLISHED',
self::STATUS_CLOSING => 'CLOSING',
self::STATUS_ENDING => 'ENDING',
self::STATUS_CLOSED => 'CLOSED',
];
/**
* Construct.
*
* @param EventInterface $eventLoop
* @param resource $socket
* @param string $remoteAddress
*/
public function __construct(EventInterface $eventLoop, $socket, string $remoteAddress = '')
{
++self::$statistics['connection_count'];
$this->id = $this->realId = self::$idRecorder++;
if (self::$idRecorder === PHP_INT_MAX) {
self::$idRecorder = 0;
}
$this->socket = $socket;
stream_set_blocking($this->socket, false);
stream_set_read_buffer($this->socket, 0);
$this->eventLoop = $eventLoop;
$this->eventLoop->onReadable($this->socket, $this->baseRead(...));
$this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
$this->maxPackageSize = self::$defaultMaxPackageSize;
$this->lingerTimeout = self::$defaultLingerTimeout;
$this->remoteAddress = $remoteAddress;
static::$connections[$this->id] = $this;
$this->context = new stdClass();
}
/**
* Get status.
*
* @param bool $rawOutput
*
* @return int|string
*/
public function getStatus(bool $rawOutput = true): int|string
{
if ($rawOutput) {
return $this->status;
}
return self::STATUS_TO_STRING[$this->status];
}
/**
* Sends data on the connection.
*
* @param mixed $sendBuffer
* @param bool $raw
* @return bool|null
*/
public function send(mixed $sendBuffer, bool $raw = false): bool|null
{
if ($this->status === self::STATUS_ENDING || $this->status === self::STATUS_CLOSING || $this->status === self::STATUS_CLOSED) {
return false;
}
// Fix null to empty string.
$sendBuffer ??= '';
// Try to call protocol::encode($sendBuffer) before sending.
if (false === $raw && $this->protocol !== null) {
try {
$sendBuffer = $this->protocol::encode($sendBuffer, $this);
} catch(Throwable $e) {
$this->error($e);
}
if ($sendBuffer === '') {
return null;
}
}
if ($this->status !== self::STATUS_ESTABLISHED ||
($this->transport === 'ssl' && $this->sslHandshakeCompleted !== true)
) {
if ($this->sendBuffer && $this->bufferIsFull()) {
++self::$statistics['send_fail'];
return false;
}
$this->sendBuffer .= $sendBuffer;
$this->checkBufferWillFull();
return null;
}
// Attempt to send data directly.
if ($this->sendBuffer === '') {
if ($this->transport === 'ssl') {
$this->eventLoop->onWritable($this->socket, $this->baseWrite(...));
$this->sendBuffer = $sendBuffer;
$this->checkBufferWillFull();
return null;
}
$len = 0;
try {
$len = @fwrite($this->socket, $sendBuffer);
} catch (Throwable $e) {
Worker::log($e);
}
// send successful.
if ($len === strlen($sendBuffer)) {
$this->bytesWritten += $len;
return true;
}
// Send only part of the data.
if ($len > 0) {
$this->sendBuffer = substr($sendBuffer, $len);
$this->bytesWritten += $len;
} else {
// Connection closed?
if (!is_resource($this->socket) || feof($this->socket)) {
++self::$statistics['send_fail'];
if ($this->onError) {
try {
($this->onError)($this, static::SEND_FAIL, 'client closed');
} catch (Throwable $e) {
$this->error($e);
}
}
$this->destroy();
return false;
}
$this->sendBuffer = $sendBuffer;
}
$this->eventLoop->onWritable($this->socket, $this->baseWrite(...));
// Check if send buffer will be full.
$this->checkBufferWillFull();
return null;
}
if ($this->bufferIsFull()) {
++self::$statistics['send_fail'];
return false;
}
$this->sendBuffer .= $sendBuffer;
// Check if send buffer is full.
$this->checkBufferWillFull();
return null;
}
/**
* Get remote IP.
*
* @return string
*/
public function getRemoteIp(): string
{
$pos = strrpos($this->remoteAddress, ':');
if ($pos) {
return substr($this->remoteAddress, 0, $pos);
}
return '';
}
/**
* Get remote port.
*
* @return int
*/
public function getRemotePort(): int
{
if ($this->remoteAddress) {
return (int)substr(strrchr($this->remoteAddress, ':'), 1);
}
return 0;
}
/**
* Get remote address.
*
* @return string
*/
public function getRemoteAddress(): string
{
return $this->remoteAddress;
}
/**
* Get local IP.
*
* @return string
*/
public function getLocalIp(): string
{
$address = $this->getLocalAddress();
$pos = strrpos($address, ':');
if (!$pos) {
return '';
}
return substr($address, 0, $pos);
}
/**
* Get local port.
*
* @return int
*/
public function getLocalPort(): int
{
$address = $this->getLocalAddress();
$pos = strrpos($address, ':');
if (!$pos) {
return 0;
}
return (int)substr(strrchr($address, ':'), 1);
}
/**
* Get local address.
*
* @return string
*/
public function getLocalAddress(): string
{
if (!is_resource($this->socket)) {
return '';
}
return (string)@stream_socket_get_name($this->socket, false);
}
/**
* Get send buffer queue size.
*
* @return integer
*/
public function getSendBufferQueueSize(): int
{
return strlen($this->sendBuffer);
}
/**
* Get receive buffer queue size.
*
* @return integer
*/
public function getRecvBufferQueueSize(): int
{
return strlen($this->recvBuffer);
}
/**
* Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
*
* @return void
*/
public function pauseRecv(): void
{
if($this->eventLoop !== null){
$this->eventLoop->offReadable($this->socket);
}
$this->isPaused = true;
}
/**
* Resumes reading after a call to pauseRecv.
*
* @return void
*/
public function resumeRecv(): void
{
if ($this->isPaused === true) {
$this->eventLoop->onReadable($this->socket, $this->baseRead(...));
$this->isPaused = false;
$this->baseRead($this->socket, false);
}
}
/**
* Base read handler.
*
* @param resource $socket
* @param bool $checkEof
* @return void
*/
public function baseRead($socket, bool $checkEof = true): void
{
static $requests = [];
// SSL handshake.
if ($this->transport === 'ssl' && $this->sslHandshakeCompleted !== true) {
if ($this->doSslHandshake($socket)) {
$this->sslHandshakeCompleted = true;
if ($this->sendBuffer) {
$this->eventLoop->onWritable($socket, $this->baseWrite(...));
}
} else {
return;
}
}
$buffer = '';
try {
$buffer = @fread($socket, self::READ_BUFFER_SIZE);
} catch (Throwable) {
// do nothing
}
// Check connection closed.
if ($buffer === '' || $buffer === false) {
if ($checkEof && (!is_resource($socket) || feof($socket) || $buffer === false)) {
$this->destroy();
return;
}
} else {
$this->bytesRead += strlen($buffer);
if ($this->status === self::STATUS_ENDING) {
return;
}
if ($this->recvBuffer === '') {
if (!isset($buffer[static::MAX_CACHE_STRING_LENGTH]) && isset($requests[$buffer])) {
++self::$statistics['total_request'];
if ($this->protocol === Http::class) {
$request = $requests[$buffer];
$request->connection = $this;
try {
($this->onMessage)($this, $request);
} catch (Throwable $e) {
$this->error($e);
}
$request = clone $request;
$request->destroy();
$requests[$buffer] = $request;
return;
}
$request = $requests[$buffer];
try {
($this->onMessage)($this, $request);
} catch (Throwable $e) {
$this->error($e);
}
return;
}
$this->recvBuffer = $buffer;
} else {
$this->recvBuffer .= $buffer;
}
}
// If the application layer protocol has been set up.
if ($this->protocol !== null) {
while ($this->recvBuffer !== '' && !$this->isPaused) {
// The current packet length is known.
if ($this->currentPackageLength) {
// Data is not enough for a package.
$recvBufferLength = strlen($this->recvBuffer);
if ($this->currentPackageLength > $recvBufferLength) {
break;
}
} else {
// Get current package length.
try {
$this->currentPackageLength = $this->protocol::input($this->recvBuffer, $this);
} catch (Throwable $e) {
$this->currentPackageLength = -1;
Worker::safeEcho((string)$e);
}
// The packet length is unknown.
if ($this->currentPackageLength === 0) {
break;
} elseif ($this->currentPackageLength > 0 && $this->currentPackageLength <= $this->maxPackageSize) {
// Data is not enough for a package.
// Note: recalculate length here since protocol::input() may call consumeRecvBuffer().
$recvBufferLength = strlen($this->recvBuffer);
if ($this->currentPackageLength > $recvBufferLength) {
break;
}
} // Wrong package.
else {
Worker::safeEcho((string)(new RuntimeException("Protocol $this->protocol Error package. package_length=" . var_export($this->currentPackageLength, true))));
$this->destroy();
return;
}
}
// The data is enough for a packet.
++self::$statistics['total_request'];
// The current packet length is equal to the length of the buffer.
if ($recvBufferLength === $this->currentPackageLength) {
$oneRequestBuffer = $this->recvBuffer;
$this->recvBuffer = '';
} else {
// Get a full package from the buffer.
$oneRequestBuffer = substr($this->recvBuffer, 0, $this->currentPackageLength);
// Remove the current package from receive buffer.
$this->recvBuffer = substr($this->recvBuffer, $this->currentPackageLength);
}
// Reset the current packet length to 0.
$this->currentPackageLength = 0;
try {
if (!isset($oneRequestBuffer[static::MAX_CACHE_STRING_LENGTH]) && isset($requests[$oneRequestBuffer])) {
$request = $requests[$oneRequestBuffer];
if ($request instanceof Request) {
$request->connection = $this;
($this->onMessage)($this, $request);
$request = clone $request;
$request->destroy();
$requests[$oneRequestBuffer] = $request;
} else {
($this->onMessage)($this, $request);
}
continue;
}
// Decode request buffer before Emitting onMessage callback.
$request = $this->protocol::decode($oneRequestBuffer, $this);
if ((!is_object($request) || $request instanceof Request) && !isset($oneRequestBuffer[static::MAX_CACHE_STRING_LENGTH])) {
($this->onMessage)($this, $request);
if ($request instanceof Request) {
$request = clone $request;
$request->destroy();
}
$requests[$oneRequestBuffer] = $request;
if (count($requests) > static::MAX_CACHE_SIZE) {
unset($requests[key($requests)]);
}
continue;
}
($this->onMessage)($this, $request);
} catch (Throwable $e) {
$this->error($e);
}
}
return;
}
if ($this->recvBuffer === '' || $this->isPaused) {
return;
}
// Application protocol is not set.
++self::$statistics['total_request'];
try {
($this->onMessage)($this, $this->recvBuffer);
} catch (Throwable $e) {
$this->error($e);
}
// Clean receive buffer.
$this->recvBuffer = '';
}
/**
* Base write handler.
*
* @return void
*/
public function baseWrite(): void
{
$len = 0;
try {
if ($this->transport === 'ssl') {
$len = @fwrite($this->socket, $this->sendBuffer, 8192);
} else {
$len = @fwrite($this->socket, $this->sendBuffer);
}
} catch (Throwable) {
}
if ($len === strlen($this->sendBuffer)) {
$this->bytesWritten += $len;
$this->eventLoop->offWritable($this->socket);
$this->sendBuffer = '';
// Try to emit onBufferDrain callback when send buffer becomes empty.
if ($this->onBufferDrain) {
try {
($this->onBufferDrain)($this);
} catch (Throwable $e) {
$this->error($e);
}
}
if ($this->status === self::STATUS_ENDING) {
$this->endMaybeShutdownWrite();
}
if ($this->status === self::STATUS_CLOSING) {
if (!empty($this->context->streamSending)) {
return;
}
$this->destroy();
}
return;
}
if ($len > 0) {
$this->bytesWritten += $len;
$this->sendBuffer = substr($this->sendBuffer, $len);
} else {
++self::$statistics['send_fail'];
$this->destroy();
}
}
/**
* SSL handshake.
*
* @param resource $socket
* @return bool|int
*/
public function doSslHandshake($socket): bool|int
{
if (!is_resource($socket) || feof($socket)) {
$this->destroy();
return false;
}
$async = $this instanceof AsyncTcpConnection;
/**
* We disabled ssl3 because https://blog.qualys.com/ssllabs/2014/10/15/ssl-3-is-dead-killed-by-the-poodle-attack.
* You can enable ssl3 by the codes below.
*/
/*if($async){
$type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
}else{
$type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER | STREAM_CRYPTO_METHOD_SSLv3_SERVER;
}*/
if ($async) {
$type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
} else {
$type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER;
}
// Hidden error.
set_error_handler(static function (int $code, string $msg): bool {
if (!Worker::$daemonize) {
Worker::safeEcho(sprintf("SSL handshake error: %s\n", $msg));
}
return true;
});
$ret = stream_socket_enable_crypto($socket, true, $type);
restore_error_handler();
// Negotiation has failed.
if (false === $ret) {
$this->destroy();
return false;
}
if (0 === $ret) {
// There isn't enough data and should try again.
return 0;
}
return true;
}
/**
* This method pulls all the data out of a readable stream, and writes it to the supplied destination.
*
* @param self $dest
* @return void
*/
public function pipe(self $dest): void
{
$this->onMessage = fn ($source, $data) => $dest->send($data);
$this->onClose = fn () => $dest->close();
$dest->onBufferFull = fn () => $this->pauseRecv();
$dest->onBufferDrain = fn() => $this->resumeRecv();
}
/**
* Remove $length of data from receive buffer.
*
* @param int $length
* @return void
*/
public function consumeRecvBuffer(int $length): void
{
$this->recvBuffer = substr($this->recvBuffer, $length);
}
/**
* Close connection.
*
* @param mixed $data
* @param bool $raw
* @return void
*/
public function close(mixed $data = null, bool $raw = false): void
{
if ($this->status === self::STATUS_INITIAL || $this->status === self::STATUS_CONNECTING) {
$this->destroy();
return;
}
if ($this->status === self::STATUS_CLOSING || $this->status === self::STATUS_CLOSED) {
return;
}
if ($data !== null) {
$this->send($data, $raw);
}
$this->status = self::STATUS_CLOSING;
if ($this->sendBuffer === '') {
$this->destroy();
} else {
$this->pauseRecv();
}
}
/**
* Graceful end connection.
* It tries to: send response -> wait sendBuffer empty -> shutdown write(FIN) -> linger/drain reads -> close().
*