From 1a239a835c0de9f0b548704b52abe7d1dee0a046 Mon Sep 17 00:00:00 2001 From: Vincent Michel Date: Thu, 16 Feb 2017 12:06:07 +0100 Subject: [PATCH] Do not connect UDP sockets when broadcast is allowed This fixes issue #480. The _SelectorDatagramTransport.sendto method has to be modified so _sock.sendto is used in all cases (since there is no proper way to tell if the socket is connected or not). Cound that be an issue for connected sockets? --- asyncio/base_events.py | 3 ++- asyncio/selector_events.py | 18 +++++++----------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/asyncio/base_events.py b/asyncio/base_events.py index 50153f8d..10352bd2 100644 --- a/asyncio/base_events.py +++ b/asyncio/base_events.py @@ -916,7 +916,8 @@ def create_datagram_endpoint(self, protocol_factory, if local_addr: sock.bind(local_address) if remote_addr: - yield from self.sock_connect(sock, remote_address) + if not allow_broadcast: + yield from self.sock_connect(sock, remote_address) r_addr = remote_address except OSError as exc: if sock is not None: diff --git a/asyncio/selector_events.py b/asyncio/selector_events.py index 12d357b5..54b40f76 100644 --- a/asyncio/selector_events.py +++ b/asyncio/selector_events.py @@ -1083,9 +1083,11 @@ def sendto(self, data, addr=None): if not data: return - if self._address and addr not in (None, self._address): - raise ValueError('Invalid address: must be None or %s' % - (self._address,)) + if self._address: + if addr not in (None, self._address): + raise ValueError( + 'Invalid address: must be None or %s' % (self._address,)) + addr = self._address if self._conn_lost and self._address: if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES: @@ -1096,10 +1098,7 @@ def sendto(self, data, addr=None): if not self._buffer: # Attempt to send it right away first. try: - if self._address: - self._sock.send(data) - else: - self._sock.sendto(data, addr) + self._sock.sendto(data, addr) return except (BlockingIOError, InterruptedError): self._loop._add_writer(self._sock_fd, self._sendto_ready) @@ -1119,10 +1118,7 @@ def _sendto_ready(self): while self._buffer: data, addr = self._buffer.popleft() try: - if self._address: - self._sock.send(data) - else: - self._sock.sendto(data, addr) + self._sock.sendto(data, addr) except (BlockingIOError, InterruptedError): self._buffer.appendleft((data, addr)) # Try again later. break