/
endpoints.py
2335 lines (1887 loc) · 76.4 KB
/
endpoints.py
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
# -*- test-case-name: twisted.internet.test.test_endpoints -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Implementations of L{IStreamServerEndpoint} and L{IStreamClientEndpoint} that
wrap the L{IReactorTCP}, L{IReactorSSL}, and L{IReactorUNIX} interfaces.
This also implements an extensible mini-language for describing endpoints,
parsed by the L{clientFromString} and L{serverFromString} functions.
@since: 10.1
"""
import os
import re
import socket
import warnings
from typing import Optional
from unicodedata import normalize
from zope.interface import directlyProvides, implementer, provider
from constantly import NamedConstant, Names # type: ignore[import]
from incremental import Version
from twisted.internet import defer, error, fdesc, interfaces, threads
from twisted.internet.abstract import isIPAddress, isIPv6Address
from twisted.internet.address import (
HostnameAddress,
IPv4Address,
IPv6Address,
_ProcessAddress,
)
from twisted.internet.interfaces import (
IHostnameResolver,
IReactorPluggableNameResolver,
IReactorSocket,
IResolutionReceiver,
IStreamClientEndpointStringParserWithReactor,
IStreamServerEndpointStringParser,
)
from twisted.internet.protocol import ClientFactory, Factory, ProcessProtocol, Protocol
try:
from twisted.internet.stdio import PipeAddress, StandardIO
except ImportError:
# fallback if pywin32 is not installed
StandardIO = None # type: ignore[assignment,misc]
PipeAddress = None # type: ignore[assignment,misc]
from twisted.internet._resolver import HostResolution
from twisted.internet.defer import Deferred
from twisted.internet.task import LoopingCall
from twisted.logger import Logger
from twisted.plugin import IPlugin, getPlugins
from twisted.python import deprecate, log
from twisted.python.compat import _matchingString, iterbytes, nativeString
from twisted.python.components import proxyForInterface
from twisted.python.failure import Failure
from twisted.python.filepath import FilePath
from twisted.python.systemd import ListenFDs
from ._idna import _idnaBytes, _idnaText
try:
from OpenSSL.SSL import Error as SSLError
from twisted.internet.ssl import (
Certificate,
CertificateOptions,
KeyPair,
PrivateCertificate,
optionsForClientTLS,
trustRootFromCertificates,
)
from twisted.protocols.tls import TLSMemoryBIOFactory as _TLSMemoryBIOFactory
except ImportError:
TLSMemoryBIOFactory = None
else:
TLSMemoryBIOFactory = _TLSMemoryBIOFactory
__all__ = [
"clientFromString",
"serverFromString",
"TCP4ServerEndpoint",
"TCP6ServerEndpoint",
"TCP4ClientEndpoint",
"TCP6ClientEndpoint",
"UNIXServerEndpoint",
"UNIXClientEndpoint",
"SSL4ServerEndpoint",
"SSL4ClientEndpoint",
"AdoptedStreamServerEndpoint",
"StandardIOEndpoint",
"ProcessEndpoint",
"HostnameEndpoint",
"StandardErrorBehavior",
"connectProtocol",
"wrapClientTLS",
]
class _WrappingProtocol(Protocol):
"""
Wrap another protocol in order to notify my user when a connection has
been made.
"""
def __init__(self, connectedDeferred, wrappedProtocol):
"""
@param connectedDeferred: The L{Deferred} that will callback
with the C{wrappedProtocol} when it is connected.
@param wrappedProtocol: An L{IProtocol} provider that will be
connected.
"""
self._connectedDeferred = connectedDeferred
self._wrappedProtocol = wrappedProtocol
for iface in [
interfaces.IHalfCloseableProtocol,
interfaces.IFileDescriptorReceiver,
interfaces.IHandshakeListener,
]:
if iface.providedBy(self._wrappedProtocol):
directlyProvides(self, iface)
def logPrefix(self):
"""
Transparently pass through the wrapped protocol's log prefix.
"""
if interfaces.ILoggingContext.providedBy(self._wrappedProtocol):
return self._wrappedProtocol.logPrefix()
return self._wrappedProtocol.__class__.__name__
def connectionMade(self):
"""
Connect the C{self._wrappedProtocol} to our C{self.transport} and
callback C{self._connectedDeferred} with the C{self._wrappedProtocol}
"""
self._wrappedProtocol.makeConnection(self.transport)
self._connectedDeferred.callback(self._wrappedProtocol)
def dataReceived(self, data):
"""
Proxy C{dataReceived} calls to our C{self._wrappedProtocol}
"""
return self._wrappedProtocol.dataReceived(data)
def fileDescriptorReceived(self, descriptor):
"""
Proxy C{fileDescriptorReceived} calls to our C{self._wrappedProtocol}
"""
return self._wrappedProtocol.fileDescriptorReceived(descriptor)
def connectionLost(self, reason):
"""
Proxy C{connectionLost} calls to our C{self._wrappedProtocol}
"""
return self._wrappedProtocol.connectionLost(reason)
def readConnectionLost(self):
"""
Proxy L{IHalfCloseableProtocol.readConnectionLost} to our
C{self._wrappedProtocol}
"""
self._wrappedProtocol.readConnectionLost()
def writeConnectionLost(self):
"""
Proxy L{IHalfCloseableProtocol.writeConnectionLost} to our
C{self._wrappedProtocol}
"""
self._wrappedProtocol.writeConnectionLost()
def handshakeCompleted(self):
"""
Proxy L{interfaces.IHandshakeListener} to our
C{self._wrappedProtocol}.
"""
self._wrappedProtocol.handshakeCompleted()
class _WrappingFactory(ClientFactory):
"""
Wrap a factory in order to wrap the protocols it builds.
@ivar _wrappedFactory: A provider of I{IProtocolFactory} whose buildProtocol
method will be called and whose resulting protocol will be wrapped.
@ivar _onConnection: A L{Deferred} that fires when the protocol is
connected
@ivar _connector: A L{connector <twisted.internet.interfaces.IConnector>}
that is managing the current or previous connection attempt.
"""
# Type is wrong. See https://twistedmatrix.com/trac/ticket/10005#ticket
protocol = _WrappingProtocol # type: ignore[assignment]
def __init__(self, wrappedFactory):
"""
@param wrappedFactory: A provider of I{IProtocolFactory} whose
buildProtocol method will be called and whose resulting protocol
will be wrapped.
"""
self._wrappedFactory = wrappedFactory
self._onConnection = defer.Deferred(canceller=self._canceller)
def startedConnecting(self, connector):
"""
A connection attempt was started. Remember the connector which started
said attempt, for use later.
"""
self._connector = connector
def _canceller(self, deferred):
"""
The outgoing connection attempt was cancelled. Fail that L{Deferred}
with an L{error.ConnectingCancelledError}.
@param deferred: The L{Deferred <defer.Deferred>} that was cancelled;
should be the same as C{self._onConnection}.
@type deferred: L{Deferred <defer.Deferred>}
@note: This relies on startedConnecting having been called, so it may
seem as though there's a race condition where C{_connector} may not
have been set. However, using public APIs, this condition is
impossible to catch, because a connection API
(C{connectTCP}/C{SSL}/C{UNIX}) is always invoked before a
L{_WrappingFactory}'s L{Deferred <defer.Deferred>} is returned to
C{connect()}'s caller.
@return: L{None}
"""
deferred.errback(
error.ConnectingCancelledError(self._connector.getDestination())
)
self._connector.stopConnecting()
def doStart(self):
"""
Start notifications are passed straight through to the wrapped factory.
"""
self._wrappedFactory.doStart()
def doStop(self):
"""
Stop notifications are passed straight through to the wrapped factory.
"""
self._wrappedFactory.doStop()
def buildProtocol(self, addr):
"""
Proxy C{buildProtocol} to our C{self._wrappedFactory} or errback the
C{self._onConnection} L{Deferred} if the wrapped factory raises an
exception or returns L{None}.
@return: An instance of L{_WrappingProtocol} or L{None}
"""
try:
proto = self._wrappedFactory.buildProtocol(addr)
if proto is None:
raise error.NoProtocol()
except BaseException:
self._onConnection.errback()
else:
return self.protocol(self._onConnection, proto)
def clientConnectionFailed(self, connector, reason):
"""
Errback the C{self._onConnection} L{Deferred} when the
client connection fails.
"""
if not self._onConnection.called:
self._onConnection.errback(reason)
@implementer(interfaces.IStreamServerEndpoint)
class StandardIOEndpoint:
"""
A Standard Input/Output endpoint
@ivar _stdio: a callable, like L{stdio.StandardIO}, which takes an
L{IProtocol} provider and a C{reactor} keyword argument (interface
dependent upon your platform).
"""
_stdio = StandardIO
def __init__(self, reactor):
"""
@param reactor: The reactor for the endpoint.
"""
self._reactor = reactor
def listen(self, stdioProtocolFactory):
"""
Implement L{IStreamServerEndpoint.listen} to listen on stdin/stdout
"""
return defer.execute(
self._stdio,
stdioProtocolFactory.buildProtocol(PipeAddress()),
reactor=self._reactor,
)
class _IProcessTransportWithConsumerAndProducer(
interfaces.IProcessTransport, interfaces.IConsumer, interfaces.IPushProducer
):
"""
An L{_IProcessTransportWithConsumerAndProducer} combines various interfaces
to work around the issue that L{interfaces.IProcessTransport} is
incompletely defined and doesn't specify flow-control interfaces, and that
L{proxyForInterface} doesn't allow for multiple interfaces.
"""
class _ProcessEndpointTransport(
proxyForInterface( # type: ignore[misc]
_IProcessTransportWithConsumerAndProducer,
"_process",
)
):
"""
An L{ITransport}, L{IProcessTransport}, L{IConsumer}, and L{IPushProducer}
provider for the L{IProtocol} instance passed to the process endpoint.
@ivar _process: An active process transport which will be used by write
methods on this object to write data to a child process.
@type _process: L{interfaces.IProcessTransport} provider
"""
class _WrapIProtocol(ProcessProtocol):
"""
An L{IProcessProtocol} provider that wraps an L{IProtocol}.
@ivar transport: A L{_ProcessEndpointTransport} provider that is hooked to
the wrapped L{IProtocol} provider.
@see: L{protocol.ProcessProtocol}
"""
def __init__(self, proto, executable, errFlag):
"""
@param proto: An L{IProtocol} provider.
@param errFlag: A constant belonging to L{StandardErrorBehavior}
that determines if stderr is logged or dropped.
@param executable: The file name (full path) to spawn.
"""
self.protocol = proto
self.errFlag = errFlag
self.executable = executable
def makeConnection(self, process):
"""
Call L{IProtocol} provider's makeConnection method with an
L{ITransport} provider.
@param process: An L{IProcessTransport} provider.
"""
self.transport = _ProcessEndpointTransport(process)
return self.protocol.makeConnection(self.transport)
def childDataReceived(self, childFD, data):
"""
This is called with data from the process's stdout or stderr pipes. It
checks the status of the errFlag to setermine if stderr should be
logged (default) or dropped.
"""
if childFD == 1:
return self.protocol.dataReceived(data)
elif childFD == 2 and self.errFlag == StandardErrorBehavior.LOG:
log.msg(
format="Process %(executable)r wrote stderr unhandled by "
"%(protocol)s: %(data)s",
executable=self.executable,
protocol=self.protocol,
data=data,
)
def processEnded(self, reason):
"""
If the process ends with L{error.ProcessDone}, this method calls the
L{IProtocol} provider's L{connectionLost} with a
L{error.ConnectionDone}
@see: L{ProcessProtocol.processEnded}
"""
if (reason.check(error.ProcessDone) == error.ProcessDone) and (
reason.value.status == 0
):
return self.protocol.connectionLost(Failure(error.ConnectionDone()))
else:
return self.protocol.connectionLost(reason)
class StandardErrorBehavior(Names):
"""
Constants used in ProcessEndpoint to decide what to do with stderr.
@cvar LOG: Indicates that stderr is to be logged.
@cvar DROP: Indicates that stderr is to be dropped (and not logged).
@since: 13.1
"""
LOG = NamedConstant()
DROP = NamedConstant()
@implementer(interfaces.IStreamClientEndpoint)
class ProcessEndpoint:
"""
An endpoint for child processes
@ivar _spawnProcess: A hook used for testing the spawning of child process.
@since: 13.1
"""
def __init__(
self,
reactor,
executable,
args=(),
env={},
path=None,
uid=None,
gid=None,
usePTY=0,
childFDs=None,
errFlag=StandardErrorBehavior.LOG,
):
"""
See L{IReactorProcess.spawnProcess}.
@param errFlag: Determines if stderr should be logged.
@type errFlag: L{endpoints.StandardErrorBehavior}
"""
self._reactor = reactor
self._executable = executable
self._args = args
self._env = env
self._path = path
self._uid = uid
self._gid = gid
self._usePTY = usePTY
self._childFDs = childFDs
self._errFlag = errFlag
self._spawnProcess = self._reactor.spawnProcess
def connect(self, protocolFactory):
"""
Implement L{IStreamClientEndpoint.connect} to launch a child process
and connect it to a protocol created by C{protocolFactory}.
@param protocolFactory: A factory for an L{IProtocol} provider which
will be notified of all events related to the created process.
"""
proto = protocolFactory.buildProtocol(_ProcessAddress())
try:
self._spawnProcess(
_WrapIProtocol(proto, self._executable, self._errFlag),
self._executable,
self._args,
self._env,
self._path,
self._uid,
self._gid,
self._usePTY,
self._childFDs,
)
except BaseException:
return defer.fail()
else:
return defer.succeed(proto)
@implementer(interfaces.IStreamServerEndpoint)
class _TCPServerEndpoint:
"""
A TCP server endpoint interface
"""
def __init__(self, reactor, port, backlog, interface):
"""
@param reactor: An L{IReactorTCP} provider.
@param port: The port number used for listening
@type port: int
@param backlog: Size of the listen queue
@type backlog: int
@param interface: The hostname to bind to
@type interface: str
"""
self._reactor = reactor
self._port = port
self._backlog = backlog
self._interface = interface
def listen(self, protocolFactory):
"""
Implement L{IStreamServerEndpoint.listen} to listen on a TCP
socket
"""
return defer.execute(
self._reactor.listenTCP,
self._port,
protocolFactory,
backlog=self._backlog,
interface=self._interface,
)
class TCP4ServerEndpoint(_TCPServerEndpoint):
"""
Implements TCP server endpoint with an IPv4 configuration
"""
def __init__(self, reactor, port, backlog=50, interface=""):
"""
@param reactor: An L{IReactorTCP} provider.
@param port: The port number used for listening
@type port: int
@param backlog: Size of the listen queue
@type backlog: int
@param interface: The hostname to bind to, defaults to '' (all)
@type interface: str
"""
_TCPServerEndpoint.__init__(self, reactor, port, backlog, interface)
class TCP6ServerEndpoint(_TCPServerEndpoint):
"""
Implements TCP server endpoint with an IPv6 configuration
"""
def __init__(self, reactor, port, backlog=50, interface="::"):
"""
@param reactor: An L{IReactorTCP} provider.
@param port: The port number used for listening
@type port: int
@param backlog: Size of the listen queue
@type backlog: int
@param interface: The hostname to bind to, defaults to C{::} (all)
@type interface: str
"""
_TCPServerEndpoint.__init__(self, reactor, port, backlog, interface)
@implementer(interfaces.IStreamClientEndpoint)
class TCP4ClientEndpoint:
"""
TCP client endpoint with an IPv4 configuration.
"""
def __init__(self, reactor, host, port, timeout=30, bindAddress=None):
"""
@param reactor: An L{IReactorTCP} provider
@param host: A hostname, used when connecting
@type host: str
@param port: The port number, used when connecting
@type port: int
@param timeout: The number of seconds to wait before assuming the
connection has failed.
@type timeout: L{float} or L{int}
@param bindAddress: A (host, port) tuple of local address to bind to,
or None.
@type bindAddress: tuple
"""
self._reactor = reactor
self._host = host
self._port = port
self._timeout = timeout
self._bindAddress = bindAddress
def connect(self, protocolFactory):
"""
Implement L{IStreamClientEndpoint.connect} to connect via TCP.
"""
try:
wf = _WrappingFactory(protocolFactory)
self._reactor.connectTCP(
self._host,
self._port,
wf,
timeout=self._timeout,
bindAddress=self._bindAddress,
)
return wf._onConnection
except BaseException:
return defer.fail()
@implementer(interfaces.IStreamClientEndpoint)
class TCP6ClientEndpoint:
"""
TCP client endpoint with an IPv6 configuration.
@ivar _getaddrinfo: A hook used for testing name resolution.
@ivar _deferToThread: A hook used for testing deferToThread.
@ivar _GAI_ADDRESS: Index of the address portion in result of
getaddrinfo to be used.
@ivar _GAI_ADDRESS_HOST: Index of the actual host-address in the
5-tuple L{_GAI_ADDRESS}.
"""
_getaddrinfo = staticmethod(socket.getaddrinfo)
_deferToThread = staticmethod(threads.deferToThread)
_GAI_ADDRESS = 4
_GAI_ADDRESS_HOST = 0
def __init__(self, reactor, host, port, timeout=30, bindAddress=None):
"""
@param host: An IPv6 address literal or a hostname with an
IPv6 address
@see: L{twisted.internet.interfaces.IReactorTCP.connectTCP}
"""
self._reactor = reactor
self._host = host
self._port = port
self._timeout = timeout
self._bindAddress = bindAddress
def connect(self, protocolFactory):
"""
Implement L{IStreamClientEndpoint.connect} to connect via TCP,
once the hostname resolution is done.
"""
if isIPv6Address(self._host):
d = self._resolvedHostConnect(self._host, protocolFactory)
else:
d = self._nameResolution(self._host)
d.addCallback(
lambda result: result[0][self._GAI_ADDRESS][self._GAI_ADDRESS_HOST]
)
d.addCallback(self._resolvedHostConnect, protocolFactory)
return d
def _nameResolution(self, host):
"""
Resolve the hostname string into a tuple containing the host
IPv6 address.
"""
return self._deferToThread(self._getaddrinfo, host, 0, socket.AF_INET6)
def _resolvedHostConnect(self, resolvedHost, protocolFactory):
"""
Connect to the server using the resolved hostname.
"""
try:
wf = _WrappingFactory(protocolFactory)
self._reactor.connectTCP(
resolvedHost,
self._port,
wf,
timeout=self._timeout,
bindAddress=self._bindAddress,
)
return wf._onConnection
except BaseException:
return defer.fail()
@implementer(IHostnameResolver)
class _SimpleHostnameResolver:
"""
An L{IHostnameResolver} provider that invokes a provided callable
to resolve hostnames.
@ivar _nameResolution: the callable L{resolveHostName} invokes to
resolve hostnames.
@type _nameResolution: A L{callable} that accepts two arguments:
the host to resolve and the port number to include in the
result.
"""
_log = Logger()
def __init__(self, nameResolution):
"""
Create a L{_SimpleHostnameResolver} instance.
"""
self._nameResolution = nameResolution
def resolveHostName(
self,
resolutionReceiver,
hostName,
portNumber=0,
addressTypes=None,
transportSemantics="TCP",
):
"""
Initiate a hostname resolution.
@param resolutionReceiver: an object that will receive each resolved
address as it arrives.
@type resolutionReceiver: L{IResolutionReceiver}
@param hostName: see interface
@param portNumber: see interface
@param addressTypes: Ignored in this implementation.
@param transportSemantics: Ignored in this implementation.
@return: The resolution in progress.
@rtype: L{IResolutionReceiver}
"""
resolutionReceiver.resolutionBegan(HostResolution(hostName))
d = self._nameResolution(hostName, portNumber)
def cbDeliver(gairesult):
for family, socktype, proto, canonname, sockaddr in gairesult:
if family == socket.AF_INET6:
resolutionReceiver.addressResolved(IPv6Address("TCP", *sockaddr))
elif family == socket.AF_INET:
resolutionReceiver.addressResolved(IPv4Address("TCP", *sockaddr))
def ebLog(error):
self._log.failure(
"while looking up {name} with {callable}",
error,
name=hostName,
callable=self._nameResolution,
)
d.addCallback(cbDeliver)
d.addErrback(ebLog)
d.addBoth(lambda ignored: resolutionReceiver.resolutionComplete())
return resolutionReceiver
@implementer(interfaces.IStreamClientEndpoint)
class HostnameEndpoint:
"""
A name-based endpoint that connects to the fastest amongst the resolved
host addresses.
@cvar _DEFAULT_ATTEMPT_DELAY: The default time to use between attempts, in
seconds, when no C{attemptDelay} is given to
L{HostnameEndpoint.__init__}.
@ivar _hostText: the textual representation of the hostname passed to the
constructor. Used to pass to the reactor's hostname resolver.
@type _hostText: L{unicode}
@ivar _hostBytes: the encoded bytes-representation of the hostname passed
to the constructor. Used to construct the L{HostnameAddress}
associated with this endpoint.
@type _hostBytes: L{bytes}
@ivar _hostStr: the native-string representation of the hostname passed to
the constructor, used for exception construction
@type _hostStr: native L{str}
@ivar _badHostname: a flag - hopefully false! - indicating that an invalid
hostname was passed to the constructor. This might be a textual
hostname that isn't valid IDNA, or non-ASCII bytes.
@type _badHostname: L{bool}
"""
_getaddrinfo = staticmethod(socket.getaddrinfo)
_deferToThread = staticmethod(threads.deferToThread)
_DEFAULT_ATTEMPT_DELAY = 0.3
def __init__(
self, reactor, host, port, timeout=30, bindAddress=None, attemptDelay=None
):
"""
Create a L{HostnameEndpoint}.
@param reactor: The reactor to use for connections and delayed calls.
@type reactor: provider of L{IReactorTCP}, L{IReactorTime} and either
L{IReactorPluggableNameResolver} or L{IReactorPluggableResolver}.
@param host: A hostname to connect to.
@type host: L{bytes} or L{unicode}
@param port: The port number to connect to.
@type port: L{int}
@param timeout: For each individual connection attempt, the number of
seconds to wait before assuming the connection has failed.
@type timeout: L{float} or L{int}
@param bindAddress: the local address of the network interface to make
the connections from.
@type bindAddress: L{bytes}
@param attemptDelay: The number of seconds to delay between connection
attempts.
@type attemptDelay: L{float}
@see: L{twisted.internet.interfaces.IReactorTCP.connectTCP}
"""
self._reactor = reactor
self._nameResolver = self._getNameResolverAndMaybeWarn(reactor)
[self._badHostname, self._hostBytes, self._hostText] = self._hostAsBytesAndText(
host
)
self._hostStr = self._hostBytes if bytes is str else self._hostText
self._port = port
self._timeout = timeout
self._bindAddress = bindAddress
if attemptDelay is None:
attemptDelay = self._DEFAULT_ATTEMPT_DELAY
self._attemptDelay = attemptDelay
def __repr__(self) -> str:
"""
Produce a string representation of the L{HostnameEndpoint}.
@return: A L{str}
"""
if self._badHostname:
# Use the backslash-encoded version of the string passed to the
# constructor, which is already a native string.
host = self._hostStr
elif isIPv6Address(self._hostStr):
host = f"[{self._hostStr}]"
else:
# Convert the bytes representation to a native string to ensure
# that we display the punycoded version of the hostname, which is
# more useful than any IDN version as it can be easily copy-pasted
# into debugging tools.
host = nativeString(self._hostBytes)
return "".join(["<HostnameEndpoint ", host, ":", str(self._port), ">"])
def _getNameResolverAndMaybeWarn(self, reactor):
"""
Retrieve a C{nameResolver} callable and warn the caller's
caller that using a reactor which doesn't provide
L{IReactorPluggableNameResolver} is deprecated.
@param reactor: The reactor to check.
@return: A L{IHostnameResolver} provider.
"""
if not IReactorPluggableNameResolver.providedBy(reactor):
warningString = deprecate.getDeprecationWarningString(
reactor.__class__,
Version("Twisted", 17, 5, 0),
format=(
"Passing HostnameEndpoint a reactor that does not"
" provide IReactorPluggableNameResolver (%(fqpn)s)"
" was deprecated in %(version)s"
),
replacement=(
"a reactor that provides" " IReactorPluggableNameResolver"
),
)
warnings.warn(warningString, DeprecationWarning, stacklevel=3)
return _SimpleHostnameResolver(self._fallbackNameResolution)
return reactor.nameResolver
@staticmethod
def _hostAsBytesAndText(host):
"""
For various reasons (documented in the C{@ivar}'s in the class
docstring) we need both a textual and a binary representation of the
hostname given to the constructor. For compatibility and convenience,
we accept both textual and binary representations of the hostname, save
the form that was passed, and convert into the other form. This is
mostly just because L{HostnameAddress} chose somewhat poorly to define
its attribute as bytes; hopefully we can find a compatible way to clean
this up in the future and just operate in terms of text internally.
@param host: A hostname to convert.
@type host: L{bytes} or C{str}
@return: a 3-tuple of C{(invalid, bytes, text)} where C{invalid} is a
boolean indicating the validity of the hostname, C{bytes} is a
binary representation of C{host}, and C{text} is a textual
representation of C{host}.
"""
if isinstance(host, bytes):
if isIPAddress(host) or isIPv6Address(host):
return False, host, host.decode("ascii")
else:
try:
return False, host, _idnaText(host)
except UnicodeError:
# Convert the host to _some_ kind of text, to handle below.
host = host.decode("charmap")
else:
host = normalize("NFC", host)
if isIPAddress(host) or isIPv6Address(host):
return False, host.encode("ascii"), host
else:
try:
return False, _idnaBytes(host), host
except UnicodeError:
pass
# `host` has been converted to text by this point either way; it's
# invalid as a hostname, and so may contain unprintable characters and
# such. escape it with backslashes so the user can get _some_ guess as
# to what went wrong.
asciibytes = host.encode("ascii", "backslashreplace")
return True, asciibytes, asciibytes.decode("ascii")
def connect(self, protocolFactory):
"""
Attempts a connection to each resolved address, and returns a
connection which is established first.
@param protocolFactory: The protocol factory whose protocol
will be connected.
@type protocolFactory:
L{IProtocolFactory<twisted.internet.interfaces.IProtocolFactory>}
@return: A L{Deferred} that fires with the connected protocol
or fails a connection-related error.
"""
if self._badHostname:
return defer.fail(ValueError(f"invalid hostname: {self._hostStr}"))
d = Deferred()
addresses = []
@provider(IResolutionReceiver)
class EndpointReceiver:
@staticmethod
def resolutionBegan(resolutionInProgress):
pass
@staticmethod
def addressResolved(address):
addresses.append(address)
@staticmethod
def resolutionComplete():
d.callback(addresses)
self._nameResolver.resolveHostName(
EndpointReceiver, self._hostText, portNumber=self._port
)
d.addErrback(
lambda ignored: defer.fail(
error.DNSLookupError(f"Couldn't find the hostname '{self._hostStr}'")
)
)
@d.addCallback
def resolvedAddressesToEndpoints(addresses):
# Yield an endpoint for every address resolved from the name.
for eachAddress in addresses:
if isinstance(eachAddress, IPv6Address):
yield TCP6ClientEndpoint(
self._reactor,
eachAddress.host,
eachAddress.port,
self._timeout,
self._bindAddress,
)
if isinstance(eachAddress, IPv4Address):
yield TCP4ClientEndpoint(
self._reactor,
eachAddress.host,
eachAddress.port,
self._timeout,
self._bindAddress,
)
d.addCallback(list)
def _canceller(d):
# This canceller must remain defined outside of
# `startConnectionAttempts`, because Deferred should not
# participate in cycles with their cancellers; that would create a
# potentially problematic circular reference and possibly
# gc.garbage.
d.errback(
error.ConnectingCancelledError(
HostnameAddress(self._hostBytes, self._port)
)
)