tcp.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. # -*- test-case-name: twisted.test.test_tcp -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Various asynchronous TCP/IP classes.
  6. End users shouldn't use this module directly - use the reactor APIs instead.
  7. """
  8. from __future__ import annotations
  9. import os
  10. import socket
  11. import struct
  12. import sys
  13. from typing import Callable, ClassVar, List, Optional, Union
  14. from zope.interface import Interface, implementer
  15. import attr
  16. import typing_extensions
  17. from twisted.internet.interfaces import (
  18. IHalfCloseableProtocol,
  19. IListeningPort,
  20. IProtocol,
  21. IReactorTCP,
  22. ISystemHandle,
  23. ITCPTransport,
  24. )
  25. from twisted.logger import ILogObserver, LogEvent, Logger
  26. from twisted.python import deprecate, versions
  27. from twisted.python.compat import lazyByteSlice
  28. from twisted.python.runtime import platformType
  29. try:
  30. # Try to get the memory BIO based startTLS implementation, available since
  31. # pyOpenSSL 0.10
  32. from twisted.internet._newtls import (
  33. ClientMixin as _TLSClientMixin,
  34. ConnectionMixin as _TLSConnectionMixin,
  35. ServerMixin as _TLSServerMixin,
  36. )
  37. from twisted.internet.interfaces import ITLSTransport
  38. except ImportError:
  39. # There is no version of startTLS available
  40. ITLSTransport = Interface # type: ignore[misc,assignment]
  41. class _TLSConnectionMixin: # type: ignore[no-redef]
  42. TLS = False
  43. class _TLSClientMixin: # type: ignore[no-redef]
  44. pass
  45. class _TLSServerMixin: # type: ignore[no-redef]
  46. pass
  47. if platformType == "win32":
  48. # no such thing as WSAEPERM or error code 10001
  49. # according to winsock.h or MSDN
  50. EPERM = object()
  51. from errno import ( # type: ignore[attr-defined]
  52. WSAEALREADY as EALREADY,
  53. WSAEINPROGRESS as EINPROGRESS,
  54. WSAEINVAL as EINVAL,
  55. WSAEISCONN as EISCONN,
  56. WSAEMFILE as EMFILE,
  57. WSAENOBUFS as ENOBUFS,
  58. WSAEWOULDBLOCK as EWOULDBLOCK,
  59. )
  60. # No such thing as WSAENFILE, either.
  61. ENFILE = object()
  62. # Nor ENOMEM
  63. ENOMEM = object()
  64. EAGAIN = EWOULDBLOCK
  65. from errno import WSAECONNRESET as ECONNABORTED # type: ignore[attr-defined]
  66. from twisted.python.win32 import formatError as strerror
  67. else:
  68. from errno import EPERM
  69. from errno import EINVAL
  70. from errno import EWOULDBLOCK
  71. from errno import EINPROGRESS
  72. from errno import EALREADY
  73. from errno import EISCONN
  74. from errno import ENOBUFS
  75. from errno import EMFILE
  76. from errno import ENFILE
  77. from errno import ENOMEM
  78. from errno import EAGAIN
  79. from errno import ECONNABORTED
  80. from os import strerror
  81. from errno import errorcode
  82. # Twisted Imports
  83. from twisted.internet import abstract, address, base, error, fdesc, main
  84. from twisted.internet.error import CannotListenError
  85. from twisted.internet.protocol import Protocol
  86. from twisted.internet.task import deferLater
  87. from twisted.python import failure, log, reflect
  88. from twisted.python.util import untilConcludes
  89. # Not all platforms have, or support, this flag.
  90. _AI_NUMERICSERV = getattr(socket, "AI_NUMERICSERV", 0)
  91. def _getrealname(addr):
  92. """
  93. Return a 2-tuple of socket IP and port for IPv4 and a 4-tuple of
  94. socket IP, port, flowInfo, and scopeID for IPv6. For IPv6, it
  95. returns the interface portion (the part after the %) as a part of
  96. the IPv6 address, which Python 3.7+ does not include.
  97. @param addr: A 2-tuple for IPv4 information or a 4-tuple for IPv6
  98. information.
  99. """
  100. if len(addr) == 4:
  101. # IPv6
  102. host = socket.getnameinfo(addr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)[
  103. 0
  104. ]
  105. return tuple([host] + list(addr[1:]))
  106. else:
  107. return addr[:2]
  108. def _getpeername(skt):
  109. """
  110. See L{_getrealname}.
  111. """
  112. return _getrealname(skt.getpeername())
  113. def _getsockname(skt):
  114. """
  115. See L{_getrealname}.
  116. """
  117. return _getrealname(skt.getsockname())
  118. class _SocketCloser:
  119. """
  120. @ivar _shouldShutdown: Set to C{True} if C{shutdown} should be called
  121. before calling C{close} on the underlying socket.
  122. @type _shouldShutdown: C{bool}
  123. """
  124. _shouldShutdown = True
  125. def _closeSocket(self, orderly):
  126. # The call to shutdown() before close() isn't really necessary, because
  127. # we set FD_CLOEXEC now, which will ensure this is the only process
  128. # holding the FD, thus ensuring close() really will shutdown the TCP
  129. # socket. However, do it anyways, just to be safe.
  130. skt = self.socket
  131. try:
  132. if orderly:
  133. if self._shouldShutdown:
  134. skt.shutdown(2)
  135. else:
  136. # Set SO_LINGER to 1,0 which, by convention, causes a
  137. # connection reset to be sent when close is called,
  138. # instead of the standard FIN shutdown sequence.
  139. self.socket.setsockopt(
  140. socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)
  141. )
  142. except OSError:
  143. pass
  144. try:
  145. skt.close()
  146. except OSError:
  147. pass
  148. class _AbortingMixin:
  149. """
  150. Common implementation of C{abortConnection}.
  151. @ivar _aborting: Set to C{True} when C{abortConnection} is called.
  152. @type _aborting: C{bool}
  153. """
  154. _aborting = False
  155. def abortConnection(self):
  156. """
  157. Aborts the connection immediately, dropping any buffered data.
  158. @since: 11.1
  159. """
  160. if self.disconnected or self._aborting:
  161. return
  162. self._aborting = True
  163. self.stopReading()
  164. self.stopWriting()
  165. self.doRead = lambda *args, **kwargs: None
  166. self.doWrite = lambda *args, **kwargs: None
  167. self.reactor.callLater(
  168. 0, self.connectionLost, failure.Failure(error.ConnectionAborted())
  169. )
  170. @implementer(ITLSTransport, ITCPTransport, ISystemHandle)
  171. class Connection(
  172. _TLSConnectionMixin, abstract.FileDescriptor, _SocketCloser, _AbortingMixin
  173. ):
  174. """
  175. Superclass of all socket-based FileDescriptors.
  176. This is an abstract superclass of all objects which represent a TCP/IP
  177. connection based socket.
  178. @ivar logstr: prefix used when logging events related to this connection.
  179. @type logstr: C{str}
  180. """
  181. def __init__(self, skt, protocol, reactor=None):
  182. abstract.FileDescriptor.__init__(self, reactor=reactor)
  183. self.socket = skt
  184. self.socket.setblocking(0)
  185. self.fileno = skt.fileno
  186. self.protocol = protocol
  187. def getHandle(self):
  188. """Return the socket for this connection."""
  189. return self.socket
  190. def doRead(self):
  191. """Calls self.protocol.dataReceived with all available data.
  192. This reads up to self.bufferSize bytes of data from its socket, then
  193. calls self.dataReceived(data) to process it. If the connection is not
  194. lost through an error in the physical recv(), this function will return
  195. the result of the dataReceived call.
  196. """
  197. try:
  198. data = self.socket.recv(self.bufferSize)
  199. except OSError as se:
  200. if se.args[0] == EWOULDBLOCK:
  201. return
  202. else:
  203. return main.CONNECTION_LOST
  204. return self._dataReceived(data)
  205. def _dataReceived(self, data):
  206. if not data:
  207. return main.CONNECTION_DONE
  208. rval = self.protocol.dataReceived(data)
  209. if rval is not None:
  210. offender = self.protocol.dataReceived
  211. warningFormat = (
  212. "Returning a value other than None from %(fqpn)s is "
  213. "deprecated since %(version)s."
  214. )
  215. warningString = deprecate.getDeprecationWarningString(
  216. offender, versions.Version("Twisted", 11, 0, 0), format=warningFormat
  217. )
  218. deprecate.warnAboutFunction(offender, warningString)
  219. return rval
  220. def writeSomeData(self, data):
  221. """
  222. Write as much as possible of the given data to this TCP connection.
  223. This sends up to C{self.SEND_LIMIT} bytes from C{data}. If the
  224. connection is lost, an exception is returned. Otherwise, the number
  225. of bytes successfully written is returned.
  226. """
  227. # Limit length of buffer to try to send, because some OSes are too
  228. # stupid to do so themselves (ahem windows)
  229. limitedData = lazyByteSlice(data, 0, self.SEND_LIMIT)
  230. try:
  231. return untilConcludes(self.socket.send, limitedData)
  232. except OSError as se:
  233. if se.args[0] in (EWOULDBLOCK, ENOBUFS):
  234. return 0
  235. else:
  236. return main.CONNECTION_LOST
  237. def _closeWriteConnection(self):
  238. try:
  239. self.socket.shutdown(1)
  240. except OSError:
  241. pass
  242. p = IHalfCloseableProtocol(self.protocol, None)
  243. if p:
  244. try:
  245. p.writeConnectionLost()
  246. except BaseException:
  247. f = failure.Failure()
  248. log.err()
  249. self.connectionLost(f)
  250. def readConnectionLost(self, reason):
  251. p = IHalfCloseableProtocol(self.protocol, None)
  252. if p:
  253. try:
  254. p.readConnectionLost()
  255. except BaseException:
  256. log.err()
  257. self.connectionLost(failure.Failure())
  258. else:
  259. self.connectionLost(reason)
  260. def connectionLost(self, reason):
  261. """See abstract.FileDescriptor.connectionLost()."""
  262. # Make sure we're not called twice, which can happen e.g. if
  263. # abortConnection() is called from protocol's dataReceived and then
  264. # code immediately after throws an exception that reaches the
  265. # reactor. We can't rely on "disconnected" attribute for this check
  266. # since twisted.internet._oldtls does evil things to it:
  267. if not hasattr(self, "socket"):
  268. return
  269. abstract.FileDescriptor.connectionLost(self, reason)
  270. self._closeSocket(not reason.check(error.ConnectionAborted))
  271. protocol = self.protocol
  272. del self.protocol
  273. del self.socket
  274. del self.fileno
  275. protocol.connectionLost(reason)
  276. logstr = "Uninitialized"
  277. def logPrefix(self):
  278. """Return the prefix to log with when I own the logging thread."""
  279. return self.logstr
  280. def getTcpNoDelay(self):
  281. return bool(self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY))
  282. def setTcpNoDelay(self, enabled):
  283. self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, enabled)
  284. def getTcpKeepAlive(self):
  285. return bool(self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE))
  286. def setTcpKeepAlive(self, enabled):
  287. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled)
  288. class _BaseBaseClient:
  289. """
  290. Code shared with other (non-POSIX) reactors for management of general
  291. outgoing connections.
  292. Requirements upon subclasses are documented as instance variables rather
  293. than abstract methods, in order to avoid MRO confusion, since this base is
  294. mixed in to unfortunately weird and distinctive multiple-inheritance
  295. hierarchies and many of these attributes are provided by peer classes
  296. rather than descendant classes in those hierarchies.
  297. @ivar addressFamily: The address family constant (C{socket.AF_INET},
  298. C{socket.AF_INET6}, C{socket.AF_UNIX}) of the underlying socket of this
  299. client connection.
  300. @type addressFamily: C{int}
  301. @ivar socketType: The socket type constant (C{socket.SOCK_STREAM} or
  302. C{socket.SOCK_DGRAM}) of the underlying socket.
  303. @type socketType: C{int}
  304. @ivar _requiresResolution: A flag indicating whether the address of this
  305. client will require name resolution. C{True} if the hostname of said
  306. address indicates a name that must be resolved by hostname lookup,
  307. C{False} if it indicates an IP address literal.
  308. @type _requiresResolution: C{bool}
  309. @cvar _commonConnection: Subclasses must provide this attribute, which
  310. indicates the L{Connection}-alike class to invoke C{__init__} and
  311. C{connectionLost} on.
  312. @type _commonConnection: C{type}
  313. @ivar _stopReadingAndWriting: Subclasses must implement in order to remove
  314. this transport from its reactor's notifications in response to a
  315. terminated connection attempt.
  316. @type _stopReadingAndWriting: 0-argument callable returning L{None}
  317. @ivar _closeSocket: Subclasses must implement in order to close the socket
  318. in response to a terminated connection attempt.
  319. @type _closeSocket: 1-argument callable; see L{_SocketCloser._closeSocket}
  320. @ivar _collectSocketDetails: Clean up references to the attached socket in
  321. its underlying OS resource (such as a file descriptor or file handle),
  322. as part of post connection-failure cleanup.
  323. @type _collectSocketDetails: 0-argument callable returning L{None}.
  324. @ivar reactor: The class pointed to by C{_commonConnection} should set this
  325. attribute in its constructor.
  326. @type reactor: L{twisted.internet.interfaces.IReactorTime},
  327. L{twisted.internet.interfaces.IReactorCore},
  328. L{twisted.internet.interfaces.IReactorFDSet}
  329. """
  330. addressFamily = socket.AF_INET
  331. socketType = socket.SOCK_STREAM
  332. def _finishInit(self, whenDone, skt, error, reactor):
  333. """
  334. Called by subclasses to continue to the stage of initialization where
  335. the socket connect attempt is made.
  336. @param whenDone: A 0-argument callable to invoke once the connection is
  337. set up. This is L{None} if the connection could not be prepared
  338. due to a previous error.
  339. @param skt: The socket object to use to perform the connection.
  340. @type skt: C{socket._socketobject}
  341. @param error: The error to fail the connection with.
  342. @param reactor: The reactor to use for this client.
  343. @type reactor: L{twisted.internet.interfaces.IReactorTime}
  344. """
  345. if whenDone:
  346. self._commonConnection.__init__(self, skt, None, reactor)
  347. reactor.callLater(0, whenDone)
  348. else:
  349. reactor.callLater(0, self.failIfNotConnected, error)
  350. def resolveAddress(self):
  351. """
  352. Resolve the name that was passed to this L{_BaseBaseClient}, if
  353. necessary, and then move on to attempting the connection once an
  354. address has been determined. (The connection will be attempted
  355. immediately within this function if either name resolution can be
  356. synchronous or the address was an IP address literal.)
  357. @note: You don't want to call this method from outside, as it won't do
  358. anything useful; it's just part of the connection bootstrapping
  359. process. Also, although this method is on L{_BaseBaseClient} for
  360. historical reasons, it's not used anywhere except for L{Client}
  361. itself.
  362. @return: L{None}
  363. """
  364. if self._requiresResolution:
  365. d = self.reactor.resolve(self.addr[0])
  366. d.addCallback(lambda n: (n,) + self.addr[1:])
  367. d.addCallbacks(self._setRealAddress, self.failIfNotConnected)
  368. else:
  369. self._setRealAddress(self.addr)
  370. def _setRealAddress(self, address):
  371. """
  372. Set the resolved address of this L{_BaseBaseClient} and initiate the
  373. connection attempt.
  374. @param address: Depending on whether this is an IPv4 or IPv6 connection
  375. attempt, a 2-tuple of C{(host, port)} or a 4-tuple of C{(host,
  376. port, flow, scope)}. At this point it is a fully resolved address,
  377. and the 'host' portion will always be an IP address, not a DNS
  378. name.
  379. """
  380. if len(address) == 4:
  381. # IPv6, make sure we have the scopeID associated
  382. hostname = socket.getnameinfo(
  383. address, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV
  384. )[0]
  385. self.realAddress = tuple([hostname] + list(address[1:]))
  386. else:
  387. self.realAddress = address
  388. self.doConnect()
  389. def failIfNotConnected(self, err):
  390. """
  391. Generic method called when the attempts to connect failed. It basically
  392. cleans everything it can: call connectionFailed, stop read and write,
  393. delete socket related members.
  394. """
  395. if self.connected or self.disconnected or not hasattr(self, "connector"):
  396. return
  397. self._stopReadingAndWriting()
  398. try:
  399. self._closeSocket(True)
  400. except AttributeError:
  401. pass
  402. else:
  403. self._collectSocketDetails()
  404. self.connector.connectionFailed(failure.Failure(err))
  405. del self.connector
  406. def stopConnecting(self):
  407. """
  408. If a connection attempt is still outstanding (i.e. no connection is
  409. yet established), immediately stop attempting to connect.
  410. """
  411. self.failIfNotConnected(error.UserError())
  412. def connectionLost(self, reason):
  413. """
  414. Invoked by lower-level logic when it's time to clean the socket up.
  415. Depending on the state of the connection, either inform the attached
  416. L{Connector} that the connection attempt has failed, or inform the
  417. connected L{IProtocol} that the established connection has been lost.
  418. @param reason: the reason that the connection was terminated
  419. @type reason: L{Failure}
  420. """
  421. if not self.connected:
  422. self.failIfNotConnected(error.ConnectError(string=reason))
  423. else:
  424. self._commonConnection.connectionLost(self, reason)
  425. self.connector.connectionLost(reason)
  426. class BaseClient(_BaseBaseClient, _TLSClientMixin, Connection):
  427. """
  428. A base class for client TCP (and similar) sockets.
  429. @ivar realAddress: The address object that will be used for socket.connect;
  430. this address is an address tuple (the number of elements dependent upon
  431. the address family) which does not contain any names which need to be
  432. resolved.
  433. @type realAddress: C{tuple}
  434. @ivar _base: L{Connection}, which is the base class of this class which has
  435. all of the useful file descriptor methods. This is used by
  436. L{_TLSServerMixin} to call the right methods to directly manipulate the
  437. transport, as is necessary for writing TLS-encrypted bytes (whereas
  438. those methods on L{Server} will go through another layer of TLS if it
  439. has been enabled).
  440. """
  441. _base = Connection
  442. _commonConnection = Connection
  443. def _stopReadingAndWriting(self):
  444. """
  445. Implement the POSIX-ish (i.e.
  446. L{twisted.internet.interfaces.IReactorFDSet}) method of detaching this
  447. socket from the reactor for L{_BaseBaseClient}.
  448. """
  449. if hasattr(self, "reactor"):
  450. # this doesn't happen if we failed in __init__
  451. self.stopReading()
  452. self.stopWriting()
  453. def _collectSocketDetails(self):
  454. """
  455. Clean up references to the socket and its file descriptor.
  456. @see: L{_BaseBaseClient}
  457. """
  458. del self.socket, self.fileno
  459. def createInternetSocket(self):
  460. """(internal) Create a non-blocking socket using
  461. self.addressFamily, self.socketType.
  462. """
  463. s = socket.socket(self.addressFamily, self.socketType)
  464. s.setblocking(0)
  465. fdesc._setCloseOnExec(s.fileno())
  466. return s
  467. def doConnect(self):
  468. """
  469. Initiate the outgoing connection attempt.
  470. @note: Applications do not need to call this method; it will be invoked
  471. internally as part of L{IReactorTCP.connectTCP}.
  472. """
  473. self.doWrite = self.doConnect
  474. self.doRead = self.doConnect
  475. if not hasattr(self, "connector"):
  476. # this happens when connection failed but doConnect
  477. # was scheduled via a callLater in self._finishInit
  478. return
  479. err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  480. if err:
  481. self.failIfNotConnected(error.getConnectError((err, strerror(err))))
  482. return
  483. # doConnect gets called twice. The first time we actually need to
  484. # start the connection attempt. The second time we don't really
  485. # want to (SO_ERROR above will have taken care of any errors, and if
  486. # it reported none, the mere fact that doConnect was called again is
  487. # sufficient to indicate that the connection has succeeded), but it
  488. # is not /particularly/ detrimental to do so. This should get
  489. # cleaned up some day, though.
  490. try:
  491. connectResult = self.socket.connect_ex(self.realAddress)
  492. except OSError as se:
  493. connectResult = se.args[0]
  494. if connectResult:
  495. if connectResult == EISCONN:
  496. pass
  497. # on Windows EINVAL means sometimes that we should keep trying:
  498. # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/connect_2.asp
  499. elif (connectResult in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (
  500. connectResult == EINVAL and platformType == "win32"
  501. ):
  502. self.startReading()
  503. self.startWriting()
  504. return
  505. else:
  506. self.failIfNotConnected(
  507. error.getConnectError((connectResult, strerror(connectResult)))
  508. )
  509. return
  510. # If I have reached this point without raising or returning, that means
  511. # that the socket is connected.
  512. del self.doWrite
  513. del self.doRead
  514. # we first stop and then start, to reset any references to the old doRead
  515. self.stopReading()
  516. self.stopWriting()
  517. self._connectDone()
  518. def _connectDone(self):
  519. """
  520. This is a hook for when a connection attempt has succeeded.
  521. Here, we build the protocol from the
  522. L{twisted.internet.protocol.ClientFactory} that was passed in, compute
  523. a log string, begin reading so as to send traffic to the newly built
  524. protocol, and finally hook up the protocol itself.
  525. This hook is overridden by L{ssl.Client} to initiate the TLS protocol.
  526. """
  527. self.protocol = self.connector.buildProtocol(self.getPeer())
  528. self.connected = 1
  529. logPrefix = self._getLogPrefix(self.protocol)
  530. self.logstr = "%s,client" % logPrefix
  531. if self.protocol is None:
  532. # Factory.buildProtocol is allowed to return None. In that case,
  533. # make up a protocol to satisfy the rest of the implementation;
  534. # connectionLost is going to be called on something, for example.
  535. # This is easier than adding special case support for a None
  536. # protocol throughout the rest of the transport implementation.
  537. self.protocol = Protocol()
  538. # But dispose of the connection quickly.
  539. self.loseConnection()
  540. else:
  541. self.startReading()
  542. self.protocol.makeConnection(self)
  543. _NUMERIC_ONLY = socket.AI_NUMERICHOST | _AI_NUMERICSERV
  544. def _resolveIPv6(ip, port):
  545. """
  546. Resolve an IPv6 literal into an IPv6 address.
  547. This is necessary to resolve any embedded scope identifiers to the relevant
  548. C{sin6_scope_id} for use with C{socket.connect()}, C{socket.listen()}, or
  549. C{socket.bind()}; see U{RFC 3493 <https://tools.ietf.org/html/rfc3493>} for
  550. more information.
  551. @param ip: An IPv6 address literal.
  552. @type ip: C{str}
  553. @param port: A port number.
  554. @type port: C{int}
  555. @return: a 4-tuple of C{(host, port, flow, scope)}, suitable for use as an
  556. IPv6 address.
  557. @raise socket.gaierror: if either the IP or port is not numeric as it
  558. should be.
  559. """
  560. return socket.getaddrinfo(ip, port, 0, 0, 0, _NUMERIC_ONLY)[0][4]
  561. class _BaseTCPClient:
  562. """
  563. Code shared with other (non-POSIX) reactors for management of outgoing TCP
  564. connections (both TCPv4 and TCPv6).
  565. @note: In order to be functional, this class must be mixed into the same
  566. hierarchy as L{_BaseBaseClient}. It would subclass L{_BaseBaseClient}
  567. directly, but the class hierarchy here is divided in strange ways out
  568. of the need to share code along multiple axes; specifically, with the
  569. IOCP reactor and also with UNIX clients in other reactors.
  570. @ivar _addressType: The Twisted _IPAddress implementation for this client
  571. @type _addressType: L{IPv4Address} or L{IPv6Address}
  572. @ivar connector: The L{Connector} which is driving this L{_BaseTCPClient}'s
  573. connection attempt.
  574. @ivar addr: The address that this socket will be connecting to.
  575. @type addr: If IPv4, a 2-C{tuple} of C{(str host, int port)}. If IPv6, a
  576. 4-C{tuple} of (C{str host, int port, int ignored, int scope}).
  577. @ivar createInternetSocket: Subclasses must implement this as a method to
  578. create a python socket object of the appropriate address family and
  579. socket type.
  580. @type createInternetSocket: 0-argument callable returning
  581. C{socket._socketobject}.
  582. """
  583. _addressType = address.IPv4Address
  584. def __init__(self, host, port, bindAddress, connector, reactor=None):
  585. # BaseClient.__init__ is invoked later
  586. self.connector = connector
  587. self.addr = (host, port)
  588. whenDone = self.resolveAddress
  589. err = None
  590. skt = None
  591. if abstract.isIPAddress(host):
  592. self._requiresResolution = False
  593. elif abstract.isIPv6Address(host):
  594. self._requiresResolution = False
  595. self.addr = _resolveIPv6(host, port)
  596. self.addressFamily = socket.AF_INET6
  597. self._addressType = address.IPv6Address
  598. else:
  599. self._requiresResolution = True
  600. try:
  601. skt = self.createInternetSocket()
  602. except OSError as se:
  603. err = error.ConnectBindError(se.args[0], se.args[1])
  604. whenDone = None
  605. if whenDone and bindAddress is not None:
  606. try:
  607. if abstract.isIPv6Address(bindAddress[0]):
  608. bindinfo = _resolveIPv6(*bindAddress)
  609. else:
  610. bindinfo = bindAddress
  611. skt.bind(bindinfo)
  612. except OSError as se:
  613. err = error.ConnectBindError(se.args[0], se.args[1])
  614. whenDone = None
  615. self._finishInit(whenDone, skt, err, reactor)
  616. def getHost(self):
  617. """
  618. Returns an L{IPv4Address} or L{IPv6Address}.
  619. This indicates the address from which I am connecting.
  620. """
  621. return self._addressType("TCP", *_getsockname(self.socket))
  622. def getPeer(self):
  623. """
  624. Returns an L{IPv4Address} or L{IPv6Address}.
  625. This indicates the address that I am connected to.
  626. """
  627. return self._addressType("TCP", *self.realAddress)
  628. def __repr__(self) -> str:
  629. s = f"<{self.__class__} to {self.addr} at {id(self):x}>"
  630. return s
  631. class Client(_BaseTCPClient, BaseClient):
  632. """
  633. A transport for a TCP protocol; either TCPv4 or TCPv6.
  634. Do not create these directly; use L{IReactorTCP.connectTCP}.
  635. """
  636. class Server(_TLSServerMixin, Connection):
  637. """
  638. Serverside socket-stream connection class.
  639. This is a serverside network connection transport; a socket which came from
  640. an accept() on a server.
  641. @ivar _base: L{Connection}, which is the base class of this class which has
  642. all of the useful file descriptor methods. This is used by
  643. L{_TLSServerMixin} to call the right methods to directly manipulate the
  644. transport, as is necessary for writing TLS-encrypted bytes (whereas
  645. those methods on L{Server} will go through another layer of TLS if it
  646. has been enabled).
  647. """
  648. _base = Connection
  649. _addressType: Union[
  650. type[address.IPv4Address], type[address.IPv6Address]
  651. ] = address.IPv4Address
  652. def __init__(
  653. self,
  654. sock: socket.socket,
  655. protocol: IProtocol,
  656. client: tuple[object, ...],
  657. server: Port,
  658. sessionno: int,
  659. reactor: IReactorTCP,
  660. ) -> None:
  661. """
  662. Server(sock, protocol, client, server, sessionno)
  663. Initialize it with a socket, a protocol, a descriptor for my peer (a
  664. tuple of host, port describing the other end of the connection), an
  665. instance of Port, and a session number.
  666. """
  667. Connection.__init__(self, sock, protocol, reactor)
  668. if len(client) != 2:
  669. self._addressType = address.IPv6Address
  670. self.server = server
  671. self.client = client
  672. self.sessionno = sessionno
  673. self.hostname = client[0]
  674. logPrefix = self._getLogPrefix(self.protocol)
  675. self.logstr = f"{logPrefix},{sessionno},{self.hostname}"
  676. if self.server is not None:
  677. self.repstr: str = "<{} #{} on {}>".format(
  678. self.protocol.__class__.__name__,
  679. self.sessionno,
  680. self.server._realPortNumber,
  681. )
  682. self.startReading()
  683. self.connected = 1
  684. def __repr__(self) -> str:
  685. """
  686. A string representation of this connection.
  687. """
  688. return self.repstr
  689. @classmethod
  690. def _fromConnectedSocket(cls, fileDescriptor, addressFamily, factory, reactor):
  691. """
  692. Create a new L{Server} based on an existing connected I{SOCK_STREAM}
  693. socket.
  694. Arguments are the same as to L{Server.__init__}, except where noted.
  695. @param fileDescriptor: An integer file descriptor associated with a
  696. connected socket. The socket must be in non-blocking mode. Any
  697. additional attributes desired, such as I{FD_CLOEXEC}, must also be
  698. set already.
  699. @param addressFamily: The address family (sometimes called I{domain})
  700. of the existing socket. For example, L{socket.AF_INET}.
  701. @return: A new instance of C{cls} wrapping the socket given by
  702. C{fileDescriptor}.
  703. """
  704. addressType = address.IPv4Address
  705. if addressFamily == socket.AF_INET6:
  706. addressType = address.IPv6Address
  707. skt = socket.fromfd(fileDescriptor, addressFamily, socket.SOCK_STREAM)
  708. addr = _getpeername(skt)
  709. protocolAddr = addressType("TCP", *addr)
  710. localPort = skt.getsockname()[1]
  711. protocol = factory.buildProtocol(protocolAddr)
  712. if protocol is None:
  713. skt.close()
  714. return
  715. self = cls(skt, protocol, addr, None, addr[1], reactor)
  716. self.repstr = "<{} #{} on {}>".format(
  717. self.protocol.__class__.__name__,
  718. self.sessionno,
  719. localPort,
  720. )
  721. protocol.makeConnection(self)
  722. return self
  723. def getHost(self):
  724. """
  725. Returns an L{IPv4Address} or L{IPv6Address}.
  726. This indicates the server's address.
  727. """
  728. addr = _getsockname(self.socket)
  729. return self._addressType("TCP", *addr)
  730. def getPeer(self):
  731. """
  732. Returns an L{IPv4Address} or L{IPv6Address}.
  733. This indicates the client's address.
  734. """
  735. return self._addressType("TCP", *self.client)
  736. class _IFileDescriptorReservation(Interface):
  737. """
  738. An open file that represents an emergency reservation in the
  739. process' file descriptor table. If L{Port} encounters C{EMFILE}
  740. on C{accept(2)}, it can close this file descriptor, retry the
  741. C{accept} so that the incoming connection occupies this file
  742. descriptor's space, and then close that connection and reopen this
  743. one.
  744. Calling L{_IFileDescriptorReservation.reserve} attempts to open
  745. the reserve file descriptor if it is not already open.
  746. L{_IFileDescriptorReservation.available} returns L{True} if the
  747. underlying file is open and its descriptor claimed.
  748. L{_IFileDescriptorReservation} instances are context managers;
  749. entering them releases the underlying file descriptor, while
  750. exiting them attempts to reacquire it. The block can take
  751. advantage of the free slot in the process' file descriptor table
  752. accept and close a client connection.
  753. Because another thread might open a file descriptor between the
  754. time the context manager is entered and the time C{accept} is
  755. called, opening the reserve descriptor is best-effort only.
  756. """
  757. def available():
  758. """
  759. Is the reservation available?
  760. @return: L{True} if the reserved file descriptor is open and
  761. can thus be closed to allow a new file to be opened in its
  762. place; L{False} if it is not open.
  763. """
  764. def reserve():
  765. """
  766. Attempt to open the reserved file descriptor; if this fails
  767. because of C{EMFILE}, internal state is reset so that another
  768. reservation attempt can be made.
  769. @raises Exception: Any exception except an L{OSError} whose
  770. errno is L{EMFILE}.
  771. """
  772. def __enter__():
  773. """
  774. Release the underlying file descriptor so that code within the
  775. context manager can open a new file.
  776. """
  777. def __exit__(excType, excValue, traceback):
  778. """
  779. Attempt to re-open the reserved file descriptor. See
  780. L{reserve} for caveats.
  781. @param excType: See L{object.__exit__}
  782. @param excValue: See L{object.__exit__}
  783. @param traceback: See L{object.__exit__}
  784. """
  785. class _HasClose(typing_extensions.Protocol):
  786. def close(self) -> object:
  787. ...
  788. @implementer(_IFileDescriptorReservation)
  789. @attr.s(auto_attribs=True)
  790. class _FileDescriptorReservation:
  791. """
  792. L{_IFileDescriptorReservation} implementation.
  793. @ivar fileFactory: A factory that will be called to reserve a
  794. file descriptor.
  795. @type fileFactory: A L{callable} that accepts no arguments and
  796. returns an object with a C{close} method.
  797. """
  798. _log: ClassVar[Logger] = Logger()
  799. _fileFactory: Callable[[], _HasClose]
  800. _fileDescriptor: Optional[_HasClose] = attr.ib(init=False, default=None)
  801. def available(self):
  802. """
  803. See L{_IFileDescriptorReservation.available}.
  804. @return: L{True} if the reserved file descriptor is open and
  805. can thus be closed to allow a new file to be opened in its
  806. place; L{False} if it is not open.
  807. """
  808. return self._fileDescriptor is not None
  809. def reserve(self):
  810. """
  811. See L{_IFileDescriptorReservation.reserve}.
  812. """
  813. if self._fileDescriptor is None:
  814. try:
  815. fileDescriptor = self._fileFactory()
  816. except OSError as e:
  817. if e.errno == EMFILE:
  818. self._log.failure(
  819. "Could not reserve EMFILE recovery file descriptor."
  820. )
  821. else:
  822. raise
  823. else:
  824. self._fileDescriptor = fileDescriptor
  825. def __enter__(self):
  826. """
  827. See L{_IFileDescriptorReservation.__enter__}.
  828. """
  829. if self._fileDescriptor is None:
  830. raise RuntimeError("No file reserved. Have you called my reserve method?")
  831. self._fileDescriptor.close()
  832. self._fileDescriptor = None
  833. def __exit__(self, excType, excValue, traceback):
  834. """
  835. See L{_IFileDescriptorReservation.__exit__}.
  836. """
  837. try:
  838. self.reserve()
  839. except Exception:
  840. self._log.failure("Could not re-reserve EMFILE recovery file descriptor.")
  841. @implementer(_IFileDescriptorReservation)
  842. class _NullFileDescriptorReservation:
  843. """
  844. A null implementation of L{_IFileDescriptorReservation}.
  845. """
  846. def available(self):
  847. """
  848. The reserved file is never available. See
  849. L{_IFileDescriptorReservation.available}.
  850. @return: L{False}
  851. """
  852. return False
  853. def reserve(self):
  854. """
  855. Do nothing. See L{_IFileDescriptorReservation.reserve}.
  856. """
  857. def __enter__(self):
  858. """
  859. Do nothing. See L{_IFileDescriptorReservation.__enter__}
  860. @return: L{False}
  861. """
  862. def __exit__(self, excType, excValue, traceback):
  863. """
  864. Do nothing. See L{_IFileDescriptorReservation.__exit__}.
  865. @param excType: See L{object.__exit__}
  866. @param excValue: See L{object.__exit__}
  867. @param traceback: See L{object.__exit__}
  868. """
  869. # Don't keep a reserve file descriptor for coping with file descriptor
  870. # exhaustion on Windows.
  871. # WSAEMFILE occurs when a process has run out of memory, not when a
  872. # specific limit has been reached. Windows sockets are handles, which
  873. # differ from UNIX's file descriptors in that they can refer to any
  874. # "named kernel object", including user interface resources like menu
  875. # and icons. The generality of handles results in a much higher limit
  876. # than UNIX imposes on file descriptors: a single Windows process can
  877. # allocate up to 16,777,216 handles. Because they're indexes into a
  878. # three level table whose upper two layers are allocated from
  879. # swappable pages, handles compete for heap space with other kernel
  880. # objects, not with each other. Closing a given socket handle may not
  881. # release enough memory to allow the process to make progress.
  882. #
  883. # This fundamental difference between file descriptors and handles
  884. # makes a reserve file descriptor useless on Windows. Note that other
  885. # event loops, such as libuv and libevent, also do not special case
  886. # WSAEMFILE.
  887. #
  888. # For an explanation of handles, see the "Object Manager"
  889. # (pp. 140-175) section of
  890. #
  891. # Windows Internals, Part 1: Covering Windows Server 2008 R2 and
  892. # Windows 7 (6th ed.)
  893. # Mark E. Russinovich, David A. Solomon, and Alex
  894. # Ionescu. 2012. Microsoft Press.
  895. if platformType == "win32":
  896. _reservedFD = _NullFileDescriptorReservation()
  897. else:
  898. _reservedFD = _FileDescriptorReservation(lambda: open(os.devnull)) # type: ignore[assignment]
  899. # Linux and other UNIX-like operating systems return EMFILE when a
  900. # process has reached its soft limit of file descriptors. *BSD and
  901. # Win32 raise (WSA)ENOBUFS when socket limits are reached. Linux can
  902. # give ENFILE if the system is out of inodes, or ENOMEM if there is
  903. # insufficient memory to allocate a new dentry. ECONNABORTED is
  904. # documented as possible on all relevant platforms (Linux, Windows,
  905. # macOS, and the BSDs) but occurs only on the BSDs. It occurs when a
  906. # client sends a FIN or RST after the server sends a SYN|ACK but
  907. # before application code calls accept(2). On Linux, calling
  908. # accept(2) on such a listener returns a connection that fails as
  909. # though the it were terminated after being fully established. This
  910. # appears to be an implementation choice (see inet_accept in
  911. # inet/ipv4/af_inet.c). On macOS, such a listener is not considered
  912. # readable, so accept(2) will never be called. Calling accept(2) on
  913. # such a listener, however, does not return at all.
  914. _ACCEPT_ERRORS = (EMFILE, ENOBUFS, ENFILE, ENOMEM, ECONNABORTED)
  915. @attr.s(auto_attribs=True)
  916. class _BuffersLogs:
  917. """
  918. A context manager that buffers any log events until after its
  919. block exits.
  920. @ivar _namespace: The namespace of the buffered events.
  921. @type _namespace: L{str}.
  922. @ivar _observer: The observer to which buffered log events will be
  923. written
  924. @type _observer: L{twisted.logger.ILogObserver}.
  925. """
  926. _namespace: str
  927. _observer: ILogObserver
  928. _logs: List[LogEvent] = attr.ib(default=attr.Factory(list))
  929. def __enter__(self):
  930. """
  931. Enter a log buffering context.
  932. @return: A logger that buffers log events.
  933. @rtype: L{Logger}.
  934. """
  935. return Logger(namespace=self._namespace, observer=self._logs.append)
  936. def __exit__(self, excValue, excType, traceback):
  937. """
  938. Exit a log buffering context and log all buffered events to
  939. the provided observer.
  940. @param excType: See L{object.__exit__}
  941. @param excValue: See L{object.__exit__}
  942. @param traceback: See L{object.__exit__}
  943. """
  944. for event in self._logs:
  945. self._observer(event)
  946. def _accept(logger, accepts, listener, reservedFD):
  947. """
  948. Return a generator that yields client sockets from the provided
  949. listening socket until there are none left or an unrecoverable
  950. error occurs.
  951. @param logger: A logger to which C{accept}-related events will be
  952. logged. This should not log to arbitrary observers that might
  953. open a file descriptor to avoid claiming the C{EMFILE} file
  954. descriptor on UNIX-like systems.
  955. @type logger: L{Logger}
  956. @param accepts: An iterable iterated over to limit the number
  957. consecutive C{accept}s.
  958. @type accepts: An iterable.
  959. @param listener: The listening socket.
  960. @type listener: L{socket.socket}
  961. @param reservedFD: A reserved file descriptor that can be used to
  962. recover from C{EMFILE} on UNIX-like systems.
  963. @type reservedFD: L{_IFileDescriptorReservation}
  964. @return: A generator that yields C{(socket, addr)} tuples from
  965. L{socket.socket.accept}
  966. """
  967. for _ in accepts:
  968. try:
  969. client, address = listener.accept()
  970. except OSError as e:
  971. if e.args[0] in (EWOULDBLOCK, EAGAIN):
  972. # No more clients.
  973. return
  974. elif e.args[0] == EPERM:
  975. # Netfilter on Linux may have rejected the
  976. # connection, but we get told to try to accept()
  977. # anyway.
  978. continue
  979. elif e.args[0] == EMFILE and reservedFD.available():
  980. # Linux and other UNIX-like operating systems return
  981. # EMFILE when a process has reached its soft limit of
  982. # file descriptors. The reserved file descriptor is
  983. # available, so it can be released to free up a
  984. # descriptor for use by listener.accept()'s clients.
  985. # Each client socket will be closed until the listener
  986. # returns EAGAIN.
  987. logger.info(
  988. "EMFILE encountered;" " releasing reserved file descriptor."
  989. )
  990. # The following block should not run arbitrary code
  991. # that might acquire its own file descriptor.
  992. with reservedFD:
  993. clientsToClose = _accept(logger, accepts, listener, reservedFD)
  994. for clientToClose, closedAddress in clientsToClose:
  995. clientToClose.close()
  996. logger.info(
  997. "EMFILE recovery:" " Closed socket from {address}",
  998. address=closedAddress,
  999. )
  1000. logger.info("Re-reserving EMFILE recovery file descriptor.")
  1001. return
  1002. elif e.args[0] in _ACCEPT_ERRORS:
  1003. logger.info(
  1004. "Could not accept new connection ({acceptError})",
  1005. acceptError=errorcode[e.args[0]],
  1006. )
  1007. return
  1008. else:
  1009. raise
  1010. else:
  1011. yield client, address
  1012. @implementer(IListeningPort)
  1013. class Port(base.BasePort, _SocketCloser):
  1014. """
  1015. A TCP server port, listening for connections.
  1016. When a connection is accepted, this will call a factory's buildProtocol
  1017. with the incoming address as an argument, according to the specification
  1018. described in L{twisted.internet.interfaces.IProtocolFactory}.
  1019. If you wish to change the sort of transport that will be used, the
  1020. C{transport} attribute will be called with the signature expected for
  1021. C{Server.__init__}, so it can be replaced.
  1022. @ivar deferred: a deferred created when L{stopListening} is called, and
  1023. that will fire when connection is lost. This is not to be used it
  1024. directly: prefer the deferred returned by L{stopListening} instead.
  1025. @type deferred: L{defer.Deferred}
  1026. @ivar disconnecting: flag indicating that the L{stopListening} method has
  1027. been called and that no connections should be accepted anymore.
  1028. @type disconnecting: C{bool}
  1029. @ivar connected: flag set once the listen has successfully been called on
  1030. the socket.
  1031. @type connected: C{bool}
  1032. @ivar _type: A string describing the connections which will be created by
  1033. this port. Normally this is C{"TCP"}, since this is a TCP port, but
  1034. when the TLS implementation re-uses this class it overrides the value
  1035. with C{"TLS"}. Only used for logging.
  1036. @ivar _preexistingSocket: If not L{None}, a L{socket.socket} instance which
  1037. was created and initialized outside of the reactor and will be used to
  1038. listen for connections (instead of a new socket being created by this
  1039. L{Port}).
  1040. """
  1041. socketType = socket.SOCK_STREAM
  1042. transport = Server
  1043. sessionno = 0
  1044. interface = ""
  1045. backlog = 50
  1046. _type = "TCP"
  1047. # Actual port number being listened on, only set to a non-None
  1048. # value when we are actually listening.
  1049. _realPortNumber: Optional[int] = None
  1050. # An externally initialized socket that we will use, rather than creating
  1051. # our own.
  1052. _preexistingSocket = None
  1053. addressFamily = socket.AF_INET
  1054. _addressType = address.IPv4Address
  1055. _logger = Logger()
  1056. def __init__(self, port, factory, backlog=50, interface="", reactor=None):
  1057. """Initialize with a numeric port to listen on."""
  1058. base.BasePort.__init__(self, reactor=reactor)
  1059. self.port = port
  1060. self.factory = factory
  1061. self.backlog = backlog
  1062. if abstract.isIPv6Address(interface):
  1063. self.addressFamily = socket.AF_INET6
  1064. self._addressType = address.IPv6Address
  1065. self.interface = interface
  1066. @classmethod
  1067. def _fromListeningDescriptor(cls, reactor, fd, addressFamily, factory):
  1068. """
  1069. Create a new L{Port} based on an existing listening I{SOCK_STREAM}
  1070. socket.
  1071. Arguments are the same as to L{Port.__init__}, except where noted.
  1072. @param fd: An integer file descriptor associated with a listening
  1073. socket. The socket must be in non-blocking mode. Any additional
  1074. attributes desired, such as I{FD_CLOEXEC}, must also be set already.
  1075. @param addressFamily: The address family (sometimes called I{domain}) of
  1076. the existing socket. For example, L{socket.AF_INET}.
  1077. @return: A new instance of C{cls} wrapping the socket given by C{fd}.
  1078. """
  1079. port = socket.fromfd(fd, addressFamily, cls.socketType)
  1080. interface = _getsockname(port)[0]
  1081. self = cls(None, factory, None, interface, reactor)
  1082. self._preexistingSocket = port
  1083. return self
  1084. def __repr__(self) -> str:
  1085. if self._realPortNumber is not None:
  1086. return "<{} of {} on {}>".format(
  1087. self.__class__,
  1088. self.factory.__class__,
  1089. self._realPortNumber,
  1090. )
  1091. else:
  1092. return "<{} of {} (not listening)>".format(
  1093. self.__class__,
  1094. self.factory.__class__,
  1095. )
  1096. def createInternetSocket(self):
  1097. s = base.BasePort.createInternetSocket(self)
  1098. if platformType == "posix" and sys.platform != "cygwin":
  1099. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1100. return s
  1101. def startListening(self):
  1102. """Create and bind my socket, and begin listening on it.
  1103. This is called on unserialization, and must be called after creating a
  1104. server to begin listening on the specified port.
  1105. """
  1106. _reservedFD.reserve()
  1107. if self._preexistingSocket is None:
  1108. # Create a new socket and make it listen
  1109. try:
  1110. skt = self.createInternetSocket()
  1111. if self.addressFamily == socket.AF_INET6:
  1112. addr = _resolveIPv6(self.interface, self.port)
  1113. else:
  1114. addr = (self.interface, self.port)
  1115. skt.bind(addr)
  1116. except OSError as le:
  1117. raise CannotListenError(self.interface, self.port, le)
  1118. skt.listen(self.backlog)
  1119. else:
  1120. # Re-use the externally specified socket
  1121. skt = self._preexistingSocket
  1122. self._preexistingSocket = None
  1123. # Avoid shutting it down at the end.
  1124. self._shouldShutdown = False
  1125. # Make sure that if we listened on port 0, we update that to
  1126. # reflect what the OS actually assigned us.
  1127. self._realPortNumber = skt.getsockname()[1]
  1128. log.msg(
  1129. "%s starting on %s"
  1130. % (self._getLogPrefix(self.factory), self._realPortNumber)
  1131. )
  1132. # The order of the next 5 lines is kind of bizarre. If no one
  1133. # can explain it, perhaps we should re-arrange them.
  1134. self.factory.doStart()
  1135. self.connected = True
  1136. self.socket = skt
  1137. self.fileno = self.socket.fileno
  1138. self.numberAccepts = 100
  1139. self.startReading()
  1140. def _buildAddr(self, address):
  1141. return self._addressType("TCP", *address)
  1142. def doRead(self):
  1143. """
  1144. Called when my socket is ready for reading.
  1145. This accepts a connection and calls self.protocol() to handle the
  1146. wire-level protocol.
  1147. """
  1148. try:
  1149. if platformType == "posix":
  1150. numAccepts = self.numberAccepts
  1151. else:
  1152. # win32 event loop breaks if we do more than one accept()
  1153. # in an iteration of the event loop.
  1154. numAccepts = 1
  1155. with _BuffersLogs(
  1156. self._logger.namespace, self._logger.observer
  1157. ) as bufferingLogger:
  1158. accepted = 0
  1159. clients = _accept(
  1160. bufferingLogger, range(numAccepts), self.socket, _reservedFD
  1161. )
  1162. for accepted, (skt, addr) in enumerate(clients, 1):
  1163. fdesc._setCloseOnExec(skt.fileno())
  1164. if len(addr) == 4:
  1165. # IPv6, make sure we get the scopeID if it
  1166. # exists
  1167. host = socket.getnameinfo(
  1168. addr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV
  1169. )
  1170. addr = tuple([host[0]] + list(addr[1:]))
  1171. protocol = self.factory.buildProtocol(self._buildAddr(addr))
  1172. if protocol is None:
  1173. skt.close()
  1174. continue
  1175. s = self.sessionno
  1176. self.sessionno = s + 1
  1177. transport = self.transport(
  1178. skt, protocol, addr, self, s, self.reactor
  1179. )
  1180. protocol.makeConnection(transport)
  1181. # Scale our synchronous accept loop according to traffic
  1182. # Reaching our limit on consecutive accept calls indicates
  1183. # there might be still more clients to serve the next time
  1184. # the reactor calls us. Prepare to accept some more.
  1185. if accepted == self.numberAccepts:
  1186. self.numberAccepts += 20
  1187. # Otherwise, don't attempt to accept any more clients than
  1188. # we just accepted or any less than 1.
  1189. else:
  1190. self.numberAccepts = max(1, accepted)
  1191. except BaseException:
  1192. # Note that in TLS mode, this will possibly catch SSL.Errors
  1193. # raised by self.socket.accept()
  1194. #
  1195. # There is no "except SSL.Error:" above because SSL may be
  1196. # None if there is no SSL support. In any case, all the
  1197. # "except SSL.Error:" suite would probably do is log.deferr()
  1198. # and return, so handling it here works just as well.
  1199. log.deferr()
  1200. def loseConnection(self, connDone=failure.Failure(main.CONNECTION_DONE)):
  1201. """
  1202. Stop accepting connections on this port.
  1203. This will shut down the socket and call self.connectionLost(). It
  1204. returns a deferred which will fire successfully when the port is
  1205. actually closed, or with a failure if an error occurs shutting down.
  1206. """
  1207. self.disconnecting = True
  1208. self.stopReading()
  1209. if self.connected:
  1210. self.deferred = deferLater(self.reactor, 0, self.connectionLost, connDone)
  1211. return self.deferred
  1212. stopListening = loseConnection
  1213. def _logConnectionLostMsg(self):
  1214. """
  1215. Log message for closing port
  1216. """
  1217. log.msg(f"({self._type} Port {self._realPortNumber} Closed)")
  1218. def connectionLost(self, reason):
  1219. """
  1220. Cleans up the socket.
  1221. """
  1222. self._logConnectionLostMsg()
  1223. self._realPortNumber = None
  1224. base.BasePort.connectionLost(self, reason)
  1225. self.connected = False
  1226. self._closeSocket(True)
  1227. del self.socket
  1228. del self.fileno
  1229. try:
  1230. self.factory.doStop()
  1231. finally:
  1232. self.disconnecting = False
  1233. def logPrefix(self):
  1234. """Returns the name of my class, to prefix log entries with."""
  1235. return reflect.qual(self.factory.__class__)
  1236. def getHost(self):
  1237. """
  1238. Return an L{IPv4Address} or L{IPv6Address} indicating the listening
  1239. address of this port.
  1240. """
  1241. addr = _getsockname(self.socket)
  1242. return self._addressType("TCP", *addr)
  1243. class Connector(base.BaseConnector):
  1244. """
  1245. A L{Connector} provides of L{twisted.internet.interfaces.IConnector} for
  1246. all POSIX-style reactors.
  1247. @ivar _addressType: the type returned by L{Connector.getDestination}.
  1248. Either L{IPv4Address} or L{IPv6Address}, depending on the type of
  1249. address.
  1250. @type _addressType: C{type}
  1251. """
  1252. _addressType = address.IPv4Address
  1253. def __init__(self, host, port, factory, timeout, bindAddress, reactor=None):
  1254. if isinstance(port, str):
  1255. try:
  1256. port = socket.getservbyname(port, "tcp")
  1257. except OSError as e:
  1258. raise error.ServiceNameUnknownError(string=f"{e} ({port!r})")
  1259. self.host, self.port = host, port
  1260. if abstract.isIPv6Address(host):
  1261. self._addressType = address.IPv6Address
  1262. self.bindAddress = bindAddress
  1263. base.BaseConnector.__init__(self, factory, timeout, reactor)
  1264. def _makeTransport(self):
  1265. """
  1266. Create a L{Client} bound to this L{Connector}.
  1267. @return: a new L{Client}
  1268. @rtype: L{Client}
  1269. """
  1270. return Client(self.host, self.port, self.bindAddress, self, self.reactor)
  1271. def getDestination(self):
  1272. """
  1273. @see: L{twisted.internet.interfaces.IConnector.getDestination}.
  1274. """
  1275. return self._addressType("TCP", self.host, self.port)