Python ssl.SSL_ERROR_WANT_WRITE Examples

The following are 30 code examples of ssl.SSL_ERROR_WANT_WRITE(). 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 ssl , 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: test_ftplib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _do_ssl_shutdown(self):
            self._ssl_closing = True
            try:
                self.socket = self.socket.unwrap()
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
            except socket.error as err:
                # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
                # from OpenSSL's SSL_shutdown(), corresponding to a
                # closed socket condition. See also:
                # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
                pass
            self._ssl_closing = False
            if getattr(self, '_ccc', False) is False:
                super(SSLConnection, self).close()
            else:
                pass 
Example #3
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 #4
Source File: XAsyncSockets.py    From MicroWebSrv2 with MIT License 6 votes vote down vote up
def _doSSLHandshake(self) :
        count = 0
        while count < 10 :
            try :
                self._socket.do_handshake()
                break
            except ssl.SSLError as sslErr :
                count += 1
                if sslErr.args[0] == ssl.SSL_ERROR_WANT_READ :
                    select([self._socket], [], [], 1)
                elif sslErr.args[0] == ssl.SSL_ERROR_WANT_WRITE :
                    select([], [self._socket], [], 1)
                else :
                    raise XAsyncTCPClientException('SSL : Bad handshake : %s' % sslErr)
            except Exception as ex :
                raise XAsyncTCPClientException('SSL : Handshake error : %s' % ex)

    # ------------------------------------------------------------------------ 
Example #5
Source File: test_connection.py    From nsq-py with MIT License 6 votes vote down vote up
def test_flush_would_block_ssl_write_buffer(self):
        '''ssl.SSL_ERROR_WANT_WRITE usesthe same buffer on next send'''
        pending = deque([b'1', b'2', b'3'])
        with mock.patch.object(self.connection, '_pending', pending):
            with mock.patch.object(self.connection, '_socket') as mock_socket:
                mock_socket.send.side_effect = ssl.SSLError(
                    ssl.SSL_ERROR_WANT_WRITE)
                self.assertFalse(self.connection._out_buffer)
                self.connection.flush()
                self.assertEqual(self.connection._out_buffer, b'123')

        # With some more pending items, make sure we still only get '123' sent
        pending = deque([b'4', b'5', b'6'])
        with mock.patch.object(self.connection, '_pending', pending):
            with mock.patch.object(self.connection, '_socket') as mock_socket:
                mock_socket.send.return_value = 3
                # The first flush should see the existing buffer
                self.connection.flush()
                mock_socket.send.assert_called_with(b'123')
                # The second flush should see the pending requests
                self.connection.flush()
                mock_socket.send.assert_called_with(b'456') 
Example #6
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 #7
Source File: tls.py    From nsq-py with MIT License 6 votes vote down vote up
def wrap_socket(cls, socket):
        sock = ssl.wrap_socket(socket, ssl_version=ssl.PROTOCOL_TLSv1)
        while True:
            try:
                logger.info('Performing TLS handshade...')
                sock.do_handshake()
                break
            except ssl.SSLError as err:
                errs = (
                    ssl.SSL_ERROR_WANT_READ,
                    ssl.SSL_ERROR_WANT_WRITE)
                if err.args[0] not in (errs):
                    raise
                else:
                    logger.info('Continuing TLS handshake...')
        logger.info('Socket wrapped')
        return sock 
Example #8
Source File: test_ftplib.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _do_ssl_shutdown(self):
            self._ssl_closing = True
            try:
                self.socket = self.socket.unwrap()
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
            except OSError as err:
                # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
                # from OpenSSL's SSL_shutdown(), corresponding to a
                # closed socket condition. See also:
                # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
                pass
            self._ssl_closing = False
            if getattr(self, '_ccc', False) is False:
                super(SSLConnection, self).close()
            else:
                pass 
Example #9
Source File: iostream.py    From pySINDy with MIT License 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 #10
Source File: test_ftplib.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def _do_ssl_shutdown(self):
            self._ssl_closing = True
            try:
                self.socket = self.socket.unwrap()
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
            except OSError as err:
                # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
                # from OpenSSL's SSL_shutdown(), corresponding to a
                # closed socket condition. See also:
                # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
                pass
            self._ssl_closing = False
            if getattr(self, '_ccc', False) is False:
                super(SSLConnection, self).close()
            else:
                pass 
Example #11
Source File: providers.py    From aws-iot-device-sdk-python with Apache License 2.0 6 votes vote down vote up
def _send_discovery_request(self, ssl_sock, thing_name):
        request = self.REQUEST_TYPE_PREFIX + \
                  self.PAYLOAD_PREFIX + \
                  thing_name + \
                  self.PAYLOAD_SUFFIX + \
                  self.HOST_PREFIX + \
                  self._host + ":" + str(self._port) + \
                  self.HOST_SUFFIX
        self._logger.debug("Sending discover request: " + request)

        start_time = time.time()
        desired_length_to_write = len(request)
        actual_length_written = 0
        while True:
            try:
                length_written = ssl_sock.write(request.encode("utf-8"))
                actual_length_written += length_written
            except socket.error as err:
                if err.errno == ssl.SSL_ERROR_WANT_READ or err.errno == ssl.SSL_ERROR_WANT_WRITE:
                    pass
            if actual_length_written == desired_length_to_write:
                return self.LOW_LEVEL_RC_COMPLETE
            if start_time + self._timeout_sec < time.time():
                return self.LOW_LEVEL_RC_TIMEOUT 
Example #12
Source File: providers.py    From aws-iot-device-sdk-python with Apache License 2.0 6 votes vote down vote up
def _receive_until(self, ssl_sock, criteria_function, extra_data=None):
        start_time = time.time()
        response = bytearray()
        number_bytes_read = 0
        while True:  # Python does not have do-while
            try:
                response.append(self._convert_to_int_py3(ssl_sock.read(1)))
                number_bytes_read += 1
            except socket.error as err:
                if err.errno == ssl.SSL_ERROR_WANT_READ or err.errno == ssl.SSL_ERROR_WANT_WRITE:
                    pass

            if criteria_function((number_bytes_read, response, extra_data)):
                return self.LOW_LEVEL_RC_COMPLETE, response
            if start_time + self._timeout_sec < time.time():
                return self.LOW_LEVEL_RC_TIMEOUT, response 
Example #13
Source File: cores.py    From aws-iot-device-sdk-python with Apache License 2.0 6 votes vote down vote up
def _hasCredentialsNecessaryForWebsocket(self, allKeys):
        awsAccessKeyIdCandidate = allKeys.get("aws_access_key_id")
        awsSecretAccessKeyCandidate = allKeys.get("aws_secret_access_key")
        # None value is NOT considered as valid entries
        validEntries = awsAccessKeyIdCandidate is not None and awsAccessKeyIdCandidate is not None
        if validEntries:
            # Empty value is NOT considered as valid entries
            validEntries &= (len(awsAccessKeyIdCandidate) != 0 and len(awsSecretAccessKeyCandidate) != 0)
        return validEntries


# This is an internal class that buffers the incoming bytes into an
# internal buffer until it gets the full desired length of bytes.
# At that time, this bufferedReader will be reset.
# *Error handling:
# For retry errors (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE, EAGAIN),
# leave them to the paho _packet_read for further handling (ignored and try
# again when data is available.
# For other errors, leave them to the paho _packet_read for error reporting. 
Example #14
Source File: link.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def send(self, data):
        """
        If data is ``None`` then ``self.write_buf`` is used.
        """
        if (data is not None) and not self.send_finished:
            raise SendNotFinished(("previous send on %r is not finished, " +
                              "wait for on_ready_to_send") % self)

        data = data or self.write_buf

        self.send_finished = False
        if self.ssl_config is None:
            self.last_send_size = self.sock.send(data)
        else:
            try:
                self.last_send_size = self.sock.write(data)
                self.write_buf = None
            except ssl.SSLError as exc:
                if exc.args[0] != ssl.SSL_ERROR_WANT_WRITE:
                    raise
                self.write_buf = data

    ######################################################### 
Example #15
Source File: transport.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _continue_tls_handshake(self):
        """Continue a TLS handshake."""
        try:
            logger.debug(" do_handshake()")
            self._socket.do_handshake()
        except ssl.SSLError as err:
            if err.args[0] == ssl.SSL_ERROR_WANT_READ:
                self._tls_state = "want_read"
                logger.debug("   want_read")
                self._state_cond.notify()
                return
            elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                self._tls_state = "want_write"
                logger.debug("   want_write")
                self._write_queue.appendleft(TLSHandshake)
                return
            else:
                raise
        self._tls_state = "connected"
        self._set_state("connected")
        self.event(TLSConnectedEvent(self._socket.cipher(),
                                                self._socket.getpeercert())) 
Example #16
Source File: test_ftplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def _do_ssl_shutdown(self):
            self._ssl_closing = True
            try:
                self.socket = self.socket.unwrap()
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
            except OSError as err:
                # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
                # from OpenSSL's SSL_shutdown(), corresponding to a
                # closed socket condition. See also:
                # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
                pass
            self._ssl_closing = False
            if getattr(self, '_ccc', False) is False:
                super(SSLConnection, self).close()
            else:
                pass 
Example #17
Source File: test_poplib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _do_ssl_handshake(self):
            try:
                self.socket.do_handshake()
            except ssl.SSLError, err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
                elif err.args[0] == ssl.SSL_ERROR_EOF:
                    return self.handle_close()
                raise 
Example #18
Source File: iostream.py    From tornado-zh with MIT License 5 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 
Example #19
Source File: transport.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _write(self, data):
        """Write raw data to the socket.

        :Parameters:
            - `data`: data to send
        :Types:
            - `data`: `bytes`
        """
        OUT_LOGGER.debug("OUT: %r", data)
        if self._hup or not self._socket:
            raise PyXMPPIOError("Connection closed.")
        try:
            while data:
                try:
                    sent = self._socket.send(data)
                except ssl.SSLError as err:
                    if err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                        continue
                    else:
                        raise
                except socket.error as err:
                    if err.args[0] == errno.EINTR:
                        continue
                    if err.args[0] == errno.EWOULDBLOCK:
                        wait_for_write(self._socket)
                        continue
                    raise
                data = data[sent:]
        except (IOError, OSError, socket.error) as err:
            raise PyXMPPIOError("IO Error: {0}".format(err)) 
Example #20
Source File: test_ftplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def recv(self, buffer_size):
            try:
                return super(SSLConnection, self).recv(buffer_size)
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return b''
                if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
                    self.handle_close()
                    return b''
                raise 
Example #21
Source File: cores.py    From aws-iot-device-sdk-python with Apache License 2.0 5 votes vote down vote up
def read(self, numberOfBytesToBeBuffered):
        if not self._bufferingInProgress:  # If last read is completed...
            self._remainedLength = numberOfBytesToBeBuffered
            self._bufferingInProgress = True  # Now we start buffering a new length of bytes

        while self._remainedLength > 0:  # Read in a loop, always try to read in the remained length
            # If the data is temporarily not available, socket.error will be raised and catched by paho
            dataChunk = self._sslSocket.read(self._remainedLength)
            # There is a chance where the server terminates the connection without closing the socket.
            # If that happens, let's raise an exception and enter the reconnect flow.
            if not dataChunk:
                raise socket.error(errno.ECONNABORTED, 0)
            self._internalBuffer.extend(dataChunk)  # Buffer the data
            self._remainedLength -= len(dataChunk)  # Update the remained length

        # The requested length of bytes is buffered, recover the context and return it
        # Otherwise error should be raised
        ret = self._internalBuffer
        self._reset()
        return ret  # This should always be bytearray


# This is the internal class that sends requested data out chunk by chunk according
# to the availablity of the socket write operation. If the requested bytes of data
# (after encoding) needs to be sent out in separate socket write operations (most
# probably be interrupted by the error socket.error (errno = ssl.SSL_ERROR_WANT_WRITE).)
# , the write pointer is stored to ensure that the continued bytes will be sent next
# time this function gets called.
# *Error handling:
# For retry errors (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE, EAGAIN),
# leave them to the paho _packet_read for further handling (ignored and try
# again when data is available.
# For other errors, leave them to the paho _packet_read for error reporting. 
Example #22
Source File: iostream.py    From tornado-zh with MIT License 5 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 
Example #23
Source File: test_ftplib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _do_ssl_handshake(self):
            try:
                self.socket.do_handshake()
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
                elif err.args[0] == ssl.SSL_ERROR_EOF:
                    return self.handle_close()
                raise
            except socket.error as err:
                if err.args[0] == errno.ECONNABORTED:
                    return self.handle_close()
            else:
                self._ssl_accepting = False 
Example #24
Source File: test_ftplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def recv(self, buffer_size):
            try:
                return super(SSLConnection, self).recv(buffer_size)
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return b''
                if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
                    self.handle_close()
                    return b''
                raise 
Example #25
Source File: test_ftplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def send(self, data):
            try:
                return super(SSLConnection, self).send(data)
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
                                   ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return 0
                raise 
Example #26
Source File: test_ftplib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def send(self, data):
            try:
                return super(SSLConnection, self).send(data)
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
                                   ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return 0
                raise 
Example #27
Source File: test_ftplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _do_ssl_handshake(self):
            try:
                self.socket.do_handshake()
            except ssl.SSLError as err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
                elif err.args[0] == ssl.SSL_ERROR_EOF:
                    return self.handle_close()
                raise
            except OSError as err:
                if err.args[0] == errno.ECONNABORTED:
                    return self.handle_close()
            else:
                self._ssl_accepting = False 
Example #28
Source File: test_ftplib.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _do_ssl_shutdown(self):
            self._ssl_closing = True
            try:
                self.socket = self.socket.unwrap()
            except ssl.SSLError, err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return 
Example #29
Source File: test_ftplib.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def send(self, data):
            try:
                return super(SSLConnection, self).send(data)
            except ssl.SSLError, err:
                if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
                                   ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return 0
                raise 
Example #30
Source File: test_ftplib.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _do_ssl_handshake(self):
            try:
                self.socket.do_handshake()
            except ssl.SSLError, err:
                if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                   ssl.SSL_ERROR_WANT_WRITE):
                    return
                elif err.args[0] == ssl.SSL_ERROR_EOF:
                    return self.handle_close()
                raise