Python errno.ENOTCONN Examples

The following are 30 code examples of errno.ENOTCONN(). 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: DNRelay.py    From rtp_cluster with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def deliver_dnotify(self, dnstring, _recurse = 0):
        if self.s == None:
            self.connect()
        if _recurse > _MAX_RECURSE:
            raise Exception('Cannot reconnect: %s', self.spath)
        if not dnstring.endswith('\n'):
            dnstring += '\n'
        while True:
            try:
                self.s.send(dnstring)
                break
            except socket.error as why:
                if why[0] == EINTR:
                    continue
                elif why[0] in (EPIPE, ENOTCONN, ECONNRESET):
                    self.s = None
                    return self.deliver_dnotify(dnstring, _recurse + 1)
                raise why
        # Clean any incoming data on the socket
        if len(self.poller.poll(0)) > 0:
            try:
                self.s.recv(1024)
            except:
                pass
        return 
Example #2
Source File: smtpd.py    From meddle with MIT License 6 votes vote down vote up
def __init__(self, server, conn, addr):
        asynchat.async_chat.__init__(self, conn)
        self.__server = server
        self.__conn = conn
        self.__addr = addr
        self.__line = []
        self.__state = self.COMMAND
        self.__greeting = 0
        self.__mailfrom = None
        self.__rcpttos = []
        self.__data = ''
        self.__fqdn = socket.getfqdn()
        try:
            self.__peer = conn.getpeername()
        except socket.error, err:
            # a race condition  may occur if the other end is closing
            # before we can get the peername
            self.close()
            if err[0] != errno.ENOTCONN:
                raise
            return 
Example #3
Source File: tco.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def recv(self):
        with self.lock:
            if not (self.state.ESTABLISHED or self.state.CLOSE_WAIT):
                self.err("recv() in socket state {0}".format(self.state))
                raise err.Error(errno.ENOTCONN)

            try:
                rcvd_pdu = super(DataLinkConnection, self).recv()
            except IndexError:
                return None

            if rcvd_pdu.name == "I":
                self.recv_confs += 1
                if self.recv_confs > self.recv_win:
                    self.err("recv_confs({0}) > recv_win({1})"
                             .format(self.recv_confs, self.recv_win))
                    raise RuntimeError("recv_confs > recv_win")
                return rcvd_pdu.data

            if rcvd_pdu.name == "DISC":
                self.close()
                return None

            raise RuntimeError("only I or DISC expected, not " + rcvd_pdu.name) 
Example #4
Source File: smtpd.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def __init__(self, server, conn, addr):
        asynchat.async_chat.__init__(self, conn)
        self.__server = server
        self.__conn = conn
        self.__addr = addr
        self.__line = []
        self.__state = self.COMMAND
        self.__greeting = 0
        self.__mailfrom = None
        self.__rcpttos = []
        self.__data = ''
        self.__fqdn = socket.getfqdn()
        try:
            self.__peer = conn.getpeername()
        except socket.error, err:
            # a race condition  may occur if the other end is closing
            # before we can get the peername
            self.close()
            if err[0] != errno.ENOTCONN:
                raise
            return 
Example #5
Source File: poplib.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def close(self):
        """Close the connection without assuming anything about it."""
        try:
            file = self.file
            self.file = None
            if file is not None:
                file.close()
        finally:
            sock = self.sock
            self.sock = None
            if sock is not None:
                try:
                    sock.shutdown(socket.SHUT_RDWR)
                except OSError as e:
                    # The server might already have closed the connection
                    if e.errno != errno.ENOTCONN:
                        raise
                finally:
                    sock.close()

    #__del__ = quit


    # optional commands: 
Example #6
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 #7
Source File: smtpd.py    From BinderFilter with MIT License 6 votes vote down vote up
def __init__(self, server, conn, addr):
        asynchat.async_chat.__init__(self, conn)
        self.__server = server
        self.__conn = conn
        self.__addr = addr
        self.__line = []
        self.__state = self.COMMAND
        self.__greeting = 0
        self.__mailfrom = None
        self.__rcpttos = []
        self.__data = ''
        self.__fqdn = socket.getfqdn()
        try:
            self.__peer = conn.getpeername()
        except socket.error, err:
            # a race condition  may occur if the other end is closing
            # before we can get the peername
            self.close()
            if err[0] != errno.ENOTCONN:
                raise
            return 
Example #8
Source File: smtpd.py    From oss-ftp with MIT License 6 votes vote down vote up
def __init__(self, server, conn, addr):
        asynchat.async_chat.__init__(self, conn)
        self.__server = server
        self.__conn = conn
        self.__addr = addr
        self.__line = []
        self.__state = self.COMMAND
        self.__greeting = 0
        self.__mailfrom = None
        self.__rcpttos = []
        self.__data = ''
        self.__fqdn = socket.getfqdn()
        try:
            self.__peer = conn.getpeername()
        except socket.error, err:
            # a race condition  may occur if the other end is closing
            # before we can get the peername
            self.close()
            if err[0] != errno.ENOTCONN:
                raise
            return 
Example #9
Source File: poplib.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def close(self):
        """Close the connection without assuming anything about it."""
        try:
            file = self.file
            self.file = None
            if file is not None:
                file.close()
        finally:
            sock = self.sock
            self.sock = None
            if sock is not None:
                try:
                    sock.shutdown(socket.SHUT_RDWR)
                except OSError as e:
                    # The server might already have closed the connection
                    if e.errno != errno.ENOTCONN:
                        raise
                finally:
                    sock.close()

    #__del__ = quit


    # optional commands: 
Example #10
Source File: server.py    From testplan with Apache License 2.0 6 votes vote down vote up
def _remove_connection(self, fdesc):
        """
        Unregister, close and remove inbound connection with given fd.

        :param fdesc: File descriptor of connection to be removed.
        :type fdesc: ``int``
        """
        self._pobj.unregister(fdesc)
        try:
            self._conndetails_by_fd[fdesc].connection.shutdown(
                socket.SHUT_RDWR
            )
        except socket.error as serr:
            if serr.errno != errno.ENOTCONN:
                raise
                # Else, client already closed the connection.
        self._conndetails_by_fd[fdesc].connection.close()

        name = self._conndetails_by_fd[fdesc].name
        del self._conndetails_by_fd[fdesc]
        if name in self._conndetails_by_name:
            del self._conndetails_by_name[name] 
Example #11
Source File: linux.py    From wstan with MIT License 6 votes vote down vote up
def _sock_connect_tfo(self, fut, sock, address, dat):
        fd = sock.fileno()
        try:
            sent = sock.sendto(dat, MSG_FASTOPEN, address)
        except (BlockingIOError, InterruptedError):
            # no data sent! deal with it using sock_sendall
            # happen when fallback to 3-way handshake
            fut.add_done_callback(lambda _: self.remove_writer(fd))
            self.add_writer(fd, self._sock_connect_tfo_cb, fut, sock, address, dat)
        except Exception as exc:
            if isinstance(exc, OSError) and exc.errno == errno.ENOTCONN:
                fut.set_exception(RuntimeError('TCP Fast Open unavailable'))
            else:
                fut.set_exception(exc)
        else:
            if sent == len(dat):
                fut.set_result(None)
            else:
                # meaningless because too large data can't fit into the TCP SYN packet
                # or will it happen even when data can fit?
                # just keep consistency with fallback situation
                self._sock_sendall(fut, False, sock, dat[sent:]) 
Example #12
Source File: connection08.py    From qpid-python with Apache License 2.0 5 votes vote down vote up
def close(self):
    try:
      try:
        self.sock.shutdown(SHUT_RDWR)
      except socket.error, e:
        if (e.errno == errno.ENOTCONN):
          pass
        else:
          raise
    finally:
      self.sock.close() 
Example #13
Source File: smtpd.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def __init__(self, server, conn, addr, data_size_limit=DATA_SIZE_DEFAULT,
                 map=None):
        asynchat.async_chat.__init__(self, conn, map=map)
        self.smtp_server = server
        self.conn = conn
        self.addr = addr
        self.data_size_limit = data_size_limit
        self.received_lines = []
        self.smtp_state = self.COMMAND
        self.seen_greeting = ''
        self.mailfrom = None
        self.rcpttos = []
        self.received_data = ''
        self.fqdn = socket.getfqdn()
        self.num_bytes = 0
        try:
            self.peer = conn.getpeername()
        except OSError as err:
            # a race condition  may occur if the other end is closing
            # before we can get the peername
            self.close()
            if err.args[0] != errno.ENOTCONN:
                raise
            return
        print('Peer:', repr(self.peer), file=DEBUGSTREAM)
        self.push('220 %s %s' % (self.fqdn, __version__))
        self.set_terminator(b'\r\n')
        self.extended_smtp = False

    # properties for backwards-compatibility 
Example #14
Source File: imaplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def shutdown(self):
        """Close I/O established in "open"."""
        self.file.close()
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        except OSError as e:
            # The server might already have closed the connection
            if e.errno != errno.ENOTCONN:
                raise
        finally:
            self.sock.close() 
Example #15
Source File: ssl.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _check_connected(self):
        if not self._connected:
            # getpeername() will raise ENOTCONN if the socket is really
            # not connected; note that we can be connected even without
            # _connected being set, e.g. if connect() first returned
            # EAGAIN.
            self.getpeername() 
Example #16
Source File: test_selector_events.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test__sock_connect_cb_exception(self):
        f = asyncio.Future(loop=self.loop)
        sock = mock.Mock()
        sock.fileno.return_value = 10
        sock.getsockopt.return_value = errno.ENOTCONN

        self.loop.remove_writer = mock.Mock()
        self.loop._sock_connect_cb(f, sock, ('127.0.0.1', 8080))
        self.assertIsInstance(f.exception(), OSError) 
Example #17
Source File: message.py    From Flask-P2P with MIT License 5 votes vote down vote up
def proxy_protocol_access_check(self):
        # check in allow list
        if isinstance(self.unreader, SocketUnreader):
            try:
                remote_host = self.unreader.sock.getpeername()[0]
            except socket.error as e:
                if e.args[0] == ENOTCONN:
                    raise ForbiddenProxyRequest("UNKNOW")
                raise
            if ("*" not in self.cfg.proxy_allow_ips and
                    remote_host not in self.cfg.proxy_allow_ips):
                raise ForbiddenProxyRequest(remote_host) 
Example #18
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_do_handshake_enotconn(self):
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            with context.wrap_socket(socket.socket()) as sock:
                with self.assertRaises(OSError) as cm:
                    sock.do_handshake()
                self.assertEqual(cm.exception.errno, errno.ENOTCONN) 
Example #19
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_getpeercert_enotconn(self):
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            with context.wrap_socket(socket.socket()) as sock:
                with self.assertRaises(OSError) as cm:
                    sock.getpeercert()
                self.assertEqual(cm.exception.errno, errno.ENOTCONN) 
Example #20
Source File: test_socket.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def testRecvmsgEOF(self):
        try:
            super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF()
        except OSError as e:
            if e.errno != errno.ENOTCONN:
                raise
            self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876") 
Example #21
Source File: ascmini.py    From collection with MIT License 5 votes vote down vote up
def IsFastCGI (self):
        import socket, errno
        if 'fromfd' not in socket.__dict__:
            return False
        try:
            s = socket.fromfd(sys.stdin.fileno(), socket.AF_INET, 
                    socket.SOCK_STREAM)
            s.getpeername()
        except socket.error as err:
            if err.errno != errno.ENOTCONN: 
                return False
        return True 
Example #22
Source File: ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _check_connected(self):
        if not self._connected:
            # getpeername() will raise ENOTCONN if the socket is really
            # not connected; note that we can be connected even without
            # _connected being set, e.g. if connect() first returned
            # EAGAIN.
            self.getpeername() 
Example #23
Source File: imaplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def shutdown(self):
        """Close I/O established in "open"."""
        self.file.close()
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        except OSError as e:
            # The server might already have closed the connection
            if e.errno != errno.ENOTCONN:
                raise
        finally:
            self.sock.close() 
Example #24
Source File: tcprelay.py    From shadowsocksr with Apache License 2.0 5 votes vote down vote up
def _handle_stage_connecting(self, data):
        if self._is_local:
            data = self._protocol.client_pre_encrypt(data)
            data = self._encryptor.encrypt(data)
            data = self._obfs.client_encode(data)
        if data:
            self._data_to_write_to_remote.append(data)
        if self._is_local and not self._fastopen_connected and \
                self._config['fast_open']:
            # for sslocal and fastopen, we basically wait for data and use
            # sendto to connect
            try:
                # only connect once
                self._fastopen_connected = True
                remote_sock = \
                    self._create_remote_socket(self._chosen_server[0],
                                               self._chosen_server[1])
                self._loop.add(remote_sock, eventloop.POLL_ERR, self._server)
                data = b''.join(self._data_to_write_to_remote)
                l = len(data)
                s = remote_sock.sendto(data, MSG_FASTOPEN, self._chosen_server)
                if s < l:
                    data = data[s:]
                    self._data_to_write_to_remote = [data]
                else:
                    self._data_to_write_to_remote = []
                self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
            except (OSError, IOError) as e:
                if eventloop.errno_from_exception(e) == errno.EINPROGRESS:
                    # in this case data is not sent at all
                    self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
                elif eventloop.errno_from_exception(e) == errno.ENOTCONN:
                    logging.error('fast open not supported on this OS')
                    self._config['fast_open'] = False
                    self.destroy()
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc()
                    self.destroy() 
Example #25
Source File: fcgi.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def _setupSocket(self):
        if self._bindAddress is None: # Run as a normal FastCGI?

            sock = socket.fromfd(FCGI_LISTENSOCK_FILENO, socket.AF_INET,
                                 socket.SOCK_STREAM)
            try:
                sock.getpeername()
            except socket.error, e:
                if e[0] != errno.ENOTCONN:
                    raise 
Example #26
Source File: ssl.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, sock, keyfile=None, certfile=None,
                 server_side=False, cert_reqs=CERT_NONE,
                 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
                 do_handshake_on_connect=True,
                 suppress_ragged_eofs=True, ciphers=None):
        socket.__init__(self, _sock=sock._sock)
        # The initializer for socket overrides the methods send(), recv(), etc.
        # in the instancce, which we don't need -- but we want to provide the
        # methods defined in SSLSocket.
        for attr in _delegate_methods:
            try:
                delattr(self, attr)
            except AttributeError:
                pass

        if ciphers is None and ssl_version != _SSLv2_IF_EXISTS:
            ciphers = _DEFAULT_CIPHERS

        if certfile and not keyfile:
            keyfile = certfile
        # see if it's connected
        try:
            socket.getpeername(self)
        except socket_error, e:
            if e.errno != errno.ENOTCONN:
                raise
            # no, no connection yet
            self._connected = False
            self._sslobj = None 
Example #27
Source File: link.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def close(self):
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        except socket.error as exc:
            if exc.errno not in (errno.ENOTCONN, errno.ECONNRESET):
                raise
        self.sock.close()
        if self.is_connector:
            self.reset()
            # closed socket cannot be reconnected so a new one must be created
            self.sock = self.create_socket()

    ######################################################### 
Example #28
Source File: link.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def send(self, conn_id, data):
        """
        After calling `send` wait for :py:attr:`~.on_ready_to_send` before
        sending next data.

        This operation is non-blocking, data might be lost if you close
        connection before proper delivery. Always wait for
        :py:attr:`~.on_ready_to_send` to have confirmation about successful
        send and information about amount of sent data.

        Do not feed this method with large bulks of data in MS Windows. It
        sometimes blocks for a little time even in non-blocking mode.

        Optimal data size is 16k-64k.
        """
        try:
            sock = self._sock_by_conn[conn_id]
            sock.send(data)
            self.poller.modify(sock, select.EPOLLIN | select.EPOLLOUT)
        except socket.error as exc:
            err = exc.args[0]
            if err == errno.EWOULDBLOCK:
                pass # ignore it, make caller to wait for "ready to send"
            elif err in (errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN,
                        errno.ECONNABORTED, errno.EPIPE, errno.EBADF):
                self.handle_close(sock)
            else:
                raise

    ########################################################## 
Example #29
Source File: link.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def handle_recv(self, sock):
        conn_id = sock.conn_id
        if conn_id is None:
            # socket could be closed in one poll round before recv
            return

        # do not put it in a draining cycle to avoid other links starvation
        try:
            fragment = sock.recv(self.recv_block_size)
        except ssl.SSLError as exc:
            if exc.args[0] != ssl.SSL_ERROR_WANT_READ:
                raise
            # wait for next round, SSL context has not enough data do decrypt
        except socket.error as exc:
            # TODO catch SSL exceptions
            err = exc.args[0]
            if err in (errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN,
                        errno.ECONNABORTED, errno.EPIPE, errno.EBADF):
                self.log.error("recv %s error %s" %
                                  (conn_id, errno.errorcode[err]))
                self.handle_close(sock)
            elif err != errno.EWOULDBLOCK:
                raise
        else:
            if fragment:
                self.log.debug("recv %s len=%i" % (conn_id, len(fragment)))
                self.on_recv(conn_id, fragment)
            else:
                self.handle_close(sock)

    ########################################################## 
Example #30
Source File: ssl.py    From Imogen with MIT License 5 votes vote down vote up
def _check_connected(self):
        if not self._connected:
            # getpeername() will raise ENOTCONN if the socket is really
            # not connected; note that we can be connected even without
            # _connected being set, e.g. if connect() first returned
            # EAGAIN.
            self.getpeername()