-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.php
More file actions
1789 lines (1496 loc) · 52.6 KB
/
Socket.php
File metadata and controls
1789 lines (1496 loc) · 52.6 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
/**
* qcEvents - Asyncronous Sockets
* Copyright (C) 2014 Bernd Holzmueller <bernd@quarxconnect.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
require_once ('qcEvents/IOStream.php');
require_once ('qcEvents/Interface/Timer.php');
require_once ('qcEvents/Trait/Timer.php');
require_once ('qcEvents/Promise.php');
/**
* Event Socket
* ------------
* Generic implementation to handle internet-based connections
*
* @class qcEvents_Socket
* @package qcEvents
* @revision 03
**/
class qcEvents_Socket extends qcEvents_IOStream implements qcEvents_Interface_Timer {
use qcEvents_Trait_Timer;
/* Error-types */
const ERROR_NET_UNKNOWN = 0;
const ERROR_NET_DNS_FAILED = -1;
const ERROR_NET_TLS_FAILED = -2;
const ERROR_NET_TIMEOUT = -110;
const ERROR_NET_REFUSED = -111;
const ERROR_NET_UNREACHABLE = -101;
/* Socket-Types */
const TYPE_TCP = 0;
const TYPE_UDP = 1;
const TYPE_UDP_SERVER = 2;
/* Timeouts */
const CONNECT_TIMEOUT = 5;
const UNREACHABLE_TIMEOUT = 10;
/* Buffers */
const READ_TCP_BUFFER = 4096;
const READ_UDP_BUFFER = 1500;
/* Defaults */
const DEFAULT_TYPE = qcEvents_Socket::TYPE_TCP;
const DEFAULT_PORT = null;
const FORCE_TYPE = null;
const FORCE_PORT = null;
/* NAT64-Prefix - if set map failed IPv4-connections to IPv6 */
public static $nat64Prefix = null;
/* Known unreachable addresses */
private static $Unreachables = array ();
/* Our connection-state */
private $Connected = false;
/* Socket-Type of this connection */
private $Type = self::TYPE_TCP;
/* Any assigned server-handle */
private $serverParent = null;
/* Bind local socket to this ip-address */
private $socketBindAddress = null;
/* Bind local socket to this port */
private $socketBindPort = null;
/* Set of addresses we are trying to connectl to */
private $socketAddresses = null;
/* The current address we are trying to connect to */
private $socketAddress = null;
/* Resolve-Function of connect-promise */
private $socketConnectResolve = null;
/* Reject-Function of connect-promise */
private $socketConnectReject = null;
/* Our current remote hostname */
private $remoteHost = '';
/* Address of our current remote host */
private $remoteAddr = '';
/* Out current remote port */
private $remotePort = 0;
/* Short-hand of remote hostname and port (for UDP-Server-Mode) */
private $remoteName = null;
/* Our current TLS-Status */
private $tlsEnabled = false;
/* Our desired TLS-Status */
private $tlsStatus = null;
/* Callbacks fired when tls-status was changed */
private $tlsCallbacks = array ();
/* Size for Read-Requests */
private $bufferSize = 0;
/* Local read-buffer */
private $readBuffer = '';
private $readBufferLength = 0;
/* Local write-buffer */
private $writeBuffer = '';
/* Time of last event on this socket */
private $lastEvent = 0;
/* Use our own internal resolver (which works asyncronously as well) */
private $internalResolver = true;
// {{{ isIPv4
/**
* Check if a given address is valid IPv4
*
* @param string $Address
*
* @access public
* @return bool
**/
public static function isIPv4 ($Address) {
// Split the address into its pieces
$Check = explode ('.', $Address);
// Check if there are exactly 4 blocks
if (count ($Check) != 4)
return false;
// Validate each block
foreach ($Check as $Block)
if (!is_numeric ($Block) || ($Block < 0) || ($Block > 255))
return false;
return true;
}
// }}}
// {{{ isIPv6
/**
* Check if a given address is valid IPv6
*
* @param string $Address
*
* @access public
* @return bool
**/
public static function isIPv6 ($Address) {
if (strlen ($Address) == 0)
return false;
if ($Address [0] == '[')
$Address = substr ($Address, 1, -1);
return (filter_var ($Address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false);
}
// }}}
// {{{ ip6toBinary
/**
* Convert an IP-Adress into an IPv6 binary address
*
* @param string $IP
*
* @access public
* @return string
+*/
public static function ip6toBinary ($IP) {
// Check for an empty ip
if (strlen ($IP) == 0)
return "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
// Check wheter to convert IPv4 to mapped IPv6
if (self::isIPv4 ($IP)) {
$N = explode ('.', $IP);
$IP = sprintf ('::ffff:%02x%02x:%02x%02x', (int)$N [0], (int)$N [1], (int)$N [2], (int)$N [3]);
}
// Check for square brackets
if ($IP [0] == '[')
$IP = substr ($IP, 1, -1);
// Split into pieces
$N = explode (':', $IP);
$C = count ($N);
if ($C < 2)
return false;
// Check for ugly mapped IPv4
if (($C == 4) && (strlen ($N [0]) == 0) && (strlen ($N [1]) == 0) && ($N [2] == 'ffff') && self::isIPv4 ($N [3])) {
$IPv4 = explode ('.', array_pop ($N));
$N [] = dechex (((int)$IPv4 [0] << 8) | ((int)$IPv4 [1]));
$N [] = dechex (((int)$IPv4 [2] << 8) | ((int)$IPv4 [3]));
}
// Make sure the IPv6 is fully qualified
if ($C != 8)
for ($i = 1; $i < $C; $i++) {
if (strlen ($N [$i]) != 0)
continue;
$N = array_merge (array_slice ($N, 0, $i), array_fill (0, (8 - count ($N)), '0'), array_slice ($N, $i));
break;
}
// Return binary
return pack ('nnnnnnnn', hexdec ($N [0]), hexdec ($N [1]), hexdec ($N [2]), hexdec ($N [3]), hexdec ($N [4]), hexdec ($N [5]), hexdec ($N [6]), hexdec ($N [7]));
}
// }}}
// {{{ ip6fromBinary
/**
* Create a human readbale IPv6-Address from its binary representation
*
* @param string
*
* @access public
* @return string
**/
public static function ip6fromBinary ($IP) {
// Make sure all bits are in place
if (strlen ($IP) != 16)
return false;
// Unpack as hex-digits
$IP = array_values (unpack ('H4a/H4b/H4c/H4d/H4e/H4f/H4g/H4h', $IP));
// Try to remove zero blocks
$b = $s = $c = $m = null;
for ($i = 0; $i < 8; $i++) {
$IP [$i] = ltrim ($IP [$i], '0');
if (strlen ($IP [$i]) == 0) {
if ($s === null) {
$s = $i;
$c = 1;
} else
$c++;
} elseif ($s !== null) {
if ($c > $m) {
for ($j = $b; $j < $b + $m; $j++)
$IP [$j] = '0';
$m = $c;
$b = $s;
} else
for ($j = $s; $j < $s + $c; $j++)
$IP [$j] = '0';
$s = $c = null;
}
}
if (($s !== null) && ($c > $m)) {
for ($j = $b; $j < $b + $m; $j++)
$IP [$j] = '0';
$m = $c;
$b = $s;
}
if (($b !== null) && ($m > 1))
$IP = array_merge (array_slice ($IP, 0, $b + ($b == 0 ? 2 : 1)), array_slice ($IP, $b + $m));
// Return the IPv6
return implode (':', $IP);
}
// }}}
// {{{ __construct
/**
* Create a new event-socket
*
* @param qcEvents_Base $Base (optional)
* @param mixed $Host (optional)
* @param int $Port (optional)
* @param enum $Type (optional)
* @param bool $enableTLS (optional)
*
* @access friendly
* @return void
**/
function __construct (qcEvents_Base $Base = null, $Host = null, $Port = null, $Type = null, $enableTLS = false) {
// Don't do anything withour an events-base
if ($Base === null)
return;
// Set our handler
$this->setEventBase ($Base);
// Check wheter to create a connection
if ($Host === null)
return;
$this->connect ($Host, $Port, $Type, $enableTLS);
}
// }}}
// {{{ __destruct
/**
* Cleanly close our connection upon destruction
*
* @access friendly
* @return void
**/
function __destruct () {
if ($this->isConnected ())
$this->close ();
}
// }}}
// {{{ __sleep
/**
* Close any open connection whenever someone tries to put ourself to sleep
*
* @access friendly
* @return void
**/
function __sleep () {
if ($this->isConnected ())
$this->close ();
return array ('Type');
}
// }}}
// {{{ __wakeup
/**
* Give a warning if someone unserializes us
*
* @access friendly
* @return void
**/
function __wakeup () {
trigger_error ('Sockets may not be unserialized, remember that this connection is lost now', E_USER_NOTICE);
}
// }}}
// {{{ bind
/**
* Try to bind our sockets to this source-address
*
* @param string $IP (optional)
* @param int $Port (optional)
*
* @access public
* @return bool
**/
public function bind ($IP = null, $Port = null) {
// Make sure the IP-Address is valid
if (($IP !== null) && !$this::isIPv4 ($IP) && !$this::isIPv6 ($IP)) {
trigger_error ('Not an IP-Address: ' . $IP);
return false;
}
// Make sure the Port is valid
if (($Port !== null) && (($Port < 1) || ($Port > 0xFFFF))) {
trigger_error ('Invalid port: ' . $Port);
return false;
}
// Remember the values
$this->socketBindAddress = $IP;
$this->socketBindPort = (int)$Port;
return true;
}
// }}}
// {{{ connect
/**
* Create a connection
*
* @param mixed $Hosts
* @param int $Port
* @param enum $Type (optional) TCP is used by default
* @param bool $enableTLS (optional) Enable TLS-Encryption on connect
* @param callable $Callback (optional) Fire this callback once this operation was finished
* @param mixed $Private (optional) Any private data to pass to the callback
*
* The callback will be fired in the form of
*
* function (qcEvents_Socket $Self, bool $Status, mixed $Private) { }
*
* $Status will be TRUE if the connection succeeded
*
* @remark This function is asyncronous! If it returns true this does not securly mean that a connection was established!
*
* @access public
* @return qcEvents_Promise
**/
public function connect ($Hosts, $Port = null, $Type = null, $enableTLS = false, callable $Callback = null, $Private = null) : qcEvents_Promise {
// Check wheter to use the default socket-type
if ($Type === null)
$Type = $this::DEFAULT_TYPE;
if ($this::FORCE_TYPE !== null)
$Type = $this::FORCE_TYPE;
// Validate the type-parameter
if (($Type != self::TYPE_TCP) && ($Type != self::TYPE_UDP))
return qcEvents_Promise::reject ('Unsupported socket-type');
// Check wheter to use a default port
if ($Port === null) {
$Port = $this::DEFAULT_PORT;
if ($Port === null)
return qcEvents_Promise::reject ('No port specified');
}
if ($this::FORCE_PORT !== null)
$Port = $this::FORCE_PORT;
// Make sure we have an event-base assigned
if (!$this->getEventBase ())
return qcEvents_Promise::reject ('No Event-Base assigned or could not assign Event-Base');
// Try to close any open connection before creating a new one
# TODO: Make disconnect async
if (!$this->isDisconnected () && !$this->close ())
return qcEvents_Promise::reject ('Disconnect before connect failed');
// Reset internal addresses
$this->socketAddresses = null;
$this->socketAddress = null;
$this->socketConnectResolve = null;
$this->socketConnectReject = null;
$this->tlsStatus = ($enableTLS ? true : null);
// Create a new promise
$Promise = new qcEvents_Promise (function ($resolve, $reject) use ($Hosts, $Port, $Type) {
// Remember promises
$this->socketConnectResolve = $resolve;
$this->socketConnectReject = $reject;
// Make sure hosts is an array
if (!is_array ($Hosts))
$Hosts = array ($Hosts);
$Resolve = array ();
foreach ($Hosts as $Host) {
// Check for IPv6
if (($IPv6 = $this::isIPv6 ($Host)) && ($Host [0] != '['))
$Host = '[' . $Host . ']';
// Check for IPv4/v6 or wheter to skip the resolver
if (!$this->internalResolver || $this::isIPv4 ($Host) || $IPv6)
$this->socketAddresses [] = array ($Host, $Host, $Port, $Type);
else
$Resolve [] = $Host;
}
// Put ourself into connected-state
$this->Connected = null;
// Check if we have addresses to connect to
if ($this->socketAddresses && (count ($this->socketAddresses) > 0))
$this->socketConnectMulti ();
// Sanity-Check if to use internal resolver
if (!$this->internalResolver || (count ($Resolve) == 0))
return;
// Perform asyncronous resolve
return $this->socketResolveDo ($Host, $Port, $Type);
});
// Patch promise with callback
if ($Callback) {
trigger_error ('Callback on qcEvents_Socket::connect() is deprecated');
$Promise = $Promise->then (
function () use ($Callback, $Private) {
// Run the callback
call_user_func ($Callback, $this, true, $Private);
// Forward all results
return new qcEvents_Promise_Solution (func_get_args ());
},
function () use ($Callback, $Private) {
// Run the callback
call_user_func ($Callback, $this, false, $Private);
// Forward the exception
throw new qcEvents_Promise_Solution (func_get_args ());
}
);
}
// Return the promise
return $Promise;
}
// }}}
// {{{ connectService
/**
* Create a connection to a named service on a given domain
* by using DNS-SRV
*
* @param string $Domain
* @param string $Service
* @param enum $Type (optional)
* @param bool $enableTLS (optional)
*
* @access public
* @return qcEvents_Promise
**/
public function connectService ($Domain, $Service, $Type = null, $enableTLS = false) : qcEvents_Promise {
// Check wheter to use the default socket-type
if ($Type === null)
$Type = $this::DEFAULT_TYPE;
if ($this::FORCE_TYPE !== null)
$Type = $this::FORCE_TYPE;
// Validate the type-parameter
if (($Type != self::TYPE_TCP) && ($Type != self::TYPE_UDP))
return qcEvents_Promise::reject ('Unsupported socket-type');
// Make sure we have an event-base assigned
if (!$this->getEventBase ())
return qcEvents_Promise::reject ('Failed to get event-base');
// Try to close any open connection before creating a new one
if (!$this->isDisconnected () && !$this->close ())
return qcEvents_Promise::reject ('Failed to disconnect socket before connect');
// Reset internal addresses
$this->socketAddresses = null;
$this->socketAddress = null;
$this->socketConnectResolve = null;
$this->socketConnectReject = null;
$this->tlsStatus = ($enableTLS ? true : null);
$this->Connected = null;
$this->lastEvent = time ();
// Generate label to look up
$Label = '_' . $Service . '._' . ($Type == self::TYPE_UDP ? 'udp' : 'tcp') . '.' . $Domain;
return new qcEvents_Promise (function ($resolve, $reject) use ($Label, $Type, $Domain) {
// Remember promises
$this->socketConnectResolve = $resolve;
$this->socketConnectReject = $reject;
// Perform syncronous lookup
if ($this->internalResolver === false) {
// Fire a callback
$this->___callback ('socketResolve', array ($Label), array (qcEvents_Stream_DNS_Message::TYPE_SRV));
// Do the DNS-Lookup
if (!is_array ($Result = dns_get_record ($Label, DNS_SRV, $AuthNS, $Addtl)) || (count ($Result) == 0))
return $this->socketConnectTimeout ();
// Forward the result
return $this->socketResolverResultArray ($Result, $Addtl, $Domain, DNS_SRV, null, $Type);
}
// Perform asyncronous lookup
require_once ('qcEvents/Client/DNS.php');
return $this->socketResolveDo ($Label, null, $Type, qcEvents_Stream_DNS_Message::TYPE_SRV);
});
}
// }}}
// {{{ socketConnectMulti
/**
* Try to connect to next host on our list
*
* @access private
* @return void
**/
private function socketConnectMulti () {
// Check if there are addresses on the queue
if (!is_array ($this->socketAddresses) || (count ($this->socketAddresses) == 0) || ($this->socketAddress !== null))
return false;
// Get the next address
$this->socketAddress = array_shift ($this->socketAddresses);
// Fire a callback for this
$this->___callback ('socketTryConnect', $this->socketAddress [0], $this->socketAddress [1], $this->socketAddress [2], $this->socketAddress [3]);
// Check unreachable-cache
if (isset (self::$Unreachables [$Key = $this->socketAddress [1] . ':' . $this->socketAddress [2] . ':' . $this->socketAddress [3]])) {
if (time () - self::$Unreachables [$Key] < $this::UNREACHABLE_TIMEOUT)
return $this->socketHandleConnectFailed (self::ERROR_NET_UNREACHABLE);
unset (self::$Unreachables [$Key]);
}
// Create new client-socket
$URI = ($this->socketAddress [3] === self::TYPE_TCP ? 'tcp' : 'udp') . '://' . $this->socketAddress [1] . ':' . $this->socketAddress [2];
if (($this->socketBindAddress !== null) || ($this->socketBindPort !== null)) {
$isIPv6 = $this::isIPv6 ($this->socketBindAddress);
$ctx = stream_context_create (array ('socket' => array (
'bindto' => ($isIPv6 ? '[' : '') . $this->socketBindAddress . ($isIPv6 ? ']' : '') . ':' . (int)$this->socketBindPort,
)));
} else
$ctx = stream_context_create ();
if (!is_resource ($Socket = @stream_socket_client ($URI, $errno, $err, $this::CONNECT_TIMEOUT, STREAM_CLIENT_ASYNC_CONNECT, $ctx)))
return $this->socketHandleConnectFailed (-$errno);
stream_set_blocking ($Socket, 0);
// Set our new status
if (!$this->setStreamFD ($Socket))
return false;
// Make sure we are watching events
$this->watchWrite (true);
$this->isWatching (true);
// Setup our internal buffer-size
$this->bufferSize = ($this->socketAddress [3] === self::TYPE_UDP ? self::READ_UDP_BUFFER : self::READ_TCP_BUFFER);
$this->lastEvent = time ();
// Set our connection-state
if ($this->socketAddress [3] !== (self::TYPE_UDP ? true : null)) {
$this->addTimer (self::CONNECT_TIMEOUT, false, array ($this, 'socketConnectTimeout'));
$this->addHook ('eventWritable', array ($this, 'socketHandleConnected'), null, true);
} else
$this->socketHandleConnected ();
return true;
}
// }}}
// {{{ connectServer
/**
* Use this connection as Server-Slave
*
* @param qcEvents_Socket_Server $Server
* @param string $Remote
* @param resource $Connection (optional)
* @param bool $enableTLS (optional)
*
* @remark This is for internal use only!
*
* @access public
* @return void
**/
public final function connectServer (qcEvents_Socket_Server $Server, $Remote, $Connection = null, $enableTLS = false) {
// Set our internal buffer-size
if ($Connection === null) {
$this->bufferSize = self::READ_UDP_BUFFER;
// Store short-hand for UDP-Writes
$this->remoteName = $Remote;
} else {
$this->bufferSize = self::READ_TCP_BUFFER;
// Switch connection into non-blocking mode
stream_set_blocking ($Connection, 0);
// Store the connection
$this->setStreamFD ($Connection);
$this->tlsStatus = !!$enableTLS;
}
// Store our parent server-handle
$this->serverParent = $Server;
// Fake remote socket-settings
$p = strrpos ($Remote, ':');
$this->socketAddress = array (
substr ($Remote, 0, $p),
substr ($Remote, 0, $p),
intval (substr ($Remote, $p + 1)),
($Connection === null ? self::TYPE_UDP_SERVER : self::TYPE_TCP)
);
// Put ourself into connected state
$this->socketHandleConnected ();
}
// }}}
// {{ socketHandleConnected
/**
* Internal Callback: Our socket is now in connected state
*
* @access public
* @return void
**/
public function socketHandleConnected () {
// Unwatch writes - as we are buffered all the time, this should be okay
$this->watchWrite (false);
if ($this->Connected !== true) {
// Set connection-status
$this->Connected = true;
// Set runtime-information
if ($fd = $this->getReadFD ())
$Name = stream_socket_get_name ($fd, false);
elseif ($this->serverParent)
$Name = $this->serverParent->getLocalName ();
$this->Type = $this->socketAddress [3];
$this->localAddr = substr ($Name, 0, strrpos ($Name, ':'));
$this->localPort = (int)substr ($Name, strrpos ($Name, ':') + 1);
$this->remoteHost = $this->socketAddress [0];
$this->remoteAddr = $this->socketAddress [1];
$this->remotePort = $this->socketAddress [2];
// Free some space now
$this->socketAddress = null;
$this->socketAddresses = null;
// Destroy our resolver
if (is_object ($this->internalResolver))
$this->internalResolver = true;
// Check wheter to enable TLS
if (($this->tlsStatus === true) && !$this->tlsEnable ())
return $this->tlsEnable (true, array ($this, 'socketHandleConnected'));
}
// Check our TLS-Status and treat as connection failed if required
if (($this->tlsStatus === true) && !$this->tlsEnable ())
return $this->socketHandleConnectFailed ($this::ERROR_NET_TLS_FAILED);
// Fire custom callback
if ($this->socketConnectResolve) {
call_user_func ($this->socketConnectResolve);
$this->socketConnectResolve = null;
$this->socketConnectReject = null;
}
// Fire the callback
$this->___callback ('socketConnected');
}
// }}}
// {{{ socketHandleConnectFailed
/**
* Internal Callback: Pending connection could not be established
*
* @param enum $Error (optional)
*
* @access private
* @return void
**/
private function socketHandleConnectFailed ($Error = self::ERROR_NET_UNKNOWN) {
// Mark this host as failed
if ($this->socketAddress !== null) {
// Reset the address
$Address = $this->socketAddress;
$this->socketAddress = null;
// Mark destination as unreachable
$Key = $Address [1] . ':' . $Address [2] . ':' . $Address [3];
if (!isset (self::$Unreachables [$Key]))
self::$Unreachables [$Key] = time ();
// Check wheter to retry using IPv6
if (($this::$nat64Prefix !== null) &&
(($IPv4 = $this::isIPv4 ($Address [1])) || (strtolower (substr ($Address [1], 0, 8)) == '[::ffff:'))) {
if ($IPv4) {
$IP = explode ('.', $Address [1]);
$IP = sprintf ('[%s%02x%02x:%02x%02x]', $this::$nat64Prefix, (int)$IP [0], (int)$IP [1], (int)$IP [2], (int)$IP [3]);
} else
$IP = '[' . $this::$nat64Prefix . substr ($Address [1], 8);
$this->socketAddresses [] = array (
$Address [0],
$IP,
$Address [2],
$Address [3]
);
}
// Raise callback
$this->___callback ('socketTryConnectFailed', $Address [0], $Address [1], $Address [2], $Address [3], $Error);
}
// Check if there are more hosts on our list
if ((!is_array ($this->socketAddresses) || (count ($this->socketAddresses) == 0)) &&
(!is_object ($this->internalResolver) || !$this->internalResolver->isActive ())) {
// Fire custom callback
if ($this->socketConnectReject) {
call_user_func ($this->socketConnectReject);
$this->socketConnectResolve = null;
$this->socketConnectReject = null;
}
// Fire the callback
$this->___callback ('socketConnectionFailed', $Error);
// Disconnect cleanly
return $this->close ();
}
// Try the next host
return $this->socketConnectMulti ();
}
// }}}
// {{{ socketResolveDo
/**
* Resolve a given hostname
*
* @param string $Hostname
* @param int $Port
* @param enum $Type
* @param array $Types (optional)
*
* @access private
* @return void
**/
private function socketResolveDo ($Hostname, $Port, $Type, $Types = null) {
// Don't do further resolves if we are already connected
if ($this->isConnected ())
return false;
// Create a new resolver
if (!is_object ($this->internalResolver)) {
require_once ('qcEvents/Client/DNS.php');
$this->internalResolver = new qcEvents_Client_DNS ($this->getEventBase ());
}
// Check which types to resolve
if ($Types === null)
$Types = array (
qcEvents_Stream_DNS_Message::TYPE_AAAA,
qcEvents_Stream_DNS_Message::TYPE_A,
# qcEvents_Stream_DNS_Message::TYPE_CNAME,
);
elseif (!is_array ($Types))
$Types = array ($Types);
// Enqueue Hostnames
foreach ($Types as $rType)
$this->internalResolver->resolve ($Hostname, $rType)->then (
function (qcEvents_Stream_DNS_Recordset $Answers, qcEvents_Stream_DNS_Recordset $Authorities, qcEvents_Stream_DNS_Recordset $Additional, qcEvents_Stream_DNS_Message $Response)
use ($Hostname, $Port, $Type, $rType) {
// Discard any result if we are connected already
if ($this->isConnected ())
return;
// Update our last event (to prevent a pending disconnect)
$this->lastEvent = time ();
// Convert the result
$Result = $this->internalResolver->dnsConvertPHP ($Response, $AuthNS, $Addtl);
// Forward
return $this->socketResolverResultArray ($Result, $Addtl, $Hostname, $rType, $Port, $Type);
},
function () use ($Hostname, $Port, $Type, $rType) {
return $this->socketResolverResultArray (array (), array (), $Hostname, $rType, $Port, $Type);
}
);
// Update last action
$this->lastEvent = time ();
// Fire a callback
$this->___callback ('socketResolve', array ($Hostname), $Types);
// Setup a timeout
$this->addTimer (self::CONNECT_TIMEOUT, false, array ($this, 'socketConnectTimeout'));
}
// }}}
// {{{ socketResolverResultArray
/**
* Handle the result of from any resolve-process
*
* @param array $Results Results returned from the resolver
* @param array $Addtl Additional results returned from the resolver
* @param string $Hostname The Hostname we are looking for
* @param enum $rType DNS-Record-Type we are looking for
* @param int $Port The port we want to connect to
* @param enum $Type The type of socket we wish to create
*
* @access private
* @return void
**/
private function socketResolverResultArray ($Results, $Addtl, $Hostname, $rType, $Port, $Type) {
// Check if there are no results
if ((count ($Results) == 0) && (!is_object ($this->internalResolver) || !$this->internalResolver->isActive ())) {
// Mark connection as failed if there are no addresses pending and no current address
if ((!is_array ($this->socketAddresses) || (count ($this->socketAddresses) == 0)) && ($this->socketAddress === null))
return $this->socketHandleConnectFailed ($this::ERROR_NET_DNS_FAILED);
return;
}
// Handle all results
$Addrs = array ();
$Resolve = array ();
while (count ($Results) > 0) {
$Record = array_shift ($Results);
// Check for a normal IP-Address
if (($Record ['type'] == 'A') || ($Record ['type'] == 'AAAA')) {
if (!is_array ($this->socketAddresses))
$this->socketAddresses = array ();
$Addrs [] = $Addr = ($Record ['type'] == 'AAAA' ? '[' . $Record ['ipv6'] . ']' : $Record ['ip']);
$this->socketAddresses [] = array ($Hostname, $Addr, (isset ($Record ['port']) ? $Record ['port'] : $Port), $Type);
// Handle canonical names
} elseif ($Record ['type'] == 'CNAME') {
// Check additionals
$Found = false;
foreach ($Results as $Record2)
if ($Found = ($Record2 ['host'] == $Record ['target']))
break;
foreach ($Addtl as $Record2)
if ($Record2 ['host'] == $Record ['target']) {
$Results [] = $Record2;
$Found = true;
}
// Check wheter to enqueue this name as well
if ($Found)
continue;
$Resolve [] = $Record ['target'];
$this->socketResolveDo ($Record ['target'], $Port, $Type, array ($rType));
// Handle SRV-Records
} elseif ($Record ['type'] == 'SRV') {
// Check additionals
$Found = false;
foreach ($Addtl as $Record2)
if ($Record2 ['host'] == $Record ['target']) {
$Record2 ['port'] = $Record ['port'];
$Results [] = $Record2;
$Found = true;
}
// Resolve deeper
if (!$Found) {
$Resolve [] = $Record ['target'];
$this->socketResolveDo ($Record ['target'], $Record ['port'], $Type);
}
}
}
// Fire up new callback
$this->___callback ('socketResolved', $Hostname, $Addrs, array_keys ($Resolve));
// Check wheter to try to connect
if (is_array ($this->socketAddresses) && (count ($this->socketAddresses) > 0))
$this->socketConnectMulti ();
}
// }}}
// {{{ socketConnectTimeout
/**
* Timeout a pending connection
*