tcp.py 55 KB

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