unix.py 21 KB

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