示例#1
0
def tcp_connect(address, ssl=True, tracefile=None):
    '''
    Example connection function.
    '''
    if isinstance(address, basestring):
        address = (str(address), IANA_TCP_PORT)
    else:
        assert len(address) == 2
        address = (str(address[0]), int(address[1]))

    # Lookup addresses
    addresses = socket.getaddrinfo(address[0], address[1])
    addresses = [i for i in addresses if (i[0] == socket.AF_INET or i[0] == socket.AF_INET6) and i[1] == socket.SOCK_STREAM]
    addresses.sort(key=lambda x: x[0], reverse=True)  # AF_INET6 sorts before AF_INET

    for address in addresses:  # should be nonempty, or we have a previous gaierror
        try:
            sock = socket.socket(*address[0:3])
            if ssl:
                ssl_sock = ssl_socket(sock)  # skip certificate checks
                ssl_sock.connect(address[4])
                sock = ssl_sock
            break
        except:
            exc_info = sys.exc_info()
            pass
    else:
        # Re-raise exception
        raise exc_info[1], None, exc_info[2]

    return wrap_socket(sock, tracefile=tracefile)
示例#2
0
    def connect(self, path, secure=False, **kwargs):
        self.path = path
        self.secure = secure

        if self.secure:
            self.certfile = kwargs.get("certfile", None)
            self.keyfile = kwargs.get("keyfile", None)

        try:
            r = self._sock.connect_ex(path)
        except SocketError as e:
            r = e.args[0]

        if r:
            if r in (EISCONN, EWOULDBLOCK, EINPROGRESS, EALREADY):
                self._connected = True
            else:
                self.fire(error(r))
                return

        self._connected = True

        self._poller.addReader(self, self._sock)

        if self.secure:
            self._ssock = ssl_socket(
                self._sock, self.keyfile, self.certfile,
                do_handshake_on_connect=False
            )
            _do_handshake_for_non_blocking(self._ssock)

        self.fire(connected(gethostname(), path))
示例#3
0
    def connect(self, path, secure=False, **kwargs):
        self.path = path
        self.secure = secure

        if self.secure:
            self.certfile = kwargs.get("certfile", None)
            self.keyfile = kwargs.get("keyfile", None)

        try:
            r = self._sock.connect_ex(path)
        except SocketError as e:
            r = e.args[0]

        if r:
            if r in (EISCONN, EWOULDBLOCK, EINPROGRESS, EALREADY):
                self._connected = True
            else:
                self.fire(error(r))
                return

        self._connected = True

        self._poller.addReader(self, self._sock)

        if self.secure:
            self._ssock = ssl_socket(self._sock,
                                     self.keyfile,
                                     self.certfile,
                                     do_handshake_on_connect=False)
            _do_handshake_for_non_blocking(self._ssock)

        self.fire(connected(gethostname(), path))
示例#4
0
    def _accept(self):  # noqa
        # XXX: C901: This has a high McCacbe complexity score of 10.
        # TODO: Refactor this!

        def on_done(sock, host):
            sock.setblocking(False)
            self._poller.addReader(self, sock)
            self._clients.append(sock)
            self.fire(connect(sock, *host))

        def on_error(sock, err):
            self.fire(error(sock, err))
            self._close(sock)

        try:
            newsock, host = self._sock.accept()
        except SocketError as e:
            if e.args[0] in (EWOULDBLOCK, EAGAIN):
                return
            elif e.args[0] == EPERM:
                # Netfilter on Linux may have rejected the
                # connection, but we get told to try to accept()
                # anyway.
                return
            elif e.args[0] in (EMFILE, ENOBUFS, ENFILE, ENOMEM, ECONNABORTED):
                # Linux gives EMFILE when a process is not allowed
                # to allocate any more file descriptors.  *BSD and
                # Win32 give (WSA)ENOBUFS.  Linux can also give
                # ENFILE if the system is out of inodes, or ENOMEM
                # if there is insufficient memory to allocate a new
                # dentry.  ECONNABORTED is documented as possible on
                # both Linux and Windows, but it is not clear
                # whether there are actually any circumstances under
                # which it can happen (one might expect it to be
                # possible if a client sends a FIN or RST after the
                # server sends a SYN|ACK but before application code
                # calls accept(2), however at least on Linux this
                # _seems_ to be short-circuited by syncookies.
                return
            else:
                raise

        if self.secure and HAS_SSL:
            sslsock = ssl_socket(newsock,
                                 server_side=True,
                                 keyfile=self.keyfile,
                                 ca_certs=self.ca_certs,
                                 certfile=self.certfile,
                                 cert_reqs=self.cert_reqs,
                                 ssl_version=self.ssl_version,
                                 do_handshake_on_connect=False)

            for _ in do_handshake(sslsock,
                                  on_done,
                                  on_error,
                                  extra_args=(host, )):
                yield
        else:
            on_done(newsock, host)
示例#5
0
    def connect(self, host, port, secure=False, **kwargs):
        # XXX: C901: This has a high McCacbe complexity score of 10.
        # TODO: Refactor this!

        self.host = host
        self.port = port
        self.secure = secure

        if self.secure:
            self.certfile = kwargs.get("certfile", None)
            self.keyfile = kwargs.get("keyfile", None)
            self.ca_certs = kwargs.get("ca_certs", None)

        try:
            r = self._sock.connect((host, port))
        except SocketError as e:
            if e.args[0] in (EBADF, EINVAL,):
                self._sock = self._create_socket()
                r = self._sock.connect_ex((host, port))
            else:
                r = e.args[0]

            if r not in (EISCONN, EWOULDBLOCK, EINPROGRESS, EALREADY):
                self.fire(unreachable(host, port, e))
                self.fire(error(e))
                self._close()
                return

        stop_time = time() + self.connect_timeout
        while time() < stop_time:
            try:
                self._sock.getpeername()
                self._connected = True
                break
            except Exception:
                yield

        if not self._connected:
            self.fire(unreachable(host, port))
            return

        def on_done(sock):
            self._poller.addReader(self, sock)
            self.fire(connected(host, port))

        if self.secure:
            def on_error(sock, err):
                self.fire(error(sock, err))
                self._close()

            self._sock = ssl_socket(
                self._sock, self.keyfile, self.certfile, ca_certs=self.ca_certs,
                do_handshake_on_connect=False
            )
            for _ in do_handshake(self._sock, on_done, on_error):
                yield
        else:
            on_done(self._sock)
示例#6
0
    def _accept(self):  # noqa
        # XXX: C901: This has a high McCacbe complexity score of 10.
        # TODO: Refactor this!

        def on_done(sock, host):
            sock.setblocking(False)
            self._poller.addReader(self, sock)
            self._clients.append(sock)
            self.fire(connect(sock, *host))

        def on_error(sock, err):
            self.fire(error(sock, err))
            self._close(sock)

        try:
            newsock, host = self._sock.accept()
        except SocketError as e:
            if e.args[0] in (EWOULDBLOCK, EAGAIN):
                return
            elif e.args[0] == EPERM:
                # Netfilter on Linux may have rejected the
                # connection, but we get told to try to accept()
                # anyway.
                return
            elif e.args[0] in (EMFILE, ENOBUFS, ENFILE, ENOMEM, ECONNABORTED):
                # Linux gives EMFILE when a process is not allowed
                # to allocate any more file descriptors.  *BSD and
                # Win32 give (WSA)ENOBUFS.  Linux can also give
                # ENFILE if the system is out of inodes, or ENOMEM
                # if there is insufficient memory to allocate a new
                # dentry.  ECONNABORTED is documented as possible on
                # both Linux and Windows, but it is not clear
                # whether there are actually any circumstances under
                # which it can happen (one might expect it to be
                # possible if a client sends a FIN or RST after the
                # server sends a SYN|ACK but before application code
                # calls accept(2), however at least on Linux this
                # _seems_ to be short-circuited by syncookies.
                return
            else:
                raise

        if self.secure and HAS_SSL:
            sslsock = ssl_socket(
                newsock,
                server_side=True,
                keyfile=self.keyfile,
                ca_certs=self.ca_certs,
                certfile=self.certfile,
                cert_reqs=self.cert_reqs,
                ssl_version=self.ssl_version,
                do_handshake_on_connect=False
            )

            for _ in do_handshake(sslsock, on_done, on_error, extra_args=(host,)):
                yield
        else:
            on_done(newsock, host)
示例#7
0
    def connect(self, host, port, secure=False, **kwargs):
        # XXX: C901: This has a high McCacbe complexity score of 10.
        # TODO: Refactor this!

        self.host = host
        self.port = port
        self.secure = secure

        if self.secure:
            self.certfile = kwargs.get("certfile", None)
            self.keyfile = kwargs.get("keyfile", None)
            self.ca_certs = kwargs.get("ca_certs", None)

        try:
            r = self._sock.connect((host, port))
        except SocketError as e:
            if e.args[0] in (EBADF, EINVAL,):
                self._sock = self._create_socket()
                r = self._sock.connect_ex((host, port))
            else:
                r = e.args[0]

            if r not in (EISCONN, EWOULDBLOCK, EINPROGRESS, EALREADY):
                self.fire(unreachable(host, port, e))
                self.fire(error(e))
                self._close()
                raise StopIteration()

        stop_time = time() + self.connect_timeout
        while time() < stop_time:
            try:
                self._sock.getpeername()
                self._connected = True
                break
            except Exception as e:
                yield

        if not self._connected:
            self.fire(unreachable(host, port))
            raise StopIteration()

        def on_done(sock):
            self._poller.addReader(self, sock)
            self.fire(connected(host, port))

        if self.secure:
            def on_error(sock, err):
                self.fire(error(sock, err))
                self._close()

            self._sock = ssl_socket(
                self._sock, self.keyfile, self.certfile, ca_certs=self.ca_certs,
                do_handshake_on_connect=False
            )
            for _ in do_handshake(self._sock, on_done, on_error):
                yield
        else:
            on_done(self._sock)
示例#8
0
    def _do_handshake(self, sock, fire_connect_event=True):
        sslsock = ssl_socket(
            sock,
            server_side=True,
            keyfile=self.keyfile,
            ca_certs=self.ca_certs,
            certfile=self.certfile,
            cert_reqs=self.cert_reqs,
            ssl_version=self.ssl_version,
            do_handshake_on_connect=False
        )

        for _ in do_handshake(sslsock, self._on_accept_done, self._on_handshake_error, (fire_connect_event,)):
            yield _
示例#9
0
    def _do_handshake(self, sock, fire_connect_event=True):
        sslsock = ssl_socket(
            sock,
            server_side=True,
            keyfile=self.keyfile,
            ca_certs=self.ca_certs,
            certfile=self.certfile,
            cert_reqs=self.cert_reqs,
            ssl_version=self.ssl_version,
            do_handshake_on_connect=False
        )

        for _ in do_handshake(sslsock, self._on_accept_done, self._on_handshake_error, (fire_connect_event,)):
            yield _
示例#10
0
    def connect(self, host, port, secure=False, **kwargs):
        self.host = host
        self.port = port
        self.secure = secure

        if self.secure:
            self.certfile = kwargs.get("certfile", None)
            self.keyfile = kwargs.get("keyfile", None)

        try:
            r = self._sock.connect((host, port))
        except SocketError as e:
            if e.args[0] in (
                    EBADF,
                    EINVAL,
            ):
                self._sock = self._create_socket()
                r = self._sock.connect_ex((host, port))
            else:
                r = e.args[0]

            if r not in (EISCONN, EWOULDBLOCK, EINPROGRESS, EALREADY):
                self.fire(unreachable(host, port, e))
                self.fire(error(e))
                self._close()
                raise StopIteration

        stop_time = time() + self.connect_timeout
        while time() < stop_time:
            try:
                self._sock.getpeername()
                self._connected = True
                break
            except Exception as e:
                yield

        if not self._connected:
            self.fire(unreachable(host, port))
            raise StopIteration

        self._poller.addReader(self, self._sock)
        if self.secure:
            self._sock = ssl_socket(self._sock,
                                    self.keyfile,
                                    self.certfile,
                                    do_handshake_on_connect=False)
            _do_handshake_for_non_blocking(self._sock)

        self.fire(connected(host, port))
示例#11
0
    def connect(self, host, port, secure=False, **kwargs):
        self.host = host
        self.port = port
        self.secure = secure

        if self.secure:
            self.certfile = kwargs.get("certfile", None)
            self.keyfile = kwargs.get("keyfile", None)

        try:
            r = self._sock.connect((host, port))
        except SocketError as e:
            if e.args[0] in (EBADF, EINVAL,):
                self._sock = self._create_socket()
                r = self._sock.connect_ex((host, port))
            else:
                r = e.args[0]

            if r not in (EISCONN, EWOULDBLOCK, EINPROGRESS, EALREADY):
                self.fire(unreachable(host, port, e))
                self.fire(error(e))
                self._close()
                raise StopIteration

        stop_time = time() + self.connect_timeout
        while time() < stop_time:
            try:
                self._sock.getpeername()
                self._connected = True
                break
            except Exception as e:
                yield

        if not self._connected:
            self.fire(unreachable(host, port))
            raise StopIteration

        self._poller.addReader(self, self._sock)
        if self.secure:
            self._sock = ssl_socket(
                self._sock, self.keyfile, self.certfile,
                do_handshake_on_connect=False
            )
            _do_handshake_for_non_blocking(self._sock)

        self.fire(connected(host, port))
示例#12
0
    def connect(self, path, secure=False, **kwargs):
        # XXX: C901: This has a high McCacbe complexity score of 10.
        # TODO: Refactor this!

        self.path = path
        self.secure = secure

        if self.secure:
            self.certfile = kwargs.get("certfile", None)
            self.keyfile = kwargs.get("keyfile", None)
            self.ca_certs = kwargs.get("ca_certs", None)

        try:
            r = self._sock.connect_ex(path)
        except SocketError as e:
            r = e.args[0]

        if r:
            if r in (EISCONN, EWOULDBLOCK, EINPROGRESS, EALREADY):
                self._connected = True
            else:
                self.fire(error(r))
                return

        self._connected = True

        self._poller.addReader(self, self._sock)

        if self.secure:

            def on_done(sock):
                self.fire(connected(gethostname(), path))

            def on_error(sock, err):
                self.fire(error(err))

            self._ssock = ssl_socket(self._sock,
                                     self.keyfile,
                                     self.certfile,
                                     ca_certs=self.ca_certs,
                                     do_handshake_on_connect=False)
            for _ in do_handshake(self._ssock, on_done, on_error):
                yield
        else:
            self.fire(connected(gethostname(), path))
示例#13
0
    def connect(self, path, secure=False, **kwargs):
        # XXX: C901: This has a high McCacbe complexity score of 10.
        # TODO: Refactor this!

        self.path = path
        self.secure = secure

        if self.secure:
            self.certfile = kwargs.get("certfile", None)
            self.keyfile = kwargs.get("keyfile", None)
            self.ca_certs = kwargs.get("ca_certs", None)

        try:
            r = self._sock.connect_ex(path)
        except SocketError as e:
            r = e.args[0]

        if r:
            if r in (EISCONN, EWOULDBLOCK, EINPROGRESS, EALREADY):
                self._connected = True
            else:
                self.fire(error(r))
                return

        self._connected = True

        self._poller.addReader(self, self._sock)

        if self.secure:
            def on_done(sock):
                self.fire(connected(gethostname(), path))

            def on_error(sock, err):
                self.fire(error(err))

            self._ssock = ssl_socket(
                self._sock, self.keyfile, self.certfile, ca_certs=self.ca_certs,
                do_handshake_on_connect=False
            )
            for _ in do_handshake(self._ssock, on_done, on_error):
                yield
        else:
            self.fire(connected(gethostname(), path))