Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tcp.py 54KB

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