Python errno.EWOULDBLOCK Examples

The following are 30 code examples of errno.EWOULDBLOCK(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module errno , or try the search function .
Example #1
Source File: iostream.py    From teleport with Apache License 2.0 6 votes vote down vote up
def write_to_fd(self, data: memoryview) -> int:
        try:
            return self.socket.send(data)  # type: ignore
        except ssl.SSLError as e:
            if e.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if
                # the socket is not writeable; we need to transform this into
                # an EWOULDBLOCK socket.error or a zero return value,
                # either of which will be recognized by the caller of this
                # method. Prior to Python 3.5, an unwriteable socket would
                # simply return 0 bytes written.
                return 0
            raise
        finally:
            # Avoid keeping to data, which can be a memoryview.
            # See https://github.com/tornadoweb/tornado/pull/2008
            del data 
Example #2
Source File: SimpleWebSocketServer.py    From BiblioPixel with MIT License 6 votes vote down vote up
def _sendBuffer(self, buff):
        size = len(buff)
        tosend = size
        already_sent = 0

        while tosend > 0:
            try:
                # i should be able to send a bytearray
                sent = self.client.send(buff[already_sent:])
                if sent == 0:
                    raise RuntimeError('socket connection broken')

                already_sent += sent
                tosend -= sent

            except socket.error as e:
                # if we have full buffers then wait for them to drain and try
                # again
                if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]:
                    return buff[already_sent:]
                else:
                    raise e

        return None 
Example #3
Source File: monitor.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def _receive_device(self):
        """Receive a single device from the monitor.

        Return the received :class:`Device`, or ``None`` if no device could be
        received.

        """
        while True:
            try:
                device_p = self._libudev.udev_monitor_receive_device(self)
                return Device(self.context, device_p) if device_p else None
            except EnvironmentError as error:
                if error.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
                    # No data available
                    return None
                elif error.errno == errno.EINTR:
                    # Try again if our system call was interrupted
                    continue
                else:
                    raise 
Example #4
Source File: sync.py    From jbox with MIT License 6 votes vote down vote up
def run_for_multiple(self, timeout):
        while self.alive:
            self.notify()

            try:
                ready = self.wait(timeout)
            except StopWaiting:
                return

            if ready is not None:
                for listener in ready:
                    if listener == self.PIPE[0]:
                        continue

                    try:
                        self.accept(listener)
                    except EnvironmentError as e:
                        if e.errno not in (errno.EAGAIN, errno.ECONNABORTED,
                                errno.EWOULDBLOCK):
                            raise

            if not self.is_parent_alive():
                return 
Example #5
Source File: udp_rx_handler.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def ready_to_read(self):
        while True:
            ancillary_size = socket.CMSG_LEN(self.MAX_SIZE)
            try:
                message, ancillary_messages, _msg_flags, from_info = \
                    self.sock.recvmsg(self.MAX_SIZE, ancillary_size)
            except (IOError, OSError) as err:
                if err.args[0] != errno.EWOULDBLOCK:
                    self.warning("Socket receive failed: %s", err)
                return
            if not MACOS:
                rx_interface_index = None
                for anc in ancillary_messages:
                    # pylint:disable=no-member
                    if anc[0] == socket.SOL_IP and anc[1] == socket.IP_PKTINFO:
                        packet_info = in_pktinfo.from_buffer_copy(anc[2])
                        rx_interface_index = packet_info.ipi_ifindex
                    elif anc[0] == socket.SOL_IPV6 and anc[1] == socket.IPV6_PKTINFO:
                        packet_info = in6_pktinfo.from_buffer_copy(anc[2])
                        rx_interface_index = packet_info.ipi6_ifindex
                if rx_interface_index and (rx_interface_index != self._interface_index):
                    # Message received on "wrong" interface; ignore
                    return
            self._receive_function(message, from_info, self.sock) 
Example #6
Source File: io.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _receive(self):
        """Receive any incoming socket data.

            If an error is thrown, handle it and return an empty string.

        :return: data_in
        :rtype: bytes
        """
        data_in = EMPTY_BUFFER
        try:
            if not self.socket:
                raise socket.error('connection/socket error')
            data_in = self._read_from_socket()
        except socket.timeout:
            pass
        except (IOError, OSError) as why:
            if why.args[0] not in (EWOULDBLOCK, EAGAIN):
                self._exceptions.append(AMQPConnectionError(why))
                self._running.clear()
        return data_in 
Example #7
Source File: stream.py    From gnsq with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def read(self, size):
        while len(self.buffer) < size:
            self.ensure_connection()

            try:
                packet = self.socket.recv(self.buffer_size)
            except socket.error as error:
                if error.errno in (EDEADLK, EAGAIN, EWOULDBLOCK):
                    gevent.sleep()
                    continue
                six.raise_from(NSQSocketError(*error.args), error)

            if not packet:
                self.close()

            self.buffer += packet

        data = self.buffer[:size]
        self.buffer = self.buffer[size:]

        return data 
Example #8
Source File: test_ssl.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_timeout_connect_ex(self):
        # Issue #12065: on a timeout, connect_ex() should return the original
        # errno (mimicking the behaviour of non-SSL sockets).
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT,
                                do_handshake_on_connect=False)
            try:
                s.settimeout(0.0000001)
                rc = s.connect_ex((REMOTE_HOST, 443))
                if rc == 0:
                    self.skipTest("REMOTE_HOST responded too quickly")
                self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK))
            finally:
                s.close() 
Example #9
Source File: test_ssl.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_connect_ex_error(self):
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT)
            try:
                rc = s.connect_ex((REMOTE_HOST, 444))
                # Issue #19919: Windows machines or VMs hosted on Windows
                # machines sometimes return EWOULDBLOCK.
                errors = (
                    errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
                    errno.EWOULDBLOCK,
                )
                self.assertIn(rc, errors)
            finally:
                s.close() 
Example #10
Source File: network.py    From mopidy-mpd with Apache License 2.0 6 votes vote down vote up
def recv_callback(self, fd, flags):
        if flags & (GLib.IO_ERR | GLib.IO_HUP):
            self.stop(f"Bad client flags: {flags}")
            return True

        try:
            data = self._sock.recv(4096)
        except OSError as exc:
            if exc.errno not in (errno.EWOULDBLOCK, errno.EINTR):
                self.stop(f"Unexpected client error: {exc}")
            return True

        if not data:
            self.disable_recv()
            self.actor_ref.tell({"close": True})
            return True

        try:
            self.actor_ref.tell({"received": data})
        except pykka.ActorDeadError:
            self.stop("Actor is dead.")

        return True 
Example #11
Source File: tco.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def send(self, message, flags):
        with self.send_token:
            if not self.state.ESTABLISHED:
                self.err("send() in socket state {0}".format(self.state))
                if self.state.CLOSE_WAIT:
                    raise err.Error(errno.EPIPE)
                raise err.Error(errno.ENOTCONN)
            if len(message) > self.send_miu:
                raise err.Error(errno.EMSGSIZE)
            while self.send_window_slots == 0 and self.state.ESTABLISHED:
                if flags & nfc.llcp.MSG_DONTWAIT:
                    raise err.Error(errno.EWOULDBLOCK)
                self.log("waiting on busy send window")
                self.send_token.wait()
            self.log("send {0} byte on {1}".format(len(message), str(self)))
            if self.state.ESTABLISHED:
                send_pdu = pdu.Information(self.peer, self.addr, data=message)
                send_pdu.ns = self.send_cnt
                self.send_cnt = (self.send_cnt + 1) % 16
                super(DataLinkConnection, self).send(send_pdu, flags)
            return self.state.ESTABLISHED is True 
Example #12
Source File: client.py    From ParadoxIP150v2 with Eclipse Public License 1.0 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("localhost", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example #13
Source File: test_ssl.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_timeout_connect_ex(self):
        # Issue #12065: on a timeout, connect_ex() should return the original
        # errno (mimicking the behaviour of non-SSL sockets).
        with test_support.transient_internet("svn.python.org"):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=SVN_PYTHON_ORG_ROOT_CERT,
                                do_handshake_on_connect=False)
            try:
                s.settimeout(0.0000001)
                rc = s.connect_ex(('svn.python.org', 443))
                if rc == 0:
                    self.skipTest("svn.python.org responded too quickly")
                self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK))
            finally:
                s.close() 
Example #14
Source File: iostream.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def write_to_fd(self, data: memoryview) -> int:
        try:
            return self.socket.send(data)  # type: ignore
        except ssl.SSLError as e:
            if e.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if
                # the socket is not writeable; we need to transform this into
                # an EWOULDBLOCK socket.error or a zero return value,
                # either of which will be recognized by the caller of this
                # method. Prior to Python 3.5, an unwriteable socket would
                # simply return 0 bytes written.
                return 0
            raise
        finally:
            # Avoid keeping to data, which can be a memoryview.
            # See https://github.com/tornadoweb/tornado/pull/2008
            del data 
Example #15
Source File: tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def doRead(self):
        """Calls self.protocol.dataReceived with all available data.

        This reads up to self.bufferSize bytes of data from its socket, then
        calls self.dataReceived(data) to process it.  If the connection is not
        lost through an error in the physical recv(), this function will return
        the result of the dataReceived call.
        """
        try:
            data = self.socket.recv(self.bufferSize)
        except socket.error as se:
            if se.args[0] == EWOULDBLOCK:
                return
            else:
                return main.CONNECTION_LOST

        return self._dataReceived(data) 
Example #16
Source File: tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def writeSomeData(self, data):
        """
        Write as much as possible of the given data to this TCP connection.

        This sends up to C{self.SEND_LIMIT} bytes from C{data}.  If the
        connection is lost, an exception is returned.  Otherwise, the number
        of bytes successfully written is returned.
        """
        # Limit length of buffer to try to send, because some OSes are too
        # stupid to do so themselves (ahem windows)
        limitedData = lazyByteSlice(data, 0, self.SEND_LIMIT)

        try:
            return untilConcludes(self.socket.send, limitedData)
        except socket.error as se:
            if se.args[0] in (EWOULDBLOCK, ENOBUFS):
                return 0
            else:
                return main.CONNECTION_LOST 
Example #17
Source File: iostream.py    From teleport with Apache License 2.0 6 votes vote down vote up
def write_to_fd(self, data):
        try:
            return self.socket.send(data)
        except ssl.SSLError as e:
            if e.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if
                # the socket is not writeable; we need to transform this into
                # an EWOULDBLOCK socket.error or a zero return value,
                # either of which will be recognized by the caller of this
                # method. Prior to Python 3.5, an unwriteable socket would
                # simply return 0 bytes written.
                return 0
            raise
        finally:
            # Avoid keeping to data, which can be a memoryview.
            # See https://github.com/tornadoweb/tornado/pull/2008
            del data 
Example #18
Source File: websocketproxy.py    From zun with Apache License 2.0 6 votes vote down vote up
def _send_buffer(self, buff, target, send_all=False):
        size = len(buff)
        tosend = size
        already_sent = 0

        while tosend > 0:
            try:
                # i should be able to send a bytearray
                sent = target.send(buff[already_sent:])
                if sent == 0:
                    raise RuntimeError('socket connection broken')

                already_sent += sent
                tosend -= sent

            except socket.error as e:
                # if full buffers then wait for them to drain and try again
                if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]:
                    if send_all:
                        continue
                    return buff[already_sent:]
                else:
                    raise exception.SocketException(str(e))
        return None 
Example #19
Source File: iostream.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def connect(self, address, callback=None, server_hostname=None):
        """Connects the socket to a remote address without blocking.

        May only be called if the socket passed to the constructor was
        not previously connected.  The address parameter is in the
        same format as for `socket.connect <socket.socket.connect>`,
        i.e. a ``(host, port)`` tuple.  If ``callback`` is specified,
        it will be called when the connection is completed.

        If specified, the ``server_hostname`` parameter will be used
        in SSL connections for certificate validation (if requested in
        the ``ssl_options``) and SNI (if supported; requires
        Python 3.2+).

        Note that it is safe to call `IOStream.write
        <BaseIOStream.write>` while the connection is pending, in
        which case the data will be written as soon as the connection
        is ready.  Calling `IOStream` read methods before the socket is
        connected works on some platforms but is non-portable.
        """
        self._connecting = True
        try:
            self.socket.connect(address)
        except socket.error as e:
            # In non-blocking mode we expect connect() to raise an
            # exception with EINPROGRESS or EWOULDBLOCK.
            #
            # On freebsd, other errors such as ECONNREFUSED may be
            # returned immediately when attempting to connect to
            # localhost, so handle them the same way as an error
            # reported later in _handle_connect.
            if (e.args[0] != errno.EINPROGRESS and
                e.args[0] not in _ERRNO_WOULDBLOCK):
                gen_log.warning("Connect error on fd %d: %s",
                                self.socket.fileno(), e)
                self.close(exc_info=True)
                return
        self._connect_callback = stack_context.wrap(callback)
        self._add_io_state(self.io_loop.WRITE) 
Example #20
Source File: handlers.py    From oss-ftp with MIT License 5 votes vote down vote up
def send(self, data):
            if not isinstance(data, bytes):
                data = bytes(data)
            try:
                return super(SSLConnection, self).send(data)
            except SSL.WantReadError:
                debug("call: send(), err: want-read", inst=self)
                self._ssl_want_read = True
                return 0
            except SSL.WantWriteError:
                debug("call: send(), err: want-write", inst=self)
                self._ssl_want_write = True
                return 0
            except SSL.ZeroReturnError as err:
                debug(
                    "call: send() -> shutdown(), err: zero-return", inst=self)
                super(SSLConnection, self).handle_close()
                return 0
            except SSL.SysCallError as err:
                debug("call: send(), err: %r" % err, inst=self)
                errnum, errstr = err.args
                if errnum == errno.EWOULDBLOCK:
                    return 0
                elif (errnum in _ERRNOS_DISCONNECTED or
                        errstr == 'Unexpected EOF'):
                    super(SSLConnection, self).handle_close()
                    return 0
                else:
                    raise 
Example #21
Source File: iostream.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def _handle_read(self):
        try:
            try:
                # Pretend to have a pending callback so that an EOF in
                # _read_to_buffer doesn't trigger an immediate close
                # callback.  At the end of this method we'll either
                # estabilsh a real pending callback via
                # _read_from_buffer or run the close callback.
                #
                # We need two try statements here so that
                # pending_callbacks is decremented before the `except`
                # clause below (which calls `close` and does need to
                # trigger the callback)
                self._pending_callbacks += 1
                while not self.closed():
                    # Read from the socket until we get EWOULDBLOCK or equivalent.
                    # SSL sockets do some internal buffering, and if the data is
                    # sitting in the SSL object's buffer select() and friends
                    # can't see it; the only way to find out if it's there is to
                    # try to read it.
                    if self._read_to_buffer() == 0:
                        break
            finally:
                self._pending_callbacks -= 1
        except Exception:
            gen_log.warning("error on read", exc_info=True)
            self.close(exc_info=True)
            return
        if self._read_from_buffer():
            return
        else:
            self._maybe_run_close_callback() 
Example #22
Source File: iostream.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def read_from_fd(self):
        """Attempts to read from the underlying file.

        Returns ``None`` if there was nothing to read (the socket
        returned `~errno.EWOULDBLOCK` or equivalent), otherwise
        returns the data.  When possible, should return no more than
        ``self.read_chunk_size`` bytes at a time.
        """
        raise NotImplementedError() 
Example #23
Source File: iostream.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def _read_to_buffer(self):
        """Reads from the socket and appends the result to the read buffer.

        Returns the number of bytes read.  Returns 0 if there is nothing
        to read (i.e. the read returns EWOULDBLOCK or equivalent).  On
        error closes the socket and raises an exception.
        """
        try:
            chunk = self.read_from_fd()
        except (socket.error, IOError, OSError) as e:
            # ssl.SSLError is a subclass of socket.error
            if e.args[0] in _ERRNO_CONNRESET:
                # Treat ECONNRESET as a connection close rather than
                # an error to minimize log spam  (the exception will
                # be available on self.error for apps that care).
                self.close(exc_info=True)
                return
            self.close(exc_info=True)
            raise
        if chunk is None:
            return 0
        self._read_buffer.append(chunk)
        self._read_buffer_size += len(chunk)
        if self._read_buffer_size >= self.max_buffer_size:
            gen_log.error("Reached maximum read buffer size")
            self.close()
            raise IOError("Reached maximum read buffer size")
        return len(chunk) 
Example #24
Source File: iostream.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def _read_to_buffer(self):
        """Reads from the socket and appends the result to the read buffer.

        Returns the number of bytes read.  Returns 0 if there is nothing
        to read (i.e. the read returns EWOULDBLOCK or equivalent).  On
        error closes the socket and raises an exception.
        """
        try:
            chunk = self.read_from_fd()
        except (socket.error, IOError, OSError) as e:
            # ssl.SSLError is a subclass of socket.error
            if e.args[0] in _ERRNO_CONNRESET:
                # Treat ECONNRESET as a connection close rather than
                # an error to minimize log spam  (the exception will
                # be available on self.error for apps that care).
                self.close(exc_info=True)
                return
            self.close(exc_info=True)
            raise
        if chunk is None:
            return 0
        self._read_buffer.append(chunk)
        self._read_buffer_size += len(chunk)
        if self._read_buffer_size >= self.max_buffer_size:
            gen_log.error("Reached maximum read buffer size")
            self.close()
            raise IOError("Reached maximum read buffer size")
        return len(chunk) 
Example #25
Source File: handlers.py    From oss-ftp with MIT License 5 votes vote down vote up
def send(self, data):
            if not isinstance(data, bytes):
                data = bytes(data)
            try:
                return super(SSLConnection, self).send(data)
            except SSL.WantReadError:
                debug("call: send(), err: want-read", inst=self)
                self._ssl_want_read = True
                return 0
            except SSL.WantWriteError:
                debug("call: send(), err: want-write", inst=self)
                self._ssl_want_write = True
                return 0
            except SSL.ZeroReturnError as err:
                debug(
                    "call: send() -> shutdown(), err: zero-return", inst=self)
                super(SSLConnection, self).handle_close()
                return 0
            except SSL.SysCallError as err:
                debug("call: send(), err: %r" % err, inst=self)
                errnum, errstr = err.args
                if errnum == errno.EWOULDBLOCK:
                    return 0
                elif (errnum in _ERRNOS_DISCONNECTED or
                        errstr == 'Unexpected EOF'):
                    super(SSLConnection, self).handle_close()
                    return 0
                else:
                    raise 
Example #26
Source File: test_ssl.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_connect_ex(self):
            """
            If there is a connection error, :py:obj:`Connection.connect_ex` returns the
            errno instead of raising an exception.
            """
            port = socket()
            port.bind(('', 0))
            port.listen(3)

            clientSSL = Connection(Context(TLSv1_METHOD), socket())
            clientSSL.setblocking(False)
            result = clientSSL.connect_ex(port.getsockname())
            expected = (EINPROGRESS, EWOULDBLOCK)
            self.assertTrue(
                    result in expected, "%r not in %r" % (result, expected)) 
Example #27
Source File: test_ssl.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_wantWriteError(self):
        """
        :py:obj:`Connection` methods which generate output raise
        :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
        fail indicating a should-write state.
        """
        client_socket, server_socket = socket_pair()
        # Fill up the client's send buffer so Connection won't be able to write
        # anything.  Only write a single byte at a time so we can be sure we
        # completely fill the buffer.  Even though the socket API is allowed to
        # signal a short write via its return value it seems this doesn't
        # always happen on all platforms (FreeBSD and OS X particular) for the
        # very last bit of available buffer space.
        msg = b"x"
        for i in range(1024 * 1024 * 4):
            try:
                client_socket.send(msg)
            except error as e:
                if e.errno == EWOULDBLOCK:
                    break
                raise
        else:
            self.fail(
                "Failed to fill socket buffer, cannot test BIO want write")

        ctx = Context(TLSv1_METHOD)
        conn = Connection(ctx, client_socket)
        # Client's speak first, so make it an SSL client
        conn.set_connect_state()
        self.assertRaises(WantWriteError, conn.do_handshake)

    # XXX want_read 
Example #28
Source File: test_ssl.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_non_blocking_connect_ex(self):
        # Issue #11326: non-blocking connect_ex() should allow handshake
        # to proceed after the socket gets ready.
        with support.transient_internet("svn.python.org"):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=SVN_PYTHON_ORG_ROOT_CERT,
                                do_handshake_on_connect=False)
            try:
                s.setblocking(False)
                rc = s.connect_ex(('svn.python.org', 443))
                # EWOULDBLOCK under Windows, EINPROGRESS elsewhere
                self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK))
                # Wait for connect to finish
                select.select([], [s], [], 5.0)
                # Non-blocking handshake
                while True:
                    try:
                        s.do_handshake()
                        break
                    except ssl.SSLWantReadError:
                        select.select([s], [], [], 5.0)
                    except ssl.SSLWantWriteError:
                        select.select([], [s], [], 5.0)
                # SSL established
                self.assertTrue(s.getpeercert())
            finally:
                s.close() 
Example #29
Source File: test_ssl.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_connect_ex_error(self):
        with support.transient_internet("svn.python.org"):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
            try:
                rc = s.connect_ex(("svn.python.org", 444))
                # Issue #19919: Windows machines or VMs hosted on Windows
                # machines sometimes return EWOULDBLOCK.
                self.assertIn(rc, (errno.ECONNREFUSED, errno.EWOULDBLOCK))
            finally:
                s.close() 
Example #30
Source File: slippstream.py    From libmelee with GNU Lesser General Public License v3.0 5 votes vote down vote up
def read_message(self):
        """ Read an entire message from the registered socket.

        Returns None on failure, Dict of data from ubjson on success.
        """
        while True:
            try:
                # The first 4 bytes are the message's length
                #   read this first
                while len(self.buf) < 4:
                    self.buf += self.server.recv(4 - len(self.buf))
                    if len(self.buf) == 0:
                        return None
                message_len = unpack(">L", self.buf[0:4])[0]

                # Now read in message_len amount of data
                while len(self.buf) < (message_len + 4):
                    self.buf += self.server.recv((message_len + 4) - len(self.buf))

                try:
                    # Exclude the the message length in the header
                    msg = ubjson.loadb(self.buf[4:])
                    # Clear out the old buffer
                    del self.buf
                    self.buf = bytearray()
                    return msg

                except DecoderException as exception:
                    print("ERROR: Decode failure in Slippstream")
                    print(exception)
                    print(hexdump(self.buf[4:]))
                    self.buf.clear()
                    return None

            except socket.error as exception:
                if exception.args[0] == errno.EWOULDBLOCK:
                    continue
                print("ERROR with socket:", exception)
                return None