PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/twisted/internet/tcp.py

https://github.com/adaschevici/twisted
Python | 1180 lines | 830 code | 89 blank | 261 comment | 65 complexity | 07e2cbed341bd06d3793ad4d766edf4c MD5 | raw file
  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 types
  11. import socket
  12. import sys
  13. import operator
  14. import struct
  15. from zope.interface import implementer
  16. from twisted.python.compat import _PY3, lazyByteSlice
  17. from twisted.python.runtime import platformType
  18. from twisted.python import versions, deprecate
  19. try:
  20. # Try to get the memory BIO based startTLS implementation, available since
  21. # pyOpenSSL 0.10
  22. from twisted.internet._newtls import (
  23. ConnectionMixin as _TLSConnectionMixin,
  24. ClientMixin as _TLSClientMixin,
  25. ServerMixin as _TLSServerMixin)
  26. except ImportError:
  27. # There is no version of startTLS available
  28. class _TLSConnectionMixin(object):
  29. TLS = False
  30. class _TLSClientMixin(object):
  31. pass
  32. class _TLSServerMixin(object):
  33. pass
  34. if platformType == 'win32':
  35. # no such thing as WSAEPERM or error code 10001 according to winsock.h or MSDN
  36. EPERM = object()
  37. from errno import WSAEINVAL as EINVAL
  38. from errno import WSAEWOULDBLOCK as EWOULDBLOCK
  39. from errno import WSAEINPROGRESS as EINPROGRESS
  40. from errno import WSAEALREADY as EALREADY
  41. from errno import WSAECONNRESET as ECONNRESET
  42. from errno import WSAEISCONN as EISCONN
  43. from errno import WSAENOTCONN as ENOTCONN
  44. from errno import WSAEINTR as EINTR
  45. from errno import WSAENOBUFS as ENOBUFS
  46. from errno import WSAEMFILE as EMFILE
  47. # No such thing as WSAENFILE, either.
  48. ENFILE = object()
  49. # Nor ENOMEM
  50. ENOMEM = object()
  51. EAGAIN = EWOULDBLOCK
  52. from errno import WSAECONNRESET as ECONNABORTED
  53. from twisted.python.win32 import formatError as strerror
  54. else:
  55. from errno import EPERM
  56. from errno import EINVAL
  57. from errno import EWOULDBLOCK
  58. from errno import EINPROGRESS
  59. from errno import EALREADY
  60. from errno import ECONNRESET
  61. from errno import EISCONN
  62. from errno import ENOTCONN
  63. from errno import EINTR
  64. from errno import ENOBUFS
  65. from errno import EMFILE
  66. from errno import ENFILE
  67. from errno import ENOMEM
  68. from errno import EAGAIN
  69. from errno import ECONNABORTED
  70. from os import strerror
  71. from errno import errorcode
  72. # Twisted Imports
  73. from twisted.internet import base, address, fdesc
  74. from twisted.internet.task import deferLater
  75. from twisted.python import log, failure, reflect
  76. from twisted.python.util import untilConcludes
  77. from twisted.internet.error import CannotListenError
  78. from twisted.internet import abstract, main, interfaces, error
  79. # Not all platforms have, or support, this flag.
  80. _AI_NUMERICSERV = getattr(socket, "AI_NUMERICSERV", 0)
  81. # The type for service names passed to socket.getservbyname:
  82. if _PY3:
  83. _portNameType = str
  84. else:
  85. _portNameType = types.StringTypes
  86. class _SocketCloser(object):
  87. """
  88. @ivar _shouldShutdown: Set to C{True} if C{shutdown} should be called
  89. before callling C{close} on the underlying socket.
  90. @type _shouldShutdown: C{bool}
  91. """
  92. _shouldShutdown = True
  93. def _closeSocket(self, orderly):
  94. # The call to shutdown() before close() isn't really necessary, because
  95. # we set FD_CLOEXEC now, which will ensure this is the only process
  96. # holding the FD, thus ensuring close() really will shutdown the TCP
  97. # socket. However, do it anyways, just to be safe.
  98. skt = self.socket
  99. try:
  100. if orderly:
  101. if self._shouldShutdown:
  102. skt.shutdown(2)
  103. else:
  104. # Set SO_LINGER to 1,0 which, by convention, causes a
  105. # connection reset to be sent when close is called,
  106. # instead of the standard FIN shutdown sequence.
  107. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
  108. struct.pack("ii", 1, 0))
  109. except socket.error:
  110. pass
  111. try:
  112. skt.close()
  113. except socket.error:
  114. pass
  115. class _AbortingMixin(object):
  116. """
  117. Common implementation of C{abortConnection}.
  118. @ivar _aborting: Set to C{True} when C{abortConnection} is called.
  119. @type _aborting: C{bool}
  120. """
  121. _aborting = False
  122. def abortConnection(self):
  123. """
  124. Aborts the connection immediately, dropping any buffered data.
  125. @since: 11.1
  126. """
  127. if self.disconnected or self._aborting:
  128. return
  129. self._aborting = True
  130. self.stopReading()
  131. self.stopWriting()
  132. self.doRead = lambda *args, **kwargs: None
  133. self.doWrite = lambda *args, **kwargs: None
  134. self.reactor.callLater(0, self.connectionLost,
  135. failure.Failure(error.ConnectionAborted()))
  136. @implementer(interfaces.ITCPTransport, interfaces.ISystemHandle)
  137. class Connection(_TLSConnectionMixin, abstract.FileDescriptor, _SocketCloser,
  138. _AbortingMixin):
  139. """
  140. Superclass of all socket-based FileDescriptors.
  141. This is an abstract superclass of all objects which represent a TCP/IP
  142. connection based socket.
  143. @ivar logstr: prefix used when logging events related to this connection.
  144. @type logstr: C{str}
  145. """
  146. def __init__(self, skt, protocol, reactor=None):
  147. abstract.FileDescriptor.__init__(self, reactor=reactor)
  148. self.socket = skt
  149. self.socket.setblocking(0)
  150. self.fileno = skt.fileno
  151. self.protocol = protocol
  152. def getHandle(self):
  153. """Return the socket for this connection."""
  154. return self.socket
  155. def doRead(self):
  156. """Calls self.protocol.dataReceived with all available data.
  157. This reads up to self.bufferSize bytes of data from its socket, then
  158. calls self.dataReceived(data) to process it. If the connection is not
  159. lost through an error in the physical recv(), this function will return
  160. the result of the dataReceived call.
  161. """
  162. try:
  163. data = self.socket.recv(self.bufferSize)
  164. except socket.error as se:
  165. if se.args[0] == EWOULDBLOCK:
  166. return
  167. else:
  168. return main.CONNECTION_LOST
  169. return self._dataReceived(data)
  170. def _dataReceived(self, data):
  171. if not data:
  172. return main.CONNECTION_DONE
  173. rval = self.protocol.dataReceived(data)
  174. if rval is not None:
  175. offender = self.protocol.dataReceived
  176. warningFormat = (
  177. 'Returning a value other than None from %(fqpn)s is '
  178. 'deprecated since %(version)s.')
  179. warningString = deprecate.getDeprecationWarningString(
  180. offender, versions.Version('Twisted', 11, 0, 0),
  181. format=warningFormat)
  182. deprecate.warnAboutFunction(offender, warningString)
  183. return rval
  184. def writeSomeData(self, data):
  185. """
  186. Write as much as possible of the given data to this TCP connection.
  187. This sends up to C{self.SEND_LIMIT} bytes from C{data}. If the
  188. connection is lost, an exception is returned. Otherwise, the number
  189. of bytes successfully written is returned.
  190. """
  191. # Limit length of buffer to try to send, because some OSes are too
  192. # stupid to do so themselves (ahem windows)
  193. limitedData = lazyByteSlice(data, 0, self.SEND_LIMIT)
  194. try:
  195. return untilConcludes(self.socket.send, limitedData)
  196. except socket.error as se:
  197. if se.args[0] in (EWOULDBLOCK, ENOBUFS):
  198. return 0
  199. else:
  200. return main.CONNECTION_LOST
  201. def _closeWriteConnection(self):
  202. try:
  203. self.socket.shutdown(1)
  204. except socket.error:
  205. pass
  206. p = interfaces.IHalfCloseableProtocol(self.protocol, None)
  207. if p:
  208. try:
  209. p.writeConnectionLost()
  210. except:
  211. f = failure.Failure()
  212. log.err()
  213. self.connectionLost(f)
  214. def readConnectionLost(self, reason):
  215. p = interfaces.IHalfCloseableProtocol(self.protocol, None)
  216. if p:
  217. try:
  218. p.readConnectionLost()
  219. except:
  220. log.err()
  221. self.connectionLost(failure.Failure())
  222. else:
  223. self.connectionLost(reason)
  224. def connectionLost(self, reason):
  225. """See abstract.FileDescriptor.connectionLost().
  226. """
  227. # Make sure we're not called twice, which can happen e.g. if
  228. # abortConnection() is called from protocol's dataReceived and then
  229. # code immediately after throws an exception that reaches the
  230. # reactor. We can't rely on "disconnected" attribute for this check
  231. # since twisted.internet._oldtls does evil things to it:
  232. if not hasattr(self, "socket"):
  233. return
  234. abstract.FileDescriptor.connectionLost(self, reason)
  235. self._closeSocket(not reason.check(error.ConnectionAborted))
  236. protocol = self.protocol
  237. del self.protocol
  238. del self.socket
  239. del self.fileno
  240. protocol.connectionLost(reason)
  241. logstr = "Uninitialized"
  242. def logPrefix(self):
  243. """Return the prefix to log with when I own the logging thread.
  244. """
  245. return self.logstr
  246. def getTcpNoDelay(self):
  247. return operator.truth(self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY))
  248. def setTcpNoDelay(self, enabled):
  249. self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, enabled)
  250. def getTcpKeepAlive(self):
  251. return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
  252. socket.SO_KEEPALIVE))
  253. def setTcpKeepAlive(self, enabled):
  254. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled)
  255. class _BaseBaseClient(object):
  256. """
  257. Code shared with other (non-POSIX) reactors for management of general
  258. outgoing connections.
  259. Requirements upon subclasses are documented as instance variables rather
  260. than abstract methods, in order to avoid MRO confusion, since this base is
  261. mixed in to unfortunately weird and distinctive multiple-inheritance
  262. hierarchies and many of these attributes are provided by peer classes
  263. rather than descendant classes in those hierarchies.
  264. @ivar addressFamily: The address family constant (C{socket.AF_INET},
  265. C{socket.AF_INET6}, C{socket.AF_UNIX}) of the underlying socket of this
  266. client connection.
  267. @type addressFamily: C{int}
  268. @ivar socketType: The socket type constant (C{socket.SOCK_STREAM} or
  269. C{socket.SOCK_DGRAM}) of the underlying socket.
  270. @type socketType: C{int}
  271. @ivar _requiresResolution: A flag indicating whether the address of this
  272. client will require name resolution. C{True} if the hostname of said
  273. address indicates a name that must be resolved by hostname lookup,
  274. C{False} if it indicates an IP address literal.
  275. @type _requiresResolution: C{bool}
  276. @cvar _commonConnection: Subclasses must provide this attribute, which
  277. indicates the L{Connection}-alike class to invoke C{__init__} and
  278. C{connectionLost} on.
  279. @type _commonConnection: C{type}
  280. @ivar _stopReadingAndWriting: Subclasses must implement in order to remove
  281. this transport from its reactor's notifications in response to a
  282. terminated connection attempt.
  283. @type _stopReadingAndWriting: 0-argument callable returning C{None}
  284. @ivar _closeSocket: Subclasses must implement in order to close the socket
  285. in response to a terminated connection attempt.
  286. @type _closeSocket: 1-argument callable; see L{_SocketCloser._closeSocket}
  287. @ivar _collectSocketDetails: Clean up references to the attached socket in
  288. its underlying OS resource (such as a file descriptor or file handle),
  289. as part of post connection-failure cleanup.
  290. @type _collectSocketDetails: 0-argument callable returning C{None}.
  291. @ivar reactor: The class pointed to by C{_commonConnection} should set this
  292. attribute in its constructor.
  293. @type reactor: L{twisted.internet.interfaces.IReactorTime},
  294. L{twisted.internet.interfaces.IReactorCore},
  295. L{twisted.internet.interfaces.IReactorFDSet}
  296. """
  297. addressFamily = socket.AF_INET
  298. socketType = socket.SOCK_STREAM
  299. def _finishInit(self, whenDone, skt, error, reactor):
  300. """
  301. Called by subclasses to continue to the stage of initialization where
  302. the socket connect attempt is made.
  303. @param whenDone: A 0-argument callable to invoke once the connection is
  304. set up. This is C{None} if the connection could not be prepared
  305. due to a previous error.
  306. @param skt: The socket object to use to perform the connection.
  307. @type skt: C{socket._socketobject}
  308. @param error: The error to fail the connection with.
  309. @param reactor: The reactor to use for this client.
  310. @type reactor: L{twisted.internet.interfaces.IReactorTime}
  311. """
  312. if whenDone:
  313. self._commonConnection.__init__(self, skt, None, reactor)
  314. reactor.callLater(0, whenDone)
  315. else:
  316. reactor.callLater(0, self.failIfNotConnected, error)
  317. def resolveAddress(self):
  318. """
  319. Resolve the name that was passed to this L{_BaseBaseClient}, if
  320. necessary, and then move on to attempting the connection once an
  321. address has been determined. (The connection will be attempted
  322. immediately within this function if either name resolution can be
  323. synchronous or the address was an IP address literal.)
  324. @note: You don't want to call this method from outside, as it won't do
  325. anything useful; it's just part of the connection bootstrapping
  326. process. Also, although this method is on L{_BaseBaseClient} for
  327. historical reasons, it's not used anywhere except for L{Client}
  328. itself.
  329. @return: C{None}
  330. """
  331. if self._requiresResolution:
  332. d = self.reactor.resolve(self.addr[0])
  333. d.addCallback(lambda n: (n,) + self.addr[1:])
  334. d.addCallbacks(self._setRealAddress, self.failIfNotConnected)
  335. else:
  336. self._setRealAddress(self.addr)
  337. def _setRealAddress(self, address):
  338. """
  339. Set the resolved address of this L{_BaseBaseClient} and initiate the
  340. connection attempt.
  341. @param address: Depending on whether this is an IPv4 or IPv6 connection
  342. attempt, a 2-tuple of C{(host, port)} or a 4-tuple of C{(host,
  343. port, flow, scope)}. At this point it is a fully resolved address,
  344. and the 'host' portion will always be an IP address, not a DNS
  345. name.
  346. """
  347. self.realAddress = address
  348. self.doConnect()
  349. def failIfNotConnected(self, err):
  350. """
  351. Generic method called when the attemps to connect failed. It basically
  352. cleans everything it can: call connectionFailed, stop read and write,
  353. delete socket related members.
  354. """
  355. if (self.connected or self.disconnected or
  356. not hasattr(self, "connector")):
  357. return
  358. self._stopReadingAndWriting()
  359. try:
  360. self._closeSocket(True)
  361. except AttributeError:
  362. pass
  363. else:
  364. self._collectSocketDetails()
  365. self.connector.connectionFailed(failure.Failure(err))
  366. del self.connector
  367. def stopConnecting(self):
  368. """
  369. If a connection attempt is still outstanding (i.e. no connection is
  370. yet established), immediately stop attempting to connect.
  371. """
  372. self.failIfNotConnected(error.UserError())
  373. def connectionLost(self, reason):
  374. """
  375. Invoked by lower-level logic when it's time to clean the socket up.
  376. Depending on the state of the connection, either inform the attached
  377. L{Connector} that the connection attempt has failed, or inform the
  378. connected L{IProtocol} that the established connection has been lost.
  379. @param reason: the reason that the connection was terminated
  380. @type reason: L{Failure}
  381. """
  382. if not self.connected:
  383. self.failIfNotConnected(error.ConnectError(string=reason))
  384. else:
  385. self._commonConnection.connectionLost(self, reason)
  386. self.connector.connectionLost(reason)
  387. class BaseClient(_BaseBaseClient, _TLSClientMixin, Connection):
  388. """
  389. A base class for client TCP (and similiar) sockets.
  390. @ivar realAddress: The address object that will be used for socket.connect;
  391. this address is an address tuple (the number of elements dependent upon
  392. the address family) which does not contain any names which need to be
  393. resolved.
  394. @type realAddress: C{tuple}
  395. @ivar _base: L{Connection}, which is the base class of this class which has
  396. all of the useful file descriptor methods. This is used by
  397. L{_TLSServerMixin} to call the right methods to directly manipulate the
  398. transport, as is necessary for writing TLS-encrypted bytes (whereas
  399. those methods on L{Server} will go through another layer of TLS if it
  400. has been enabled).
  401. """
  402. _base = Connection
  403. _commonConnection = Connection
  404. def _stopReadingAndWriting(self):
  405. """
  406. Implement the POSIX-ish (i.e.
  407. L{twisted.internet.interfaces.IReactorFDSet}) method of detaching this
  408. socket from the reactor for L{_BaseBaseClient}.
  409. """
  410. if hasattr(self, "reactor"):
  411. # this doesn't happen if we failed in __init__
  412. self.stopReading()
  413. self.stopWriting()
  414. def _collectSocketDetails(self):
  415. """
  416. Clean up references to the socket and its file descriptor.
  417. @see: L{_BaseBaseClient}
  418. """
  419. del self.socket, self.fileno
  420. def createInternetSocket(self):
  421. """(internal) Create a non-blocking socket using
  422. self.addressFamily, self.socketType.
  423. """
  424. s = socket.socket(self.addressFamily, self.socketType)
  425. s.setblocking(0)
  426. fdesc._setCloseOnExec(s.fileno())
  427. return s
  428. def doConnect(self):
  429. """
  430. Initiate the outgoing connection attempt.
  431. @note: Applications do not need to call this method; it will be invoked
  432. internally as part of L{IReactorTCP.connectTCP}.
  433. """
  434. self.doWrite = self.doConnect
  435. self.doRead = self.doConnect
  436. if not hasattr(self, "connector"):
  437. # this happens when connection failed but doConnect
  438. # was scheduled via a callLater in self._finishInit
  439. return
  440. err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  441. if err:
  442. self.failIfNotConnected(error.getConnectError((err, strerror(err))))
  443. return
  444. # doConnect gets called twice. The first time we actually need to
  445. # start the connection attempt. The second time we don't really
  446. # want to (SO_ERROR above will have taken care of any errors, and if
  447. # it reported none, the mere fact that doConnect was called again is
  448. # sufficient to indicate that the connection has succeeded), but it
  449. # is not /particularly/ detrimental to do so. This should get
  450. # cleaned up some day, though.
  451. try:
  452. connectResult = self.socket.connect_ex(self.realAddress)
  453. except socket.error as se:
  454. connectResult = se.args[0]
  455. if connectResult:
  456. if connectResult == EISCONN:
  457. pass
  458. # on Windows EINVAL means sometimes that we should keep trying:
  459. # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/connect_2.asp
  460. elif ((connectResult in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or
  461. (connectResult == EINVAL and platformType == "win32")):
  462. self.startReading()
  463. self.startWriting()
  464. return
  465. else:
  466. self.failIfNotConnected(error.getConnectError((connectResult, strerror(connectResult))))
  467. return
  468. # If I have reached this point without raising or returning, that means
  469. # that the socket is connected.
  470. del self.doWrite
  471. del self.doRead
  472. # we first stop and then start, to reset any references to the old doRead
  473. self.stopReading()
  474. self.stopWriting()
  475. self._connectDone()
  476. def _connectDone(self):
  477. """
  478. This is a hook for when a connection attempt has succeeded.
  479. Here, we build the protocol from the
  480. L{twisted.internet.protocol.ClientFactory} that was passed in, compute
  481. a log string, begin reading so as to send traffic to the newly built
  482. protocol, and finally hook up the protocol itself.
  483. This hook is overridden by L{ssl.Client} to initiate the TLS protocol.
  484. """
  485. self.protocol = self.connector.buildProtocol(self.getPeer())
  486. self.connected = 1
  487. logPrefix = self._getLogPrefix(self.protocol)
  488. self.logstr = "%s,client" % logPrefix
  489. self.startReading()
  490. self.protocol.makeConnection(self)
  491. _NUMERIC_ONLY = socket.AI_NUMERICHOST | _AI_NUMERICSERV
  492. def _resolveIPv6(ip, port):
  493. """
  494. Resolve an IPv6 literal into an IPv6 address.
  495. This is necessary to resolve any embedded scope identifiers to the relevant
  496. C{sin6_scope_id} for use with C{socket.connect()}, C{socket.listen()}, or
  497. C{socket.bind()}; see U{RFC 3493 <https://tools.ietf.org/html/rfc3493>} for
  498. more information.
  499. @param ip: An IPv6 address literal.
  500. @type ip: C{str}
  501. @param port: A port number.
  502. @type port: C{int}
  503. @return: a 4-tuple of C{(host, port, flow, scope)}, suitable for use as an
  504. IPv6 address.
  505. @raise socket.gaierror: if either the IP or port is not numeric as it
  506. should be.
  507. """
  508. return socket.getaddrinfo(ip, port, 0, 0, 0, _NUMERIC_ONLY)[0][4]
  509. class _BaseTCPClient(object):
  510. """
  511. Code shared with other (non-POSIX) reactors for management of outgoing TCP
  512. connections (both TCPv4 and TCPv6).
  513. @note: In order to be functional, this class must be mixed into the same
  514. hierarchy as L{_BaseBaseClient}. It would subclass L{_BaseBaseClient}
  515. directly, but the class hierarchy here is divided in strange ways out
  516. of the need to share code along multiple axes; specifically, with the
  517. IOCP reactor and also with UNIX clients in other reactors.
  518. @ivar _addressType: The Twisted _IPAddress implementation for this client
  519. @type _addressType: L{IPv4Address} or L{IPv6Address}
  520. @ivar connector: The L{Connector} which is driving this L{_BaseTCPClient}'s
  521. connection attempt.
  522. @ivar addr: The address that this socket will be connecting to.
  523. @type addr: If IPv4, a 2-C{tuple} of C{(str host, int port)}. If IPv6, a
  524. 4-C{tuple} of (C{str host, int port, int ignored, int scope}).
  525. @ivar createInternetSocket: Subclasses must implement this as a method to
  526. create a python socket object of the appropriate address family and
  527. socket type.
  528. @type createInternetSocket: 0-argument callable returning
  529. C{socket._socketobject}.
  530. """
  531. _addressType = address.IPv4Address
  532. def __init__(self, host, port, bindAddress, connector, reactor=None):
  533. # BaseClient.__init__ is invoked later
  534. self.connector = connector
  535. self.addr = (host, port)
  536. whenDone = self.resolveAddress
  537. err = None
  538. skt = None
  539. if abstract.isIPAddress(host):
  540. self._requiresResolution = False
  541. elif abstract.isIPv6Address(host):
  542. self._requiresResolution = False
  543. self.addr = _resolveIPv6(host, port)
  544. self.addressFamily = socket.AF_INET6
  545. self._addressType = address.IPv6Address
  546. else:
  547. self._requiresResolution = True
  548. try:
  549. skt = self.createInternetSocket()
  550. except socket.error as se:
  551. err = error.ConnectBindError(se.args[0], se.args[1])
  552. whenDone = None
  553. if whenDone and bindAddress is not None:
  554. try:
  555. if abstract.isIPv6Address(bindAddress[0]):
  556. bindinfo = _resolveIPv6(*bindAddress)
  557. else:
  558. bindinfo = bindAddress
  559. skt.bind(bindinfo)
  560. except socket.error as se:
  561. err = error.ConnectBindError(se.args[0], se.args[1])
  562. whenDone = None
  563. self._finishInit(whenDone, skt, err, reactor)
  564. def getHost(self):
  565. """
  566. Returns an L{IPv4Address} or L{IPv6Address}.
  567. This indicates the address from which I am connecting.
  568. """
  569. return self._addressType('TCP', *self.socket.getsockname()[:2])
  570. def getPeer(self):
  571. """
  572. Returns an L{IPv4Address} or L{IPv6Address}.
  573. This indicates the address that I am connected to.
  574. """
  575. # an ipv6 realAddress has more than two elements, but the IPv6Address
  576. # constructor still only takes two.
  577. return self._addressType('TCP', *self.realAddress[:2])
  578. def __repr__(self):
  579. s = '<%s to %s at %x>' % (self.__class__, self.addr, id(self))
  580. return s
  581. class Client(_BaseTCPClient, BaseClient):
  582. """
  583. A transport for a TCP protocol; either TCPv4 or TCPv6.
  584. Do not create these directly; use L{IReactorTCP.connectTCP}.
  585. """
  586. class Server(_TLSServerMixin, Connection):
  587. """
  588. Serverside socket-stream connection class.
  589. This is a serverside network connection transport; a socket which came from
  590. an accept() on a server.
  591. @ivar _base: L{Connection}, which is the base class of this class which has
  592. all of the useful file descriptor methods. This is used by
  593. L{_TLSServerMixin} to call the right methods to directly manipulate the
  594. transport, as is necessary for writing TLS-encrypted bytes (whereas
  595. those methods on L{Server} will go through another layer of TLS if it
  596. has been enabled).
  597. """
  598. _base = Connection
  599. _addressType = address.IPv4Address
  600. def __init__(self, sock, protocol, client, server, sessionno, reactor):
  601. """
  602. Server(sock, protocol, client, server, sessionno)
  603. Initialize it with a socket, a protocol, a descriptor for my peer (a
  604. tuple of host, port describing the other end of the connection), an
  605. instance of Port, and a session number.
  606. """
  607. Connection.__init__(self, sock, protocol, reactor)
  608. if len(client) != 2:
  609. self._addressType = address.IPv6Address
  610. self.server = server
  611. self.client = client
  612. self.sessionno = sessionno
  613. self.hostname = client[0]
  614. logPrefix = self._getLogPrefix(self.protocol)
  615. self.logstr = "%s,%s,%s" % (logPrefix,
  616. sessionno,
  617. self.hostname)
  618. if self.server is not None:
  619. self.repstr = "<%s #%s on %s>" % (self.protocol.__class__.__name__,
  620. self.sessionno,
  621. self.server._realPortNumber)
  622. self.startReading()
  623. self.connected = 1
  624. def __repr__(self):
  625. """
  626. A string representation of this connection.
  627. """
  628. return self.repstr
  629. @classmethod
  630. def _fromConnectedSocket(cls, fileDescriptor, addressFamily, factory,
  631. reactor):
  632. """
  633. Create a new L{Server} based on an existing connected I{SOCK_STREAM}
  634. socket.
  635. Arguments are the same as to L{Server.__init__}, except where noted.
  636. @param fileDescriptor: An integer file descriptor associated with a
  637. connected socket. The socket must be in non-blocking mode. Any
  638. additional attributes desired, such as I{FD_CLOEXEC}, must also be
  639. set already.
  640. @param addressFamily: The address family (sometimes called I{domain})
  641. of the existing socket. For example, L{socket.AF_INET}.
  642. @return: A new instance of C{cls} wrapping the socket given by
  643. C{fileDescriptor}.
  644. """
  645. addressType = address.IPv4Address
  646. if addressFamily == socket.AF_INET6:
  647. addressType = address.IPv6Address
  648. skt = socket.fromfd(fileDescriptor, addressFamily, socket.SOCK_STREAM)
  649. addr = skt.getpeername()
  650. protocolAddr = addressType('TCP', addr[0], addr[1])
  651. localPort = skt.getsockname()[1]
  652. protocol = factory.buildProtocol(protocolAddr)
  653. if protocol is None:
  654. skt.close()
  655. return
  656. self = cls(skt, protocol, addr, None, addr[1], reactor)
  657. self.repstr = "<%s #%s on %s>" % (
  658. self.protocol.__class__.__name__, self.sessionno, localPort)
  659. protocol.makeConnection(self)
  660. return self
  661. def getHost(self):
  662. """
  663. Returns an L{IPv4Address} or L{IPv6Address}.
  664. This indicates the server's address.
  665. """
  666. host, port = self.socket.getsockname()[:2]
  667. return self._addressType('TCP', host, port)
  668. def getPeer(self):
  669. """
  670. Returns an L{IPv4Address} or L{IPv6Address}.
  671. This indicates the client's address.
  672. """
  673. return self._addressType('TCP', *self.client[:2])
  674. @implementer(interfaces.IListeningPort)
  675. class Port(base.BasePort, _SocketCloser):
  676. """
  677. A TCP server port, listening for connections.
  678. When a connection is accepted, this will call a factory's buildProtocol
  679. with the incoming address as an argument, according to the specification
  680. described in L{twisted.internet.interfaces.IProtocolFactory}.
  681. If you wish to change the sort of transport that will be used, the
  682. C{transport} attribute will be called with the signature expected for
  683. C{Server.__init__}, so it can be replaced.
  684. @ivar deferred: a deferred created when L{stopListening} is called, and
  685. that will fire when connection is lost. This is not to be used it
  686. directly: prefer the deferred returned by L{stopListening} instead.
  687. @type deferred: L{defer.Deferred}
  688. @ivar disconnecting: flag indicating that the L{stopListening} method has
  689. been called and that no connections should be accepted anymore.
  690. @type disconnecting: C{bool}
  691. @ivar connected: flag set once the listen has successfully been called on
  692. the socket.
  693. @type connected: C{bool}
  694. @ivar _type: A string describing the connections which will be created by
  695. this port. Normally this is C{"TCP"}, since this is a TCP port, but
  696. when the TLS implementation re-uses this class it overrides the value
  697. with C{"TLS"}. Only used for logging.
  698. @ivar _preexistingSocket: If not C{None}, a L{socket.socket} instance which
  699. was created and initialized outside of the reactor and will be used to
  700. listen for connections (instead of a new socket being created by this
  701. L{Port}).
  702. """
  703. socketType = socket.SOCK_STREAM
  704. transport = Server
  705. sessionno = 0
  706. interface = ''
  707. backlog = 50
  708. _type = 'TCP'
  709. # Actual port number being listened on, only set to a non-None
  710. # value when we are actually listening.
  711. _realPortNumber = None
  712. # An externally initialized socket that we will use, rather than creating
  713. # our own.
  714. _preexistingSocket = None
  715. addressFamily = socket.AF_INET
  716. _addressType = address.IPv4Address
  717. def __init__(self, port, factory, backlog=50, interface='', reactor=None):
  718. """Initialize with a numeric port to listen on.
  719. """
  720. base.BasePort.__init__(self, reactor=reactor)
  721. self.port = port
  722. self.factory = factory
  723. self.backlog = backlog
  724. if abstract.isIPv6Address(interface):
  725. self.addressFamily = socket.AF_INET6
  726. self._addressType = address.IPv6Address
  727. self.interface = interface
  728. @classmethod
  729. def _fromListeningDescriptor(cls, reactor, fd, addressFamily, factory):
  730. """
  731. Create a new L{Port} based on an existing listening I{SOCK_STREAM}
  732. socket.
  733. Arguments are the same as to L{Port.__init__}, except where noted.
  734. @param fd: An integer file descriptor associated with a listening
  735. socket. The socket must be in non-blocking mode. Any additional
  736. attributes desired, such as I{FD_CLOEXEC}, must also be set already.
  737. @param addressFamily: The address family (sometimes called I{domain}) of
  738. the existing socket. For example, L{socket.AF_INET}.
  739. @return: A new instance of C{cls} wrapping the socket given by C{fd}.
  740. """
  741. port = socket.fromfd(fd, addressFamily, cls.socketType)
  742. interface = port.getsockname()[0]
  743. self = cls(None, factory, None, interface, reactor)
  744. self._preexistingSocket = port
  745. return self
  746. def __repr__(self):
  747. if self._realPortNumber is not None:
  748. return "<%s of %s on %s>" % (self.__class__,
  749. self.factory.__class__, self._realPortNumber)
  750. else:
  751. return "<%s of %s (not listening)>" % (self.__class__, self.factory.__class__)
  752. def createInternetSocket(self):
  753. s = base.BasePort.createInternetSocket(self)
  754. if platformType == "posix" and sys.platform != "cygwin":
  755. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  756. return s
  757. def startListening(self):
  758. """Create and bind my socket, and begin listening on it.
  759. This is called on unserialization, and must be called after creating a
  760. server to begin listening on the specified port.
  761. """
  762. if self._preexistingSocket is None:
  763. # Create a new socket and make it listen
  764. try:
  765. skt = self.createInternetSocket()
  766. if self.addressFamily == socket.AF_INET6:
  767. addr = _resolveIPv6(self.interface, self.port)
  768. else:
  769. addr = (self.interface, self.port)
  770. skt.bind(addr)
  771. except socket.error as le:
  772. raise CannotListenError(self.interface, self.port, le)
  773. skt.listen(self.backlog)
  774. else:
  775. # Re-use the externally specified socket
  776. skt = self._preexistingSocket
  777. self._preexistingSocket = None
  778. # Avoid shutting it down at the end.
  779. self._shouldShutdown = False
  780. # Make sure that if we listened on port 0, we update that to
  781. # reflect what the OS actually assigned us.
  782. self._realPortNumber = skt.getsockname()[1]
  783. log.msg("%s starting on %s" % (
  784. self._getLogPrefix(self.factory), self._realPortNumber))
  785. # The order of the next 5 lines is kind of bizarre. If no one
  786. # can explain it, perhaps we should re-arrange them.
  787. self.factory.doStart()
  788. self.connected = True
  789. self.socket = skt
  790. self.fileno = self.socket.fileno
  791. self.numberAccepts = 100
  792. self.startReading()
  793. def _buildAddr(self, address):
  794. host, port = address[:2]
  795. return self._addressType('TCP', host, port)
  796. def doRead(self):
  797. """Called when my socket is ready for reading.
  798. This accepts a connection and calls self.protocol() to handle the
  799. wire-level protocol.
  800. """
  801. try:
  802. if platformType == "posix":
  803. numAccepts = self.numberAccepts
  804. else:
  805. # win32 event loop breaks if we do more than one accept()
  806. # in an iteration of the event loop.
  807. numAccepts = 1
  808. for i in range(numAccepts):
  809. # we need this so we can deal with a factory's buildProtocol
  810. # calling our loseConnection
  811. if self.disconnecting:
  812. return
  813. try:
  814. skt, addr = self.socket.accept()
  815. except socket.error as e:
  816. if e.args[0] in (EWOULDBLOCK, EAGAIN):
  817. self.numberAccepts = i
  818. break
  819. elif e.args[0] == EPERM:
  820. # Netfilter on Linux may have rejected the
  821. # connection, but we get told to try to accept()
  822. # anyway.
  823. continue
  824. elif e.args[0] in (EMFILE, ENOBUFS, ENFILE, ENOMEM, ECONNABORTED):
  825. # Linux gives EMFILE when a process is not allowed
  826. # to allocate any more file descriptors. *BSD and
  827. # Win32 give (WSA)ENOBUFS. Linux can also give
  828. # ENFILE if the system is out of inodes, or ENOMEM
  829. # if there is insufficient memory to allocate a new
  830. # dentry. ECONNABORTED is documented as possible on
  831. # both Linux and Windows, but it is not clear
  832. # whether there are actually any circumstances under
  833. # which it can happen (one might expect it to be
  834. # possible if a client sends a FIN or RST after the
  835. # server sends a SYN|ACK but before application code
  836. # calls accept(2), however at least on Linux this
  837. # _seems_ to be short-circuited by syncookies.
  838. log.msg("Could not accept new connection (%s)" % (
  839. errorcode[e.args[0]],))
  840. break
  841. raise
  842. fdesc._setCloseOnExec(skt.fileno())
  843. protocol = self.factory.buildProtocol(self._buildAddr(addr))
  844. if protocol is None:
  845. skt.close()
  846. continue
  847. s = self.sessionno
  848. self.sessionno = s+1
  849. transport = self.transport(skt, protocol, addr, self, s, self.reactor)
  850. protocol.makeConnection(transport)
  851. else:
  852. self.numberAccepts = self.numberAccepts+20
  853. except:
  854. # Note that in TLS mode, this will possibly catch SSL.Errors
  855. # raised by self.socket.accept()
  856. #
  857. # There is no "except SSL.Error:" above because SSL may be
  858. # None if there is no SSL support. In any case, all the
  859. # "except SSL.Error:" suite would probably do is log.deferr()
  860. # and return, so handling it here works just as well.
  861. log.deferr()
  862. def loseConnection(self, connDone=failure.Failure(main.CONNECTION_DONE)):
  863. """
  864. Stop accepting connections on this port.
  865. This will shut down the socket and call self.connectionLost(). It
  866. returns a deferred which will fire successfully when the port is
  867. actually closed, or with a failure if an error occurs shutting down.
  868. """
  869. self.disconnecting = True
  870. self.stopReading()
  871. if self.connected:
  872. self.deferred = deferLater(
  873. self.reactor, 0, self.connectionLost, connDone)
  874. return self.deferred
  875. stopListening = loseConnection
  876. def _logConnectionLostMsg(self):
  877. """
  878. Log message for closing port
  879. """
  880. log.msg('(%s Port %s Closed)' % (self._type, self._realPortNumber))
  881. def connectionLost(self, reason):
  882. """
  883. Cleans up the socket.
  884. """
  885. self._logConnectionLostMsg()
  886. self._realPortNumber = None
  887. base.BasePort.connectionLost(self, reason)
  888. self.connected = False
  889. self._closeSocket(True)
  890. del self.socket
  891. del self.fileno
  892. try:
  893. self.factory.doStop()
  894. finally:
  895. self.disconnecting = False
  896. def logPrefix(self):
  897. """Returns the name of my class, to prefix log entries with.
  898. """
  899. return reflect.qual(self.factory.__class__)
  900. def getHost(self):
  901. """
  902. Return an L{IPv4Address} or L{IPv6Address} indicating the listening
  903. address of this port.
  904. """
  905. host, port = self.socket.getsockname()[:2]
  906. return self._addressType('TCP', host, port)
  907. class Connector(base.BaseConnector):
  908. """
  909. A L{Connector} provides of L{twisted.internet.interfaces.IConnector} for
  910. all POSIX-style reactors.
  911. @ivar _addressType: the type returned by L{Connector.getDestination}.
  912. Either L{IPv4Address} or L{IPv6Address}, depending on the type of
  913. address.
  914. @type _addressType: C{type}
  915. """
  916. _addressType = address.IPv4Address
  917. def __init__(self, host, port, factory, timeout, bindAddress, reactor=None):
  918. if isinstance(port, _portNameType):
  919. try:
  920. port = socket.getservbyname(port, 'tcp')
  921. except socket.error as e:
  922. raise error.ServiceNameUnknownError(string="%s (%r)" % (e, port))
  923. self.host, self.port = host, port
  924. if abstract.isIPv6Address(host):
  925. self._addressType = address.IPv6Address
  926. self.bindAddress = bindAddress
  927. base.BaseConnector.__init__(self, factory, timeout, reactor)
  928. def _makeTransport(self):
  929. """
  930. Create a L{Client} bound to this L{Connector}.
  931. @return: a new L{Client}
  932. @rtype: L{Client}
  933. """
  934. return Client(self.host, self.port, self.bindAddress, self, self.reactor)
  935. def getDestination(self):
  936. """
  937. @see: L{twisted.internet.interfaces.IConnector.getDestination}.
  938. """
  939. return self._addressType('TCP', self.host, self.port)