posixbase.py 21 KB

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