tuntap.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # -*- test-case-name: twisted.pair.test.test_tuntap -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Support for Linux ethernet and IP tunnel devices.
  6. @see: U{https://en.wikipedia.org/wiki/TUN/TAP}
  7. """
  8. import os
  9. import fcntl
  10. import errno
  11. import struct
  12. import warnings
  13. from collections import namedtuple
  14. from constantly import Flags, FlagConstant
  15. from zope.interface import Attribute, Interface, implementer
  16. from twisted.python.util import FancyEqMixin, FancyStrMixin
  17. from incremental import Version
  18. from twisted.python.reflect import fullyQualifiedName
  19. from twisted.python.deprecate import deprecated
  20. from twisted.python import log
  21. from twisted.internet import abstract, error, task, interfaces, defer
  22. from twisted.pair import ethernet, raw
  23. __all__ = [
  24. "TunnelFlags", "TunnelAddress", "TuntapPort",
  25. ]
  26. _IFNAMSIZ = 16
  27. _TUNSETIFF = 0x400454ca
  28. _TUNGETIFF = 0x800454d2
  29. _TUN_KO_PATH = b"/dev/net/tun"
  30. class TunnelFlags(Flags):
  31. """
  32. L{TunnelFlags} defines more flags which are used to configure the behavior
  33. of a tunnel device.
  34. @cvar IFF_TUN: This indicates a I{tun}-type device. This type of tunnel
  35. carries IP datagrams. This flag is mutually exclusive with C{IFF_TAP}.
  36. @cvar IFF_TAP: This indicates a I{tap}-type device. This type of tunnel
  37. carries ethernet frames. This flag is mutually exclusive with C{IFF_TUN}.
  38. @cvar IFF_NO_PI: This indicates the I{protocol information} header will
  39. B{not} be included in data read from the tunnel.
  40. @see: U{https://www.kernel.org/doc/Documentation/networking/tuntap.txt}
  41. """
  42. IFF_TUN = FlagConstant(0x0001)
  43. IFF_TAP = FlagConstant(0x0002)
  44. TUN_FASYNC = FlagConstant(0x0010)
  45. TUN_NOCHECKSUM = FlagConstant(0x0020)
  46. TUN_NO_PI = FlagConstant(0x0040)
  47. TUN_ONE_QUEUE = FlagConstant(0x0080)
  48. TUN_PERSIST = FlagConstant(0x0100)
  49. TUN_VNET_HDR = FlagConstant(0x0200)
  50. IFF_NO_PI = FlagConstant(0x1000)
  51. IFF_ONE_QUEUE = FlagConstant(0x2000)
  52. IFF_VNET_HDR = FlagConstant(0x4000)
  53. IFF_TUN_EXCL = FlagConstant(0x8000)
  54. @implementer(interfaces.IAddress)
  55. class TunnelAddress(FancyStrMixin, FancyEqMixin, object):
  56. """
  57. A L{TunnelAddress} represents the tunnel to which a L{TuntapPort} is bound.
  58. """
  59. compareAttributes = ("_typeValue", "name")
  60. showAttributes = (("type", lambda flag: flag.name), "name")
  61. @property
  62. def _typeValue(self):
  63. """
  64. Return the integer value of the C{type} attribute. Used to produce
  65. correct results in the equality implementation.
  66. """
  67. # Work-around for https://twistedmatrix.com/trac/ticket/6878
  68. return self.type.value
  69. def __init__(self, type, name):
  70. """
  71. @param type: Either L{TunnelFlags.IFF_TUN} or L{TunnelFlags.IFF_TAP},
  72. representing the type of this tunnel.
  73. @param name: The system name of the tunnel.
  74. @type name: L{bytes}
  75. """
  76. self.type = type
  77. self.name = name
  78. def __getitem__(self, index):
  79. """
  80. Deprecated accessor for the tunnel name. Use attributes instead.
  81. """
  82. warnings.warn(
  83. "TunnelAddress.__getitem__ is deprecated since Twisted 14.0.0 "
  84. "Use attributes instead.", category=DeprecationWarning,
  85. stacklevel=2)
  86. return ('TUNTAP', self.name)[index]
  87. class _TunnelDescription(namedtuple("_TunnelDescription", "fileno name")):
  88. """
  89. Describe an existing tunnel.
  90. @ivar fileno: the file descriptor associated with the tunnel
  91. @type fileno: L{int}
  92. @ivar name: the name of the tunnel
  93. @type name: L{bytes}
  94. """
  95. class _IInputOutputSystem(Interface):
  96. """
  97. An interface for performing some basic kinds of I/O (particularly that I/O
  98. which might be useful for L{twisted.pair.tuntap}-using code).
  99. """
  100. O_RDWR = Attribute("@see: L{os.O_RDWR}")
  101. O_NONBLOCK = Attribute("@see: L{os.O_NONBLOCK}")
  102. O_CLOEXEC = Attribute("@see: L{os.O_CLOEXEC}")
  103. def open(filename, flag, mode=0o777):
  104. """
  105. @see: L{os.open}
  106. """
  107. def ioctl(fd, opt, arg=None, mutate_flag=None):
  108. """
  109. @see: L{fcntl.ioctl}
  110. """
  111. def read(fd, limit):
  112. """
  113. @see: L{os.read}
  114. """
  115. def write(fd, data):
  116. """
  117. @see: L{os.write}
  118. """
  119. def close(fd):
  120. """
  121. @see: L{os.close}
  122. """
  123. def sendUDP(datagram, address):
  124. """
  125. Send a datagram to a certain address.
  126. @param datagram: The payload of a UDP datagram to send.
  127. @type datagram: L{bytes}
  128. @param address: The destination to which to send the datagram.
  129. @type address: L{tuple} of (L{bytes}, L{int})
  130. @return: The local address from which the datagram was sent.
  131. @rtype: L{tuple} of (L{bytes}, L{int})
  132. """
  133. def receiveUDP(fileno, host, port):
  134. """
  135. Return a socket which can be used to receive datagrams sent to the
  136. given address.
  137. @param fileno: A file descriptor representing a tunnel device which the
  138. datagram was either sent via or will be received via.
  139. @type fileno: L{int}
  140. @param host: The IPv4 address at which the datagram will be received.
  141. @type host: L{bytes}
  142. @param port: The UDP port number at which the datagram will be
  143. received.
  144. @type port: L{int}
  145. @return: A L{socket.socket} which can be used to receive the specified
  146. datagram.
  147. """
  148. class _RealSystem(object):
  149. """
  150. An interface to the parts of the operating system which L{TuntapPort}
  151. relies on. This is most of an implementation of L{_IInputOutputSystem}.
  152. """
  153. open = staticmethod(os.open)
  154. read = staticmethod(os.read)
  155. write = staticmethod(os.write)
  156. close = staticmethod(os.close)
  157. ioctl = staticmethod(fcntl.ioctl)
  158. O_RDWR = os.O_RDWR
  159. O_NONBLOCK = os.O_NONBLOCK
  160. # Introduced in Python 3.x
  161. # Ubuntu 12.04, /usr/include/x86_64-linux-gnu/bits/fcntl.h
  162. O_CLOEXEC = getattr(os, "O_CLOEXEC", 0o2000000)
  163. @implementer(interfaces.IListeningPort)
  164. class TuntapPort(abstract.FileDescriptor):
  165. """
  166. A Port that reads and writes packets from/to a TUN/TAP-device.
  167. """
  168. maxThroughput = 256 * 1024 # Max bytes we read in one eventloop iteration
  169. def __init__(self, interface, proto, maxPacketSize=8192, reactor=None,
  170. system=None):
  171. if ethernet.IEthernetProtocol.providedBy(proto):
  172. self.ethernet = 1
  173. self._mode = TunnelFlags.IFF_TAP
  174. else:
  175. self.ethernet = 0
  176. self._mode = TunnelFlags.IFF_TUN
  177. assert raw.IRawPacketProtocol.providedBy(proto)
  178. if system is None:
  179. system = _RealSystem()
  180. self._system = system
  181. abstract.FileDescriptor.__init__(self, reactor)
  182. self.interface = interface
  183. self.protocol = proto
  184. self.maxPacketSize = maxPacketSize
  185. logPrefix = self._getLogPrefix(self.protocol)
  186. self.logstr = "%s (%s)" % (logPrefix, self._mode.name)
  187. def __repr__(self):
  188. args = (fullyQualifiedName(self.protocol.__class__),)
  189. if self.connected:
  190. args = args + ("",)
  191. else:
  192. args = args + ("not ",)
  193. args = args + (self._mode.name, self.interface)
  194. return "<%s %slistening on %s/%s>" % args
  195. def startListening(self):
  196. """
  197. Create and bind my socket, and begin listening on it.
  198. This must be called after creating a server to begin listening on the
  199. specified tunnel.
  200. """
  201. self._bindSocket()
  202. self.protocol.makeConnection(self)
  203. self.startReading()
  204. def _openTunnel(self, name, mode):
  205. """
  206. Open the named tunnel using the given mode.
  207. @param name: The name of the tunnel to open.
  208. @type name: L{bytes}
  209. @param mode: Flags from L{TunnelFlags} with exactly one of
  210. L{TunnelFlags.IFF_TUN} or L{TunnelFlags.IFF_TAP} set.
  211. @return: A L{_TunnelDescription} representing the newly opened tunnel.
  212. """
  213. flags = (
  214. self._system.O_RDWR | self._system.O_CLOEXEC |
  215. self._system.O_NONBLOCK)
  216. config = struct.pack("%dsH" % (_IFNAMSIZ,), name, mode.value)
  217. fileno = self._system.open(_TUN_KO_PATH, flags)
  218. result = self._system.ioctl(fileno, _TUNSETIFF, config)
  219. return _TunnelDescription(fileno, result[:_IFNAMSIZ].strip(b'\x00'))
  220. def _bindSocket(self):
  221. """
  222. Open the tunnel.
  223. """
  224. log.msg(
  225. format="%(protocol)s starting on %(interface)s",
  226. protocol=self.protocol.__class__,
  227. interface=self.interface)
  228. try:
  229. fileno, interface = self._openTunnel(
  230. self.interface, self._mode | TunnelFlags.IFF_NO_PI)
  231. except (IOError, OSError) as e:
  232. raise error.CannotListenError(None, self.interface, e)
  233. self.interface = interface
  234. self._fileno = fileno
  235. self.connected = 1
  236. def fileno(self):
  237. return self._fileno
  238. def doRead(self):
  239. """
  240. Called when my socket is ready for reading.
  241. """
  242. read = 0
  243. while read < self.maxThroughput:
  244. try:
  245. data = self._system.read(self._fileno, self.maxPacketSize)
  246. except EnvironmentError as e:
  247. if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EINTR):
  248. return
  249. else:
  250. raise
  251. except:
  252. raise
  253. read += len(data)
  254. # TODO pkt.isPartial()?
  255. try:
  256. self.protocol.datagramReceived(data, partial=0)
  257. except:
  258. cls = fullyQualifiedName(self.protocol.__class__)
  259. log.err(
  260. None,
  261. "Unhandled exception from %s.datagramReceived" % (cls,))
  262. def write(self, datagram):
  263. """
  264. Write the given data as a single datagram.
  265. @param datagram: The data that will make up the complete datagram to be
  266. written.
  267. @type datagram: L{bytes}
  268. """
  269. try:
  270. return self._system.write(self._fileno, datagram)
  271. except IOError as e:
  272. if e.errno == errno.EINTR:
  273. return self.write(datagram)
  274. raise
  275. def writeSequence(self, seq):
  276. """
  277. Write a datagram constructed from a L{list} of L{bytes}.
  278. @param datagram: The data that will make up the complete datagram to be
  279. written.
  280. @type seq: L{list} of L{bytes}
  281. """
  282. self.write(b"".join(seq))
  283. def stopListening(self):
  284. """
  285. Stop accepting connections on this port.
  286. This will shut down my socket and call self.connectionLost().
  287. @return: A L{Deferred} that fires when this port has stopped.
  288. """
  289. self.stopReading()
  290. if self.disconnecting:
  291. return self._stoppedDeferred
  292. elif self.connected:
  293. self._stoppedDeferred = task.deferLater(
  294. self.reactor, 0, self.connectionLost)
  295. self.disconnecting = True
  296. return self._stoppedDeferred
  297. else:
  298. return defer.succeed(None)
  299. def loseConnection(self):
  300. """
  301. Close this tunnel. Use L{TuntapPort.stopListening} instead.
  302. """
  303. self.stopListening().addErrback(log.err)
  304. def connectionLost(self, reason=None):
  305. """
  306. Cleans up my socket.
  307. @param reason: Ignored. Do not use this.
  308. """
  309. log.msg('(Tuntap %s Closed)' % self.interface)
  310. abstract.FileDescriptor.connectionLost(self, reason)
  311. self.protocol.doStop()
  312. self.connected = 0
  313. self._system.close(self._fileno)
  314. self._fileno = -1
  315. def logPrefix(self):
  316. """
  317. Returns the name of my class, to prefix log entries with.
  318. """
  319. return self.logstr
  320. def getHost(self):
  321. """
  322. Get the local address of this L{TuntapPort}.
  323. @return: A L{TunnelAddress} which describes the tunnel device to which
  324. this object is bound.
  325. @rtype: L{TunnelAddress}
  326. """
  327. return TunnelAddress(self._mode, self.interface)
  328. TuntapPort.loseConnection = deprecated(
  329. Version("Twisted", 14, 0, 0),
  330. TuntapPort.stopListening)(TuntapPort.loseConnection)