posixbase.py 21 KB

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