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

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