udp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. UDP support for IOCP reactor
  5. """
  6. import socket, operator, struct, warnings, errno
  7. from zope.interface import implementer
  8. from twisted.internet import defer, address, error, interfaces
  9. from twisted.internet.abstract import isIPAddress, isIPv6Address
  10. from twisted.python import log, failure
  11. from twisted.internet.iocpreactor.const import ERROR_IO_PENDING
  12. from twisted.internet.iocpreactor.const import ERROR_CONNECTION_REFUSED
  13. from twisted.internet.iocpreactor.const import ERROR_PORT_UNREACHABLE
  14. from twisted.internet.iocpreactor.interfaces import IReadWriteHandle
  15. from twisted.internet.iocpreactor import iocpsupport as _iocp, abstract
  16. @implementer(IReadWriteHandle, interfaces.IListeningPort,
  17. interfaces.IUDPTransport, interfaces.ISystemHandle)
  18. class Port(abstract.FileHandle):
  19. """
  20. UDP port, listening for packets.
  21. @ivar addressFamily: L{socket.AF_INET} or L{socket.AF_INET6}, depending on
  22. whether this port is listening on an IPv4 address or an IPv6 address.
  23. """
  24. addressFamily = socket.AF_INET
  25. socketType = socket.SOCK_DGRAM
  26. dynamicReadBuffers = False
  27. # Actual port number being listened on, only set to a non-None
  28. # value when we are actually listening.
  29. _realPortNumber = None
  30. def __init__(self, port, proto, interface='', maxPacketSize=8192,
  31. reactor=None):
  32. """
  33. Initialize with a numeric port to listen on.
  34. """
  35. self.port = port
  36. self.protocol = proto
  37. self.readBufferSize = maxPacketSize
  38. self.interface = interface
  39. self.setLogStr()
  40. self._connectedAddr = None
  41. self._setAddressFamily()
  42. abstract.FileHandle.__init__(self, reactor)
  43. skt = socket.socket(self.addressFamily, self.socketType)
  44. addrLen = _iocp.maxAddrLen(skt.fileno())
  45. self.addressBuffer = bytearray(addrLen)
  46. # WSARecvFrom takes an int
  47. self.addressLengthBuffer = bytearray(struct.calcsize('i'))
  48. def _setAddressFamily(self):
  49. """
  50. Resolve address family for the socket.
  51. """
  52. if isIPv6Address(self.interface):
  53. self.addressFamily = socket.AF_INET6
  54. elif isIPAddress(self.interface):
  55. self.addressFamily = socket.AF_INET
  56. elif self.interface:
  57. raise error.InvalidAddressError(
  58. self.interface, 'not an IPv4 or IPv6 address')
  59. def __repr__(self):
  60. if self._realPortNumber is not None:
  61. return ("<%s on %s>" %
  62. (self.protocol.__class__, self._realPortNumber))
  63. else:
  64. return "<%s not connected>" % (self.protocol.__class__,)
  65. def getHandle(self):
  66. """
  67. Return a socket object.
  68. """
  69. return self.socket
  70. def startListening(self):
  71. """
  72. Create and bind my socket, and begin listening on it.
  73. This is called on unserialization, and must be called after creating a
  74. server to begin listening on the specified port.
  75. """
  76. self._bindSocket()
  77. self._connectToProtocol()
  78. def createSocket(self):
  79. return self.reactor.createSocket(self.addressFamily, self.socketType)
  80. def _bindSocket(self):
  81. try:
  82. skt = self.createSocket()
  83. skt.bind((self.interface, self.port))
  84. except socket.error as le:
  85. raise error.CannotListenError(self.interface, self.port, le)
  86. # Make sure that if we listened on port 0, we update that to
  87. # reflect what the OS actually assigned us.
  88. self._realPortNumber = skt.getsockname()[1]
  89. log.msg("%s starting on %s" % (
  90. self._getLogPrefix(self.protocol), self._realPortNumber))
  91. self.connected = True
  92. self.socket = skt
  93. self.getFileHandle = self.socket.fileno
  94. def _connectToProtocol(self):
  95. self.protocol.makeConnection(self)
  96. self.startReading()
  97. self.reactor.addActiveHandle(self)
  98. def cbRead(self, rc, data, evt):
  99. if self.reading:
  100. self.handleRead(rc, data, evt)
  101. self.doRead()
  102. def handleRead(self, rc, data, evt):
  103. if rc in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
  104. ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
  105. if self._connectedAddr:
  106. self.protocol.connectionRefused()
  107. elif rc:
  108. log.msg("error in recvfrom -- %s (%s)" %
  109. (errno.errorcode.get(rc, 'unknown error'), rc))
  110. else:
  111. try:
  112. self.protocol.datagramReceived(bytes(evt.buff[:data]),
  113. _iocp.makesockaddr(evt.addr_buff))
  114. except:
  115. log.err()
  116. def doRead(self):
  117. evt = _iocp.Event(self.cbRead, self)
  118. evt.buff = buff = self._readBuffers[0]
  119. evt.addr_buff = addr_buff = self.addressBuffer
  120. evt.addr_len_buff = addr_len_buff = self.addressLengthBuffer
  121. rc, data = _iocp.recvfrom(self.getFileHandle(), buff,
  122. addr_buff, addr_len_buff, evt)
  123. if rc and rc != ERROR_IO_PENDING:
  124. self.handleRead(rc, data, evt)
  125. def write(self, datagram, addr=None):
  126. """
  127. Write a datagram.
  128. @param addr: should be a tuple (ip, port), can be None in connected
  129. mode.
  130. """
  131. if self._connectedAddr:
  132. assert addr in (None, self._connectedAddr)
  133. try:
  134. return self.socket.send(datagram)
  135. except socket.error as se:
  136. no = se.args[0]
  137. if no == errno.WSAEINTR:
  138. return self.write(datagram)
  139. elif no == errno.WSAEMSGSIZE:
  140. raise error.MessageLengthError("message too long")
  141. elif no in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
  142. ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
  143. self.protocol.connectionRefused()
  144. else:
  145. raise
  146. else:
  147. assert addr != None
  148. if (not isIPAddress(addr[0]) and not isIPv6Address(addr[0])
  149. and addr[0] != "<broadcast>"):
  150. raise error.InvalidAddressError(
  151. addr[0],
  152. "write() only accepts IP addresses, not hostnames")
  153. if isIPAddress(addr[0]) and self.addressFamily == socket.AF_INET6:
  154. raise error.InvalidAddressError(
  155. addr[0], "IPv6 port write() called with IPv4 address")
  156. if isIPv6Address(addr[0]) and self.addressFamily == socket.AF_INET:
  157. raise error.InvalidAddressError(
  158. addr[0], "IPv4 port write() called with IPv6 address")
  159. try:
  160. return self.socket.sendto(datagram, addr)
  161. except socket.error as se:
  162. no = se.args[0]
  163. if no == errno.WSAEINTR:
  164. return self.write(datagram, addr)
  165. elif no == errno.WSAEMSGSIZE:
  166. raise error.MessageLengthError("message too long")
  167. elif no in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
  168. ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
  169. # in non-connected UDP ECONNREFUSED is platform dependent,
  170. # I think and the info is not necessarily useful.
  171. # Nevertheless maybe we should call connectionRefused? XXX
  172. return
  173. else:
  174. raise
  175. def writeSequence(self, seq, addr):
  176. self.write(b"".join(seq), addr)
  177. def connect(self, host, port):
  178. """
  179. 'Connect' to remote server.
  180. """
  181. if self._connectedAddr:
  182. raise RuntimeError(
  183. "already connected, reconnecting is not currently supported "
  184. "(talk to itamar if you want this)")
  185. if not isIPAddress(host) and not isIPv6Address(host):
  186. raise error.InvalidAddressError(
  187. host, 'not an IPv4 or IPv6 address.')
  188. self._connectedAddr = (host, port)
  189. self.socket.connect((host, port))
  190. def _loseConnection(self):
  191. self.stopReading()
  192. self.reactor.removeActiveHandle(self)
  193. if self.connected: # actually means if we are *listening*
  194. self.reactor.callLater(0, self.connectionLost)
  195. def stopListening(self):
  196. if self.connected:
  197. result = self.d = defer.Deferred()
  198. else:
  199. result = None
  200. self._loseConnection()
  201. return result
  202. def loseConnection(self):
  203. warnings.warn("Please use stopListening() to disconnect port",
  204. DeprecationWarning, stacklevel=2)
  205. self.stopListening()
  206. def connectionLost(self, reason=None):
  207. """
  208. Cleans up my socket.
  209. """
  210. log.msg('(UDP Port %s Closed)' % self._realPortNumber)
  211. self._realPortNumber = None
  212. abstract.FileHandle.connectionLost(self, reason)
  213. self.protocol.doStop()
  214. self.socket.close()
  215. del self.socket
  216. del self.getFileHandle
  217. if hasattr(self, "d"):
  218. self.d.callback(None)
  219. del self.d
  220. def setLogStr(self):
  221. """
  222. Initialize the C{logstr} attribute to be used by C{logPrefix}.
  223. """
  224. logPrefix = self._getLogPrefix(self.protocol)
  225. self.logstr = "%s (UDP)" % logPrefix
  226. def logPrefix(self):
  227. """
  228. Returns the name of my class, to prefix log entries with.
  229. """
  230. return self.logstr
  231. def getHost(self):
  232. """
  233. Return the local address of the UDP connection
  234. @returns: the local address of the UDP connection
  235. @rtype: L{IPv4Address} or L{IPv6Address}
  236. """
  237. addr = self.socket.getsockname()
  238. if self.addressFamily == socket.AF_INET:
  239. return address.IPv4Address('UDP', *addr)
  240. elif self.addressFamily == socket.AF_INET6:
  241. return address.IPv6Address('UDP', *(addr[:2]))
  242. def setBroadcastAllowed(self, enabled):
  243. """
  244. Set whether this port may broadcast. This is disabled by default.
  245. @param enabled: Whether the port may broadcast.
  246. @type enabled: L{bool}
  247. """
  248. self.socket.setsockopt(
  249. socket.SOL_SOCKET, socket.SO_BROADCAST, enabled)
  250. def getBroadcastAllowed(self):
  251. """
  252. Checks if broadcast is currently allowed on this port.
  253. @return: Whether this port may broadcast.
  254. @rtype: L{bool}
  255. """
  256. return operator.truth(
  257. self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST))
  258. class MulticastMixin:
  259. """
  260. Implement multicast functionality.
  261. """
  262. def getOutgoingInterface(self):
  263. i = self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF)
  264. return socket.inet_ntoa(struct.pack("@i", i))
  265. def setOutgoingInterface(self, addr):
  266. """
  267. Returns Deferred of success.
  268. """
  269. return self.reactor.resolve(addr).addCallback(self._setInterface)
  270. def _setInterface(self, addr):
  271. i = socket.inet_aton(addr)
  272. self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i)
  273. return 1
  274. def getLoopbackMode(self):
  275. return self.socket.getsockopt(socket.IPPROTO_IP,
  276. socket.IP_MULTICAST_LOOP)
  277. def setLoopbackMode(self, mode):
  278. mode = struct.pack("b", operator.truth(mode))
  279. self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP,
  280. mode)
  281. def getTTL(self):
  282. return self.socket.getsockopt(socket.IPPROTO_IP,
  283. socket.IP_MULTICAST_TTL)
  284. def setTTL(self, ttl):
  285. ttl = struct.pack("B", ttl)
  286. self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
  287. def joinGroup(self, addr, interface=""):
  288. """
  289. Join a multicast group. Returns Deferred of success.
  290. """
  291. return self.reactor.resolve(addr).addCallback(self._joinAddr1,
  292. interface, 1)
  293. def _joinAddr1(self, addr, interface, join):
  294. return self.reactor.resolve(interface).addCallback(self._joinAddr2,
  295. addr, join)
  296. def _joinAddr2(self, interface, addr, join):
  297. addr = socket.inet_aton(addr)
  298. interface = socket.inet_aton(interface)
  299. if join:
  300. cmd = socket.IP_ADD_MEMBERSHIP
  301. else:
  302. cmd = socket.IP_DROP_MEMBERSHIP
  303. try:
  304. self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
  305. except socket.error as e:
  306. return failure.Failure(error.MulticastJoinError(addr, interface,
  307. *e.args))
  308. def leaveGroup(self, addr, interface=""):
  309. """
  310. Leave multicast group, return Deferred of success.
  311. """
  312. return self.reactor.resolve(addr).addCallback(self._joinAddr1,
  313. interface, 0)
  314. @implementer(interfaces.IMulticastTransport)
  315. class MulticastPort(MulticastMixin, Port):
  316. """
  317. UDP Port that supports multicasting.
  318. """
  319. def __init__(self, port, proto, interface='', maxPacketSize=8192,
  320. reactor=None, listenMultiple=False):
  321. Port.__init__(self, port, proto, interface, maxPacketSize, reactor)
  322. self.listenMultiple = listenMultiple
  323. def createSocket(self):
  324. skt = Port.createSocket(self)
  325. if self.listenMultiple:
  326. skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  327. if hasattr(socket, "SO_REUSEPORT"):
  328. skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  329. return skt