unix.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. # -*- test-case-name: twisted.test.test_unix,twisted.internet.test.test_unix,twisted.internet.test.test_posixbase -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. UNIX socket support for Twisted.
  6. End users shouldn't use this module directly - use the reactor APIs instead.
  7. Maintainer: Itamar Shtull-Trauring
  8. """
  9. import os
  10. import socket
  11. import stat
  12. import struct
  13. from errno import EAGAIN, ECONNREFUSED, EINTR, EMSGSIZE, ENOBUFS, EWOULDBLOCK
  14. from typing import Optional, Type
  15. from zope.interface import implementedBy, implementer, implementer_only
  16. from twisted.internet import address, base, error, interfaces, main, protocol, tcp, udp
  17. from twisted.internet.abstract import FileDescriptor
  18. from twisted.python import failure, lockfile, log, reflect
  19. from twisted.python.compat import lazyByteSlice
  20. from twisted.python.filepath import _coerceToFilesystemEncoding
  21. from twisted.python.util import untilConcludes
  22. try:
  23. from twisted.python import sendmsg as _sendmsg
  24. except ImportError:
  25. sendmsg = None
  26. else:
  27. sendmsg = _sendmsg
  28. if not hasattr(socket, "AF_UNIX"):
  29. raise ImportError("UNIX sockets not supported on this platform")
  30. def _ancillaryDescriptor(fd):
  31. """
  32. Pack an integer into an ancillary data structure suitable for use with
  33. L{sendmsg.sendmsg}.
  34. """
  35. packed = struct.pack("i", fd)
  36. return [(socket.SOL_SOCKET, sendmsg.SCM_RIGHTS, packed)]
  37. class _SendmsgMixin:
  38. """
  39. Mixin for stream-oriented UNIX transports which uses sendmsg and recvmsg to
  40. offer additional functionality, such as copying file descriptors into other
  41. processes.
  42. @ivar _writeSomeDataBase: The class which provides the basic implementation
  43. of C{writeSomeData}. Ultimately this should be a subclass of
  44. L{twisted.internet.abstract.FileDescriptor}. Subclasses which mix in
  45. L{_SendmsgMixin} must define this.
  46. @ivar _sendmsgQueue: A C{list} of C{int} holding file descriptors which are
  47. currently buffered before being sent.
  48. @ivar _fileDescriptorBufferSize: An C{int} giving the maximum number of file
  49. descriptors to accept and queue for sending before pausing the
  50. registered producer, if there is one.
  51. """
  52. _writeSomeDataBase: Optional[Type[FileDescriptor]] = None
  53. _fileDescriptorBufferSize = 64
  54. def __init__(self):
  55. self._sendmsgQueue = []
  56. def _isSendBufferFull(self):
  57. """
  58. Determine whether the user-space send buffer for this transport is full
  59. or not.
  60. This extends the base determination by adding consideration of how many
  61. file descriptors need to be sent using L{sendmsg.sendmsg}. When there
  62. are more than C{self._fileDescriptorBufferSize}, the buffer is
  63. considered full.
  64. @return: C{True} if it is full, C{False} otherwise.
  65. """
  66. # There must be some bytes in the normal send buffer, checked by
  67. # _writeSomeDataBase._isSendBufferFull, in order to send file
  68. # descriptors from _sendmsgQueue. That means that the buffer will
  69. # eventually be considered full even without this additional logic.
  70. # However, since we send only one byte per file descriptor, having lots
  71. # of elements in _sendmsgQueue incurs more overhead and perhaps slows
  72. # things down. Anyway, try this for now, maybe rethink it later.
  73. return len(
  74. self._sendmsgQueue
  75. ) > self._fileDescriptorBufferSize or self._writeSomeDataBase._isSendBufferFull(
  76. self
  77. )
  78. def sendFileDescriptor(self, fileno):
  79. """
  80. Queue the given file descriptor to be sent and start trying to send it.
  81. """
  82. self._sendmsgQueue.append(fileno)
  83. self._maybePauseProducer()
  84. self.startWriting()
  85. def writeSomeData(self, data):
  86. """
  87. Send as much of C{data} as possible. Also send any pending file
  88. descriptors.
  89. """
  90. # Make it a programming error to send more file descriptors than you
  91. # send regular bytes. Otherwise, due to the limitation mentioned
  92. # below, we could end up with file descriptors left, but no bytes to
  93. # send with them, therefore no way to send those file descriptors.
  94. if len(self._sendmsgQueue) > len(data):
  95. return error.FileDescriptorOverrun()
  96. # If there are file descriptors to send, try sending them first, using
  97. # a little bit of data from the stream-oriented write buffer too. It
  98. # is not possible to send a file descriptor without sending some
  99. # regular data.
  100. index = 0
  101. try:
  102. while index < len(self._sendmsgQueue):
  103. fd = self._sendmsgQueue[index]
  104. try:
  105. untilConcludes(
  106. sendmsg.sendmsg,
  107. self.socket,
  108. data[index : index + 1],
  109. _ancillaryDescriptor(fd),
  110. )
  111. except OSError as se:
  112. if se.args[0] in (EWOULDBLOCK, ENOBUFS):
  113. return index
  114. else:
  115. return main.CONNECTION_LOST
  116. else:
  117. index += 1
  118. finally:
  119. del self._sendmsgQueue[:index]
  120. # Hand the remaining data to the base implementation. Avoid slicing in
  121. # favor of a buffer, in case that happens to be any faster.
  122. limitedData = lazyByteSlice(data, index)
  123. result = self._writeSomeDataBase.writeSomeData(self, limitedData)
  124. try:
  125. return index + result
  126. except TypeError:
  127. return result
  128. def doRead(self):
  129. """
  130. Calls {IProtocol.dataReceived} with all available data and
  131. L{IFileDescriptorReceiver.fileDescriptorReceived} once for each
  132. received file descriptor in ancillary data.
  133. This reads up to C{self.bufferSize} bytes of data from its socket, then
  134. dispatches the data to protocol callbacks to be handled. If the
  135. connection is not lost through an error in the underlying recvmsg(),
  136. this function will return the result of the dataReceived call.
  137. """
  138. try:
  139. data, ancillary, flags = untilConcludes(
  140. sendmsg.recvmsg, self.socket, self.bufferSize
  141. )
  142. except OSError as se:
  143. if se.args[0] == EWOULDBLOCK:
  144. return
  145. else:
  146. return main.CONNECTION_LOST
  147. for cmsgLevel, cmsgType, cmsgData in ancillary:
  148. if cmsgLevel == socket.SOL_SOCKET and cmsgType == sendmsg.SCM_RIGHTS:
  149. self._ancillaryLevelSOLSOCKETTypeSCMRIGHTS(cmsgData)
  150. else:
  151. log.msg(
  152. format=(
  153. "%(protocolName)s (on %(hostAddress)r) "
  154. "received unsupported ancillary data "
  155. "(level=%(cmsgLevel)r, type=%(cmsgType)r) "
  156. "from %(peerAddress)r."
  157. ),
  158. hostAddress=self.getHost(),
  159. peerAddress=self.getPeer(),
  160. protocolName=self._getLogPrefix(self.protocol),
  161. cmsgLevel=cmsgLevel,
  162. cmsgType=cmsgType,
  163. )
  164. return self._dataReceived(data)
  165. def _ancillaryLevelSOLSOCKETTypeSCMRIGHTS(self, cmsgData):
  166. """
  167. Processes ancillary data with level SOL_SOCKET and type SCM_RIGHTS,
  168. indicating that the ancillary data payload holds file descriptors.
  169. Calls L{IFileDescriptorReceiver.fileDescriptorReceived} once for each
  170. received file descriptor or logs a message if the protocol does not
  171. implement L{IFileDescriptorReceiver}.
  172. @param cmsgData: Ancillary data payload.
  173. @type cmsgData: L{bytes}
  174. """
  175. fdCount = len(cmsgData) // 4
  176. fds = struct.unpack("i" * fdCount, cmsgData)
  177. if interfaces.IFileDescriptorReceiver.providedBy(self.protocol):
  178. for fd in fds:
  179. self.protocol.fileDescriptorReceived(fd)
  180. else:
  181. log.msg(
  182. format=(
  183. "%(protocolName)s (on %(hostAddress)r) does not "
  184. "provide IFileDescriptorReceiver; closing file "
  185. "descriptor received (from %(peerAddress)r)."
  186. ),
  187. hostAddress=self.getHost(),
  188. peerAddress=self.getPeer(),
  189. protocolName=self._getLogPrefix(self.protocol),
  190. )
  191. for fd in fds:
  192. os.close(fd)
  193. class _UnsupportedSendmsgMixin:
  194. """
  195. Behaviorless placeholder used when C{twisted.python.sendmsg} is not
  196. available, preventing L{IUNIXTransport} from being supported.
  197. """
  198. if sendmsg:
  199. _SendmsgMixin = _SendmsgMixin
  200. else:
  201. _SendmsgMixin = _UnsupportedSendmsgMixin # type: ignore[assignment,misc]
  202. @implementer(interfaces.IUNIXTransport)
  203. class Server(_SendmsgMixin, tcp.Server):
  204. _writeSomeDataBase = tcp.Server
  205. def __init__(self, sock, protocol, client, server, sessionno, reactor):
  206. _SendmsgMixin.__init__(self)
  207. tcp.Server.__init__(
  208. self, sock, protocol, (client, None), server, sessionno, reactor
  209. )
  210. @classmethod
  211. def _fromConnectedSocket(cls, fileDescriptor, factory, reactor):
  212. """
  213. Create a new L{Server} based on an existing connected I{SOCK_STREAM}
  214. socket.
  215. Arguments are the same as to L{Server.__init__}, except where noted.
  216. @param fileDescriptor: An integer file descriptor associated with a
  217. connected socket. The socket must be in non-blocking mode. Any
  218. additional attributes desired, such as I{FD_CLOEXEC}, must also be
  219. set already.
  220. @return: A new instance of C{cls} wrapping the socket given by
  221. C{fileDescriptor}.
  222. """
  223. skt = socket.fromfd(fileDescriptor, socket.AF_UNIX, socket.SOCK_STREAM)
  224. protocolAddr = address.UNIXAddress(skt.getsockname())
  225. proto = factory.buildProtocol(protocolAddr)
  226. if proto is None:
  227. skt.close()
  228. return
  229. # FIXME: is this a suitable sessionno?
  230. sessionno = 0
  231. self = cls(skt, proto, skt.getpeername(), None, sessionno, reactor)
  232. self.repstr = "<{} #{} on {}>".format(
  233. self.protocol.__class__.__name__,
  234. self.sessionno,
  235. skt.getsockname(),
  236. )
  237. self.logstr = "{},{},{}".format(
  238. self.protocol.__class__.__name__,
  239. self.sessionno,
  240. skt.getsockname(),
  241. )
  242. proto.makeConnection(self)
  243. return self
  244. def getHost(self):
  245. return address.UNIXAddress(self.socket.getsockname())
  246. def getPeer(self):
  247. return address.UNIXAddress(self.hostname or None)
  248. def _inFilesystemNamespace(path):
  249. """
  250. Determine whether the given unix socket path is in a filesystem namespace.
  251. While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and
  252. above support PF_UNIX sockets in an "abstract namespace" that does not
  253. correspond to any path. This function returns C{True} if the given socket
  254. path is stored in the filesystem and C{False} if the path is in this
  255. abstract namespace.
  256. """
  257. return path[:1] not in (b"\0", "\0")
  258. class _UNIXPort:
  259. def getHost(self):
  260. """
  261. Returns a UNIXAddress.
  262. This indicates the server's address.
  263. """
  264. return address.UNIXAddress(self.socket.getsockname())
  265. class Port(_UNIXPort, tcp.Port):
  266. addressFamily = socket.AF_UNIX
  267. socketType = socket.SOCK_STREAM
  268. transport = Server
  269. lockFile = None
  270. def __init__(
  271. self, fileName, factory, backlog=50, mode=0o666, reactor=None, wantPID=0
  272. ):
  273. tcp.Port.__init__(
  274. self, self._buildAddr(fileName).name, factory, backlog, reactor=reactor
  275. )
  276. self.mode = mode
  277. self.wantPID = wantPID
  278. self._preexistingSocket = None
  279. @classmethod
  280. def _fromListeningDescriptor(cls, reactor, fd, factory):
  281. """
  282. Create a new L{Port} based on an existing listening I{SOCK_STREAM}
  283. socket.
  284. Arguments are the same as to L{Port.__init__}, except where noted.
  285. @param fd: An integer file descriptor associated with a listening
  286. socket. The socket must be in non-blocking mode. Any additional
  287. attributes desired, such as I{FD_CLOEXEC}, must also be set already.
  288. @return: A new instance of C{cls} wrapping the socket given by C{fd}.
  289. """
  290. port = socket.fromfd(fd, cls.addressFamily, cls.socketType)
  291. self = cls(port.getsockname(), factory, reactor=reactor)
  292. self._preexistingSocket = port
  293. return self
  294. def __repr__(self) -> str:
  295. factoryName = reflect.qual(self.factory.__class__)
  296. if hasattr(self, "socket"):
  297. return "<{} on {!r}>".format(
  298. factoryName,
  299. _coerceToFilesystemEncoding("", self.port),
  300. )
  301. else:
  302. return f"<{factoryName} (not listening)>"
  303. def _buildAddr(self, name):
  304. return address.UNIXAddress(name)
  305. def startListening(self):
  306. """
  307. Create and bind my socket, and begin listening on it.
  308. This is called on unserialization, and must be called after creating a
  309. server to begin listening on the specified port.
  310. """
  311. tcp._reservedFD.reserve()
  312. log.msg(
  313. "%s starting on %r"
  314. % (
  315. self._getLogPrefix(self.factory),
  316. _coerceToFilesystemEncoding("", self.port),
  317. )
  318. )
  319. if self.wantPID:
  320. self.lockFile = lockfile.FilesystemLock(self.port + b".lock")
  321. if not self.lockFile.lock():
  322. raise error.CannotListenError(None, self.port, "Cannot acquire lock")
  323. else:
  324. if not self.lockFile.clean:
  325. try:
  326. # This is a best-attempt at cleaning up
  327. # left-over unix sockets on the filesystem.
  328. # If it fails, there's not much else we can
  329. # do. The bind() below will fail with an
  330. # exception that actually propagates.
  331. if stat.S_ISSOCK(os.stat(self.port).st_mode):
  332. os.remove(self.port)
  333. except BaseException:
  334. pass
  335. self.factory.doStart()
  336. try:
  337. if self._preexistingSocket is not None:
  338. skt = self._preexistingSocket
  339. self._preexistingSocket = None
  340. else:
  341. skt = self.createInternetSocket()
  342. skt.bind(self.port)
  343. except OSError as le:
  344. raise error.CannotListenError(None, self.port, le)
  345. else:
  346. if _inFilesystemNamespace(self.port):
  347. # Make the socket readable and writable to the world.
  348. os.chmod(self.port, self.mode)
  349. skt.listen(self.backlog)
  350. self.connected = True
  351. self.socket = skt
  352. self.fileno = self.socket.fileno
  353. self.numberAccepts = 100
  354. self.startReading()
  355. def _logConnectionLostMsg(self):
  356. """
  357. Log message for closing socket
  358. """
  359. log.msg(
  360. "(UNIX Port %s Closed)"
  361. % (
  362. _coerceToFilesystemEncoding(
  363. "",
  364. self.port,
  365. )
  366. )
  367. )
  368. def connectionLost(self, reason):
  369. if _inFilesystemNamespace(self.port):
  370. os.unlink(self.port)
  371. if self.lockFile is not None:
  372. self.lockFile.unlock()
  373. tcp.Port.connectionLost(self, reason)
  374. @implementer(interfaces.IUNIXTransport)
  375. class Client(_SendmsgMixin, tcp.BaseClient):
  376. """A client for Unix sockets."""
  377. addressFamily = socket.AF_UNIX
  378. socketType = socket.SOCK_STREAM
  379. _writeSomeDataBase = tcp.BaseClient
  380. def __init__(self, filename, connector, reactor=None, checkPID=0):
  381. _SendmsgMixin.__init__(self)
  382. # Normalise the filename using UNIXAddress
  383. filename = address.UNIXAddress(filename).name
  384. self.connector = connector
  385. self.realAddress = self.addr = filename
  386. if checkPID and not lockfile.isLocked(filename + b".lock"):
  387. self._finishInit(None, None, error.BadFileError(filename), reactor)
  388. self._finishInit(self.doConnect, self.createInternetSocket(), None, reactor)
  389. def getPeer(self):
  390. return address.UNIXAddress(self.addr)
  391. def getHost(self):
  392. return address.UNIXAddress(None)
  393. class Connector(base.BaseConnector):
  394. def __init__(self, address, factory, timeout, reactor, checkPID):
  395. base.BaseConnector.__init__(self, factory, timeout, reactor)
  396. self.address = address
  397. self.checkPID = checkPID
  398. def _makeTransport(self):
  399. return Client(self.address, self, self.reactor, self.checkPID)
  400. def getDestination(self):
  401. return address.UNIXAddress(self.address)
  402. @implementer(interfaces.IUNIXDatagramTransport)
  403. class DatagramPort(_UNIXPort, udp.Port):
  404. """
  405. Datagram UNIX port, listening for packets.
  406. """
  407. addressFamily = socket.AF_UNIX
  408. def __init__(self, addr, proto, maxPacketSize=8192, mode=0o666, reactor=None):
  409. """Initialize with address to listen on."""
  410. udp.Port.__init__(
  411. self, addr, proto, maxPacketSize=maxPacketSize, reactor=reactor
  412. )
  413. self.mode = mode
  414. def __repr__(self) -> str:
  415. protocolName = reflect.qual(
  416. self.protocol.__class__,
  417. )
  418. if hasattr(self, "socket"):
  419. return f"<{protocolName} on {self.port!r}>"
  420. else:
  421. return f"<{protocolName} (not listening)>"
  422. def _bindSocket(self):
  423. log.msg(f"{self.protocol.__class__} starting on {repr(self.port)}")
  424. try:
  425. skt = self.createInternetSocket() # XXX: haha misnamed method
  426. if self.port:
  427. skt.bind(self.port)
  428. except OSError as le:
  429. raise error.CannotListenError(None, self.port, le)
  430. if self.port and _inFilesystemNamespace(self.port):
  431. # Make the socket readable and writable to the world.
  432. os.chmod(self.port, self.mode)
  433. self.connected = 1
  434. self.socket = skt
  435. self.fileno = self.socket.fileno
  436. def write(self, datagram, address):
  437. """Write a datagram."""
  438. try:
  439. return self.socket.sendto(datagram, address)
  440. except OSError as se:
  441. no = se.args[0]
  442. if no == EINTR:
  443. return self.write(datagram, address)
  444. elif no == EMSGSIZE:
  445. raise error.MessageLengthError("message too long")
  446. elif no == EAGAIN:
  447. # oh, well, drop the data. The only difference from UDP
  448. # is that UDP won't ever notice.
  449. # TODO: add TCP-like buffering
  450. pass
  451. else:
  452. raise
  453. def connectionLost(self, reason=None):
  454. """Cleans up my socket."""
  455. log.msg("(Port %s Closed)" % repr(self.port))
  456. base.BasePort.connectionLost(self, reason)
  457. if hasattr(self, "protocol"):
  458. # we won't have attribute in ConnectedPort, in cases
  459. # where there was an error in connection process
  460. self.protocol.doStop()
  461. self.connected = 0
  462. self.socket.close()
  463. del self.socket
  464. del self.fileno
  465. if hasattr(self, "d"):
  466. self.d.callback(None)
  467. del self.d
  468. def setLogStr(self):
  469. self.logstr = reflect.qual(self.protocol.__class__) + " (UDP)"
  470. @implementer_only(
  471. interfaces.IUNIXDatagramConnectedTransport, *(implementedBy(base.BasePort))
  472. )
  473. class ConnectedDatagramPort(DatagramPort):
  474. """
  475. A connected datagram UNIX socket.
  476. """
  477. def __init__(
  478. self,
  479. addr,
  480. proto,
  481. maxPacketSize=8192,
  482. mode=0o666,
  483. bindAddress=None,
  484. reactor=None,
  485. ):
  486. assert isinstance(proto, protocol.ConnectedDatagramProtocol)
  487. DatagramPort.__init__(self, bindAddress, proto, maxPacketSize, mode, reactor)
  488. self.remoteaddr = addr
  489. def startListening(self):
  490. try:
  491. self._bindSocket()
  492. self.socket.connect(self.remoteaddr)
  493. self._connectToProtocol()
  494. except BaseException:
  495. self.connectionFailed(failure.Failure())
  496. def connectionFailed(self, reason):
  497. """
  498. Called when a connection fails. Stop listening on the socket.
  499. @type reason: L{Failure}
  500. @param reason: Why the connection failed.
  501. """
  502. self.stopListening()
  503. self.protocol.connectionFailed(reason)
  504. del self.protocol
  505. def doRead(self):
  506. """
  507. Called when my socket is ready for reading.
  508. """
  509. read = 0
  510. while read < self.maxThroughput:
  511. try:
  512. data, addr = self.socket.recvfrom(self.maxPacketSize)
  513. read += len(data)
  514. self.protocol.datagramReceived(data)
  515. except OSError as se:
  516. no = se.args[0]
  517. if no in (EAGAIN, EINTR, EWOULDBLOCK):
  518. return
  519. if no == ECONNREFUSED:
  520. self.protocol.connectionRefused()
  521. else:
  522. raise
  523. except BaseException:
  524. log.deferr()
  525. def write(self, data):
  526. """
  527. Write a datagram.
  528. """
  529. try:
  530. return self.socket.send(data)
  531. except OSError as se:
  532. no = se.args[0]
  533. if no == EINTR:
  534. return self.write(data)
  535. elif no == EMSGSIZE:
  536. raise error.MessageLengthError("message too long")
  537. elif no == ECONNREFUSED:
  538. self.protocol.connectionRefused()
  539. elif no == EAGAIN:
  540. # oh, well, drop the data. The only difference from UDP
  541. # is that UDP won't ever notice.
  542. # TODO: add TCP-like buffering
  543. pass
  544. else:
  545. raise
  546. def getPeer(self):
  547. return address.UNIXAddress(self.remoteaddr)