posixbase.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. # -*- test-case-name: twisted.test.test_internet,twisted.internet.test.test_posixbase -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Posix reactor base class
  6. """
  7. import socket
  8. import sys
  9. from typing import Sequence
  10. from zope.interface import classImplements, implementer
  11. from twisted.internet import error, tcp, udp
  12. from twisted.internet.base import ReactorBase
  13. from twisted.internet.interfaces import (
  14. IHalfCloseableDescriptor,
  15. IReactorFDSet,
  16. IReactorMulticast,
  17. IReactorProcess,
  18. IReactorSocket,
  19. IReactorSSL,
  20. IReactorTCP,
  21. IReactorUDP,
  22. IReactorUNIX,
  23. IReactorUNIXDatagram,
  24. )
  25. from twisted.internet.main import CONNECTION_DONE, CONNECTION_LOST
  26. from twisted.python import failure, log
  27. from twisted.python.runtime import platform, platformType
  28. from ._signals import (
  29. SignalHandling,
  30. _ChildSignalHandling,
  31. _IWaker,
  32. _MultiSignalHandling,
  33. _Waker,
  34. )
  35. # Exceptions that doSelect might return frequently
  36. _NO_FILEDESC = error.ConnectionFdescWentAway("File descriptor lost")
  37. try:
  38. from twisted.protocols import tls as _tls
  39. except ImportError:
  40. tls = None
  41. else:
  42. tls = _tls
  43. try:
  44. from twisted.internet import ssl as _ssl
  45. except ImportError:
  46. ssl = None
  47. else:
  48. ssl = _ssl
  49. unixEnabled = platformType == "posix"
  50. processEnabled = False
  51. if unixEnabled:
  52. from twisted.internet import process, unix
  53. processEnabled = True
  54. if platform.isWindows():
  55. try:
  56. import win32process
  57. processEnabled = True
  58. except ImportError:
  59. win32process = None
  60. class _DisconnectSelectableMixin:
  61. """
  62. Mixin providing the C{_disconnectSelectable} method.
  63. """
  64. def _disconnectSelectable(
  65. self,
  66. selectable,
  67. why,
  68. isRead,
  69. faildict={
  70. error.ConnectionDone: failure.Failure(error.ConnectionDone()),
  71. error.ConnectionLost: failure.Failure(error.ConnectionLost()),
  72. },
  73. ):
  74. """
  75. Utility function for disconnecting a selectable.
  76. Supports half-close notification, isRead should be boolean indicating
  77. whether error resulted from doRead().
  78. """
  79. self.removeReader(selectable)
  80. f = faildict.get(why.__class__)
  81. if f:
  82. if (
  83. isRead
  84. and why.__class__ == error.ConnectionDone
  85. and IHalfCloseableDescriptor.providedBy(selectable)
  86. ):
  87. selectable.readConnectionLost(f)
  88. else:
  89. self.removeWriter(selectable)
  90. selectable.connectionLost(f)
  91. else:
  92. self.removeWriter(selectable)
  93. selectable.connectionLost(failure.Failure(why))
  94. @implementer(IReactorTCP, IReactorUDP, IReactorMulticast)
  95. class PosixReactorBase(_DisconnectSelectableMixin, ReactorBase):
  96. """
  97. A basis for reactors that use file descriptors.
  98. @ivar _childWaker: L{None} or a reference to the L{_SIGCHLDWaker}
  99. which is used to properly notice child process termination.
  100. """
  101. _childWaker = None
  102. # Callable that creates a waker, overrideable so that subclasses can
  103. # substitute their own implementation:
  104. def _wakerFactory(self) -> _IWaker:
  105. return _Waker()
  106. def installWaker(self):
  107. """
  108. Install a `waker' to allow threads and signals to wake up the IO thread.
  109. We use the self-pipe trick (http://cr.yp.to/docs/selfpipe.html) to wake
  110. the reactor. On Windows we use a pair of sockets.
  111. """
  112. if not self.waker:
  113. self.waker = self._wakerFactory()
  114. self._internalReaders.add(self.waker)
  115. self.addReader(self.waker)
  116. def _signalsFactory(self) -> SignalHandling:
  117. """
  118. Customize reactor signal handling to support child processes on POSIX
  119. platforms.
  120. """
  121. baseHandling = super()._signalsFactory()
  122. # If we're on a platform that uses signals for process event signaling
  123. if platformType == "posix":
  124. # Compose ...
  125. return _MultiSignalHandling(
  126. (
  127. # the base signal handling behavior ...
  128. baseHandling,
  129. # with our extra SIGCHLD handling behavior.
  130. _ChildSignalHandling(
  131. self._addInternalReader,
  132. self._removeInternalReader,
  133. ),
  134. )
  135. )
  136. # Otherwise just use the base behavior
  137. return baseHandling
  138. # IReactorProcess
  139. def spawnProcess(
  140. self,
  141. processProtocol,
  142. executable,
  143. args=(),
  144. env={},
  145. path=None,
  146. uid=None,
  147. gid=None,
  148. usePTY=0,
  149. childFDs=None,
  150. ):
  151. if platformType == "posix":
  152. if usePTY:
  153. if childFDs is not None:
  154. raise ValueError(
  155. "Using childFDs is not supported with usePTY=True."
  156. )
  157. return process.PTYProcess(
  158. self, executable, args, env, path, processProtocol, uid, gid, usePTY
  159. )
  160. else:
  161. return process.Process(
  162. self,
  163. executable,
  164. args,
  165. env,
  166. path,
  167. processProtocol,
  168. uid,
  169. gid,
  170. childFDs,
  171. )
  172. elif platformType == "win32":
  173. if uid is not None:
  174. raise ValueError("Setting UID is unsupported on this platform.")
  175. if gid is not None:
  176. raise ValueError("Setting GID is unsupported on this platform.")
  177. if usePTY:
  178. raise ValueError("The usePTY parameter is not supported on Windows.")
  179. if childFDs:
  180. raise ValueError("Customizing childFDs is not supported on Windows.")
  181. if win32process:
  182. from twisted.internet._dumbwin32proc import Process
  183. return Process(self, processProtocol, executable, args, env, path)
  184. else:
  185. raise NotImplementedError(
  186. "spawnProcess not available since pywin32 is not installed."
  187. )
  188. else:
  189. raise NotImplementedError(
  190. "spawnProcess only available on Windows or POSIX."
  191. )
  192. # IReactorUDP
  193. def listenUDP(self, port, protocol, interface="", maxPacketSize=8192):
  194. """Connects a given L{DatagramProtocol} to the given numeric UDP port.
  195. @returns: object conforming to L{IListeningPort}.
  196. """
  197. p = udp.Port(port, protocol, interface, maxPacketSize, self)
  198. p.startListening()
  199. return p
  200. # IReactorMulticast
  201. def listenMulticast(
  202. self, port, protocol, interface="", maxPacketSize=8192, listenMultiple=False
  203. ):
  204. """Connects a given DatagramProtocol to the given numeric UDP port.
  205. EXPERIMENTAL.
  206. @returns: object conforming to IListeningPort.
  207. """
  208. p = udp.MulticastPort(
  209. port, protocol, interface, maxPacketSize, self, listenMultiple
  210. )
  211. p.startListening()
  212. return p
  213. # IReactorUNIX
  214. def connectUNIX(self, address, factory, timeout=30, checkPID=0):
  215. assert unixEnabled, "UNIX support is not present"
  216. c = unix.Connector(address, factory, timeout, self, checkPID)
  217. c.connect()
  218. return c
  219. def listenUNIX(self, address, factory, backlog=50, mode=0o666, wantPID=0):
  220. assert unixEnabled, "UNIX support is not present"
  221. p = unix.Port(address, factory, backlog, mode, self, wantPID)
  222. p.startListening()
  223. return p
  224. # IReactorUNIXDatagram
  225. def listenUNIXDatagram(self, address, protocol, maxPacketSize=8192, mode=0o666):
  226. """
  227. Connects a given L{DatagramProtocol} to the given path.
  228. EXPERIMENTAL.
  229. @returns: object conforming to L{IListeningPort}.
  230. """
  231. assert unixEnabled, "UNIX support is not present"
  232. p = unix.DatagramPort(address, protocol, maxPacketSize, mode, self)
  233. p.startListening()
  234. return p
  235. def connectUNIXDatagram(
  236. self, address, protocol, maxPacketSize=8192, mode=0o666, bindAddress=None
  237. ):
  238. """
  239. Connects a L{ConnectedDatagramProtocol} instance to a path.
  240. EXPERIMENTAL.
  241. """
  242. assert unixEnabled, "UNIX support is not present"
  243. p = unix.ConnectedDatagramPort(
  244. address, protocol, maxPacketSize, mode, bindAddress, self
  245. )
  246. p.startListening()
  247. return p
  248. # IReactorSocket (no AF_UNIX on Windows)
  249. if unixEnabled:
  250. _supportedAddressFamilies: Sequence[socket.AddressFamily] = (
  251. socket.AF_INET,
  252. socket.AF_INET6,
  253. socket.AF_UNIX,
  254. )
  255. else:
  256. _supportedAddressFamilies = (
  257. socket.AF_INET,
  258. socket.AF_INET6,
  259. )
  260. def adoptStreamPort(self, fileDescriptor, addressFamily, factory):
  261. """
  262. Create a new L{IListeningPort} from an already-initialized socket.
  263. This just dispatches to a suitable port implementation (eg from
  264. L{IReactorTCP}, etc) based on the specified C{addressFamily}.
  265. @see: L{twisted.internet.interfaces.IReactorSocket.adoptStreamPort}
  266. """
  267. if addressFamily not in self._supportedAddressFamilies:
  268. raise error.UnsupportedAddressFamily(addressFamily)
  269. if unixEnabled and addressFamily == socket.AF_UNIX:
  270. p = unix.Port._fromListeningDescriptor(self, fileDescriptor, factory)
  271. else:
  272. p = tcp.Port._fromListeningDescriptor(
  273. self, fileDescriptor, addressFamily, factory
  274. )
  275. p.startListening()
  276. return p
  277. def adoptStreamConnection(self, fileDescriptor, addressFamily, factory):
  278. """
  279. @see:
  280. L{twisted.internet.interfaces.IReactorSocket.adoptStreamConnection}
  281. """
  282. if addressFamily not in self._supportedAddressFamilies:
  283. raise error.UnsupportedAddressFamily(addressFamily)
  284. if unixEnabled and addressFamily == socket.AF_UNIX:
  285. return unix.Server._fromConnectedSocket(fileDescriptor, factory, self)
  286. else:
  287. return tcp.Server._fromConnectedSocket(
  288. fileDescriptor, addressFamily, factory, self
  289. )
  290. def adoptDatagramPort(
  291. self, fileDescriptor, addressFamily, protocol, maxPacketSize=8192
  292. ):
  293. if addressFamily not in (socket.AF_INET, socket.AF_INET6):
  294. raise error.UnsupportedAddressFamily(addressFamily)
  295. p = udp.Port._fromListeningDescriptor(
  296. self, fileDescriptor, addressFamily, protocol, maxPacketSize=maxPacketSize
  297. )
  298. p.startListening()
  299. return p
  300. # IReactorTCP
  301. def listenTCP(self, port, factory, backlog=50, interface=""):
  302. p = tcp.Port(port, factory, backlog, interface, self)
  303. p.startListening()
  304. return p
  305. def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
  306. c = tcp.Connector(host, port, factory, timeout, bindAddress, self)
  307. c.connect()
  308. return c
  309. # IReactorSSL (sometimes, not implemented)
  310. def connectSSL(
  311. self, host, port, factory, contextFactory, timeout=30, bindAddress=None
  312. ):
  313. if tls is not None:
  314. tlsFactory = tls.TLSMemoryBIOFactory(contextFactory, True, factory)
  315. return self.connectTCP(host, port, tlsFactory, timeout, bindAddress)
  316. elif ssl is not None:
  317. c = ssl.Connector(
  318. host, port, factory, contextFactory, timeout, bindAddress, self
  319. )
  320. c.connect()
  321. return c
  322. else:
  323. assert False, "SSL support is not present"
  324. def listenSSL(self, port, factory, contextFactory, backlog=50, interface=""):
  325. if tls is not None:
  326. tlsFactory = tls.TLSMemoryBIOFactory(contextFactory, False, factory)
  327. port = self.listenTCP(port, tlsFactory, backlog, interface)
  328. port._type = "TLS"
  329. return port
  330. elif ssl is not None:
  331. p = ssl.Port(port, factory, contextFactory, backlog, interface, self)
  332. p.startListening()
  333. return p
  334. else:
  335. assert False, "SSL support is not present"
  336. def _removeAll(self, readers, writers):
  337. """
  338. Remove all readers and writers, and list of removed L{IReadDescriptor}s
  339. and L{IWriteDescriptor}s.
  340. Meant for calling from subclasses, to implement removeAll, like::
  341. def removeAll(self):
  342. return self._removeAll(self._reads, self._writes)
  343. where C{self._reads} and C{self._writes} are iterables.
  344. """
  345. removedReaders = set(readers) - self._internalReaders
  346. for reader in removedReaders:
  347. self.removeReader(reader)
  348. removedWriters = set(writers)
  349. for writer in removedWriters:
  350. self.removeWriter(writer)
  351. return list(removedReaders | removedWriters)
  352. class _PollLikeMixin:
  353. """
  354. Mixin for poll-like reactors.
  355. Subclasses must define the following attributes::
  356. - _POLL_DISCONNECTED - Bitmask for events indicating a connection was
  357. lost.
  358. - _POLL_IN - Bitmask for events indicating there is input to read.
  359. - _POLL_OUT - Bitmask for events indicating output can be written.
  360. Must be mixed in to a subclass of PosixReactorBase (for
  361. _disconnectSelectable).
  362. """
  363. def _doReadOrWrite(self, selectable, fd, event):
  364. """
  365. fd is available for read or write, do the work and raise errors if
  366. necessary.
  367. """
  368. why = None
  369. inRead = False
  370. if event & self._POLL_DISCONNECTED and not (event & self._POLL_IN):
  371. # Handle disconnection. But only if we finished processing all
  372. # the pending input.
  373. if fd in self._reads:
  374. # If we were reading from the descriptor then this is a
  375. # clean shutdown. We know there are no read events pending
  376. # because we just checked above. It also might be a
  377. # half-close (which is why we have to keep track of inRead).
  378. inRead = True
  379. why = CONNECTION_DONE
  380. else:
  381. # If we weren't reading, this is an error shutdown of some
  382. # sort.
  383. why = CONNECTION_LOST
  384. else:
  385. # Any non-disconnect event turns into a doRead or a doWrite.
  386. try:
  387. # First check to see if the descriptor is still valid. This
  388. # gives fileno() a chance to raise an exception, too.
  389. # Ideally, disconnection would always be indicated by the
  390. # return value of doRead or doWrite (or an exception from
  391. # one of those methods), but calling fileno here helps make
  392. # buggy applications more transparent.
  393. if selectable.fileno() == -1:
  394. # -1 is sort of a historical Python artifact. Python
  395. # files and sockets used to change their file descriptor
  396. # to -1 when they closed. For the time being, we'll
  397. # continue to support this anyway in case applications
  398. # replicated it, plus abstract.FileDescriptor.fileno
  399. # returns -1. Eventually it'd be good to deprecate this
  400. # case.
  401. why = _NO_FILEDESC
  402. else:
  403. if event & self._POLL_IN:
  404. # Handle a read event.
  405. why = selectable.doRead()
  406. inRead = True
  407. if not why and event & self._POLL_OUT:
  408. # Handle a write event, as long as doRead didn't
  409. # disconnect us.
  410. why = selectable.doWrite()
  411. inRead = False
  412. except BaseException:
  413. # Any exception from application code gets logged and will
  414. # cause us to disconnect the selectable.
  415. why = sys.exc_info()[1]
  416. log.err()
  417. if why:
  418. self._disconnectSelectable(selectable, why, inRead)
  419. @implementer(IReactorFDSet)
  420. class _ContinuousPolling(_PollLikeMixin, _DisconnectSelectableMixin):
  421. """
  422. Schedule reads and writes based on the passage of time, rather than
  423. notification.
  424. This is useful for supporting polling filesystem files, which C{epoll(7)}
  425. does not support.
  426. The implementation uses L{_PollLikeMixin}, which is a bit hacky, but
  427. re-implementing and testing the relevant code yet again is unappealing.
  428. @ivar _reactor: The L{EPollReactor} that is using this instance.
  429. @ivar _loop: A C{LoopingCall} that drives the polling, or L{None}.
  430. @ivar _readers: A C{set} of C{FileDescriptor} objects that should be read
  431. from.
  432. @ivar _writers: A C{set} of C{FileDescriptor} objects that should be
  433. written to.
  434. """
  435. # Attributes for _PollLikeMixin
  436. _POLL_DISCONNECTED = 1
  437. _POLL_IN = 2
  438. _POLL_OUT = 4
  439. def __init__(self, reactor):
  440. self._reactor = reactor
  441. self._loop = None
  442. self._readers = set()
  443. self._writers = set()
  444. def _checkLoop(self):
  445. """
  446. Start or stop a C{LoopingCall} based on whether there are readers and
  447. writers.
  448. """
  449. if self._readers or self._writers:
  450. if self._loop is None:
  451. from twisted.internet.task import _EPSILON, LoopingCall
  452. self._loop = LoopingCall(self.iterate)
  453. self._loop.clock = self._reactor
  454. # LoopingCall seems unhappy with timeout of 0, so use very
  455. # small number:
  456. self._loop.start(_EPSILON, now=False)
  457. elif self._loop:
  458. self._loop.stop()
  459. self._loop = None
  460. def iterate(self):
  461. """
  462. Call C{doRead} and C{doWrite} on all readers and writers respectively.
  463. """
  464. for reader in list(self._readers):
  465. self._doReadOrWrite(reader, reader, self._POLL_IN)
  466. for writer in list(self._writers):
  467. self._doReadOrWrite(writer, writer, self._POLL_OUT)
  468. def addReader(self, reader):
  469. """
  470. Add a C{FileDescriptor} for notification of data available to read.
  471. """
  472. self._readers.add(reader)
  473. self._checkLoop()
  474. def addWriter(self, writer):
  475. """
  476. Add a C{FileDescriptor} for notification of data available to write.
  477. """
  478. self._writers.add(writer)
  479. self._checkLoop()
  480. def removeReader(self, reader):
  481. """
  482. Remove a C{FileDescriptor} from notification of data available to read.
  483. """
  484. try:
  485. self._readers.remove(reader)
  486. except KeyError:
  487. return
  488. self._checkLoop()
  489. def removeWriter(self, writer):
  490. """
  491. Remove a C{FileDescriptor} from notification of data available to
  492. write.
  493. """
  494. try:
  495. self._writers.remove(writer)
  496. except KeyError:
  497. return
  498. self._checkLoop()
  499. def removeAll(self):
  500. """
  501. Remove all readers and writers.
  502. """
  503. result = list(self._readers | self._writers)
  504. # Don't reset to new value, since self.isWriting and .isReading refer
  505. # to the existing instance:
  506. self._readers.clear()
  507. self._writers.clear()
  508. return result
  509. def getReaders(self):
  510. """
  511. Return a list of the readers.
  512. """
  513. return list(self._readers)
  514. def getWriters(self):
  515. """
  516. Return a list of the writers.
  517. """
  518. return list(self._writers)
  519. def isReading(self, fd):
  520. """
  521. Checks if the file descriptor is currently being observed for read
  522. readiness.
  523. @param fd: The file descriptor being checked.
  524. @type fd: L{twisted.internet.abstract.FileDescriptor}
  525. @return: C{True} if the file descriptor is being observed for read
  526. readiness, C{False} otherwise.
  527. @rtype: C{bool}
  528. """
  529. return fd in self._readers
  530. def isWriting(self, fd):
  531. """
  532. Checks if the file descriptor is currently being observed for write
  533. readiness.
  534. @param fd: The file descriptor being checked.
  535. @type fd: L{twisted.internet.abstract.FileDescriptor}
  536. @return: C{True} if the file descriptor is being observed for write
  537. readiness, C{False} otherwise.
  538. @rtype: C{bool}
  539. """
  540. return fd in self._writers
  541. if tls is not None or ssl is not None:
  542. classImplements(PosixReactorBase, IReactorSSL)
  543. if unixEnabled:
  544. classImplements(PosixReactorBase, IReactorUNIX, IReactorUNIXDatagram)
  545. if processEnabled:
  546. classImplements(PosixReactorBase, IReactorProcess)
  547. if getattr(socket, "fromfd", None) is not None:
  548. classImplements(PosixReactorBase, IReactorSocket)
  549. __all__ = ["PosixReactorBase"]