unix.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. def getHost(self):
  197. return address.UNIXAddress(self.socket.getsockname())
  198. def getPeer(self):
  199. return address.UNIXAddress(self.hostname or None)
  200. def _inFilesystemNamespace(path):
  201. """
  202. Determine whether the given unix socket path is in a filesystem namespace.
  203. While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and
  204. above support PF_UNIX sockets in an "abstract namespace" that does not
  205. correspond to any path. This function returns C{True} if the given socket
  206. path is stored in the filesystem and C{False} if the path is in this
  207. abstract namespace.
  208. """
  209. return path[:1] not in (b"\0", u"\0")
  210. class _UNIXPort(object):
  211. def getHost(self):
  212. """
  213. Returns a UNIXAddress.
  214. This indicates the server's address.
  215. """
  216. return address.UNIXAddress(self.socket.getsockname())
  217. class Port(_UNIXPort, tcp.Port):
  218. addressFamily = socket.AF_UNIX
  219. socketType = socket.SOCK_STREAM
  220. transport = Server
  221. lockFile = None
  222. def __init__(self, fileName, factory, backlog=50, mode=0o666, reactor=None,
  223. wantPID = 0):
  224. tcp.Port.__init__(self, self._buildAddr(fileName).name, factory,
  225. backlog, reactor=reactor)
  226. self.mode = mode
  227. self.wantPID = wantPID
  228. def __repr__(self):
  229. factoryName = reflect.qual(self.factory.__class__)
  230. if hasattr(self, 'socket'):
  231. return '<%s on %r>' % (
  232. factoryName, _coerceToFilesystemEncoding('', self.port))
  233. else:
  234. return '<%s (not listening)>' % (factoryName,)
  235. def _buildAddr(self, name):
  236. return address.UNIXAddress(name)
  237. def startListening(self):
  238. """
  239. Create and bind my socket, and begin listening on it.
  240. This is called on unserialization, and must be called after creating a
  241. server to begin listening on the specified port.
  242. """
  243. log.msg("%s starting on %r" % (
  244. self._getLogPrefix(self.factory),
  245. _coerceToFilesystemEncoding('', self.port)))
  246. if self.wantPID:
  247. self.lockFile = lockfile.FilesystemLock(self.port + b".lock")
  248. if not self.lockFile.lock():
  249. raise error.CannotListenError(None, self.port,
  250. "Cannot acquire lock")
  251. else:
  252. if not self.lockFile.clean:
  253. try:
  254. # This is a best-attempt at cleaning up
  255. # left-over unix sockets on the filesystem.
  256. # If it fails, there's not much else we can
  257. # do. The bind() below will fail with an
  258. # exception that actually propagates.
  259. if stat.S_ISSOCK(os.stat(self.port).st_mode):
  260. os.remove(self.port)
  261. except:
  262. pass
  263. self.factory.doStart()
  264. try:
  265. skt = self.createInternetSocket()
  266. skt.bind(self.port)
  267. except socket.error as le:
  268. raise error.CannotListenError(None, self.port, le)
  269. else:
  270. if _inFilesystemNamespace(self.port):
  271. # Make the socket readable and writable to the world.
  272. os.chmod(self.port, self.mode)
  273. skt.listen(self.backlog)
  274. self.connected = True
  275. self.socket = skt
  276. self.fileno = self.socket.fileno
  277. self.numberAccepts = 100
  278. self.startReading()
  279. def _logConnectionLostMsg(self):
  280. """
  281. Log message for closing socket
  282. """
  283. log.msg('(UNIX Port %s Closed)' % (
  284. _coerceToFilesystemEncoding('', self.port,)))
  285. def connectionLost(self, reason):
  286. if _inFilesystemNamespace(self.port):
  287. os.unlink(self.port)
  288. if self.lockFile is not None:
  289. self.lockFile.unlock()
  290. tcp.Port.connectionLost(self, reason)
  291. class Client(_SendmsgMixin, tcp.BaseClient):
  292. """A client for Unix sockets."""
  293. addressFamily = socket.AF_UNIX
  294. socketType = socket.SOCK_STREAM
  295. _writeSomeDataBase = tcp.BaseClient
  296. def __init__(self, filename, connector, reactor=None, checkPID = 0):
  297. _SendmsgMixin.__init__(self)
  298. # Normalise the filename using UNIXAddress
  299. filename = address.UNIXAddress(filename).name
  300. self.connector = connector
  301. self.realAddress = self.addr = filename
  302. if checkPID and not lockfile.isLocked(filename + b".lock"):
  303. self._finishInit(None, None, error.BadFileError(filename), reactor)
  304. self._finishInit(self.doConnect, self.createInternetSocket(),
  305. None, reactor)
  306. def getPeer(self):
  307. return address.UNIXAddress(self.addr)
  308. def getHost(self):
  309. return address.UNIXAddress(None)
  310. class Connector(base.BaseConnector):
  311. def __init__(self, address, factory, timeout, reactor, checkPID):
  312. base.BaseConnector.__init__(self, factory, timeout, reactor)
  313. self.address = address
  314. self.checkPID = checkPID
  315. def _makeTransport(self):
  316. return Client(self.address, self, self.reactor, self.checkPID)
  317. def getDestination(self):
  318. return address.UNIXAddress(self.address)
  319. @implementer(interfaces.IUNIXDatagramTransport)
  320. class DatagramPort(_UNIXPort, udp.Port):
  321. """
  322. Datagram UNIX port, listening for packets.
  323. """
  324. addressFamily = socket.AF_UNIX
  325. def __init__(self, addr, proto, maxPacketSize=8192, mode=0o666, reactor=None):
  326. """Initialize with address to listen on.
  327. """
  328. udp.Port.__init__(self, addr, proto, maxPacketSize=maxPacketSize, reactor=reactor)
  329. self.mode = mode
  330. def __repr__(self):
  331. protocolName = reflect.qual(self.protocol.__class__,)
  332. if hasattr(self, 'socket'):
  333. return '<%s on %r>' % (protocolName, self.port)
  334. else:
  335. return '<%s (not listening)>' % (protocolName,)
  336. def _bindSocket(self):
  337. log.msg("%s starting on %s"%(self.protocol.__class__, repr(self.port)))
  338. try:
  339. skt = self.createInternetSocket() # XXX: haha misnamed method
  340. if self.port:
  341. skt.bind(self.port)
  342. except socket.error as le:
  343. raise error.CannotListenError(None, self.port, le)
  344. if self.port and _inFilesystemNamespace(self.port):
  345. # Make the socket readable and writable to the world.
  346. os.chmod(self.port, self.mode)
  347. self.connected = 1
  348. self.socket = skt
  349. self.fileno = self.socket.fileno
  350. def write(self, datagram, address):
  351. """Write a datagram."""
  352. try:
  353. return self.socket.sendto(datagram, address)
  354. except socket.error as se:
  355. no = se.args[0]
  356. if no == EINTR:
  357. return self.write(datagram, address)
  358. elif no == EMSGSIZE:
  359. raise error.MessageLengthError("message too long")
  360. elif no == EAGAIN:
  361. # oh, well, drop the data. The only difference from UDP
  362. # is that UDP won't ever notice.
  363. # TODO: add TCP-like buffering
  364. pass
  365. else:
  366. raise
  367. def connectionLost(self, reason=None):
  368. """Cleans up my socket.
  369. """
  370. log.msg('(Port %s Closed)' % repr(self.port))
  371. base.BasePort.connectionLost(self, reason)
  372. if hasattr(self, "protocol"):
  373. # we won't have attribute in ConnectedPort, in cases
  374. # where there was an error in connection process
  375. self.protocol.doStop()
  376. self.connected = 0
  377. self.socket.close()
  378. del self.socket
  379. del self.fileno
  380. if hasattr(self, "d"):
  381. self.d.callback(None)
  382. del self.d
  383. def setLogStr(self):
  384. self.logstr = reflect.qual(self.protocol.__class__) + " (UDP)"
  385. @implementer_only(interfaces.IUNIXDatagramConnectedTransport,
  386. *(implementedBy(base.BasePort)))
  387. class ConnectedDatagramPort(DatagramPort):
  388. """
  389. A connected datagram UNIX socket.
  390. """
  391. def __init__(self, addr, proto, maxPacketSize=8192, mode=0o666,
  392. bindAddress=None, reactor=None):
  393. assert isinstance(proto, protocol.ConnectedDatagramProtocol)
  394. DatagramPort.__init__(self, bindAddress, proto, maxPacketSize, mode,
  395. reactor)
  396. self.remoteaddr = addr
  397. def startListening(self):
  398. try:
  399. self._bindSocket()
  400. self.socket.connect(self.remoteaddr)
  401. self._connectToProtocol()
  402. except:
  403. self.connectionFailed(failure.Failure())
  404. def connectionFailed(self, reason):
  405. """
  406. Called when a connection fails. Stop listening on the socket.
  407. @type reason: L{Failure}
  408. @param reason: Why the connection failed.
  409. """
  410. self.stopListening()
  411. self.protocol.connectionFailed(reason)
  412. del self.protocol
  413. def doRead(self):
  414. """
  415. Called when my socket is ready for reading.
  416. """
  417. read = 0
  418. while read < self.maxThroughput:
  419. try:
  420. data, addr = self.socket.recvfrom(self.maxPacketSize)
  421. read += len(data)
  422. self.protocol.datagramReceived(data)
  423. except socket.error as se:
  424. no = se.args[0]
  425. if no in (EAGAIN, EINTR, EWOULDBLOCK):
  426. return
  427. if no == ECONNREFUSED:
  428. self.protocol.connectionRefused()
  429. else:
  430. raise
  431. except:
  432. log.deferr()
  433. def write(self, data):
  434. """
  435. Write a datagram.
  436. """
  437. try:
  438. return self.socket.send(data)
  439. except socket.error as se:
  440. no = se.args[0]
  441. if no == EINTR:
  442. return self.write(data)
  443. elif no == EMSGSIZE:
  444. raise error.MessageLengthError("message too long")
  445. elif no == ECONNREFUSED:
  446. self.protocol.connectionRefused()
  447. elif no == EAGAIN:
  448. # oh, well, drop the data. The only difference from UDP
  449. # is that UDP won't ever notice.
  450. # TODO: add TCP-like buffering
  451. pass
  452. else:
  453. raise
  454. def getPeer(self):
  455. return address.UNIXAddress(self.remoteaddr)