Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tuntap.py 12KB

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