Exemple #1
0
    def recv(self, n, encoding="unicode", timeout=5):
        # Sanity checking.
        assert n

        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        try:
            # Get data.
            self.get_chunks(n, encoding=encoding)

            # Return the current buffer.
            ret = self.buf

            # Reset the old buffer.
            self.buf = b""

            # Return results.
            if encoding == "unicode":
                ret = encode_str(ret, encoding)

            return ret
        except Exception as e:
            self.debug_print("Recv closign e" + str(e))
            error = parse_exception(e)
            log_exception(error_log_path, error)
            self.close()
            if encoding == "unicode":
                return u""
            else:
                return b""
Exemple #2
0
    def connect(self, addr, port):
        # Save addr and port so socket can be reconnected.
        self.addr = addr
        self.port = port

        # No socket detected.
        if self.s is None:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            if self.use_ssl:
                self.s = ssl.wrap_socket(self.s)

        # Make connection from custom interface.
        if self.interface != "default":
            try:
                # Todo: fix this to use static ips from Net
                src_ip = get_lan_ip(self.interface)
                self.s.bind((src_ip, 0))
            except socket.error as e:
                if e.errno != 98:
                    raise e

        try:
            self.s.connect((addr, int(port)))
            self.connected = 1
            self.set_blocking(self.blocking, self.timeout)
        except Exception as e:
            self.debug_print("Connect failed")
            error = parse_exception(e)
            self.debug_print(error)
            log_exception(error_log_path, error)
            raise socket.error("Socket connect failed.")
Exemple #3
0
    def connect(self, addr, port):
        # Save addr and port so socket can be reconnected.
        self.addr = addr
        self.port = port

        # No socket detected.
        if self.s is None:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            if self.use_ssl:
                self.s = ssl.wrap_socket(self.s)

        # Make connection from custom interface.
        if self.interface != "default":
            try:
                # Todo: fix this to use static ips from Net
                src_ip = get_lan_ip(self.interface)
                self.s.bind((src_ip, 0))
            except socket.error as e:
                if e.errno != 98:
                    raise e

        try:
            self.debug_print(addr)
            self.debug_print(port)
            self.s.connect((addr, int(port)))
            self.connected = 1
            self.set_blocking(self.blocking, self.timeout)
        except Exception as e:
            self.debug_print("Connect failed")
            error = parse_exception(e)
            self.debug_print(error)
            log_exception(error_log_path, error)
            raise socket.error("Socket connect failed.")
    def recv(self, n, encoding="unicode", timeout=5):
        # Sanity checking.
        assert n

        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        try:
            # Get data.
            self.get_chunks(n, encoding=encoding)

            # Return the current buffer.
            ret = self.buf

            # Reset the old buffer.
            self.buf = b""

            # Return results.
            if encoding == "unicode":
                ret = encode_str(ret, encoding)

            return ret
        except Exception as e:
            self.debug_print("Recv closign e" + str(e))
            error = parse_exception(e)
            log_exception(error_log_path, error)
            self.close()
            if encoding == "unicode":
                return u""
            else:
                return b""
Exemple #5
0
    def send_line(self, msg, timeout=5):
        # Sanity checking.
        assert (len(msg))

        # Not connected.
        if not self.connected:
            return 0

        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        # Check socket is in correct blocking mode.
        if self.debug:
            blocking = self.s.gettimeout()
            if self.blocking:
                assert (blocking >= 1 or blocking is None)
            else:
                assert (blocking == 0.0)

        try:
            # Convert to bytes Python 2 & 3
            if sys.version_info >= (3, 0, 0):
                if type(msg) == str:
                    msg = msg.encode("ascii")
            else:
                if type(msg) == unicode:
                    msg = str(msg)

            # Convert delimiter to bytes.
            if sys.version_info >= (3, 0, 0):
                msg += self.delimiter.encode("ascii")
            else:
                msg += str(self.delimiter)

            """
            The inclusion of the send_all flag makes this function behave like
            a blocking socket for the purposes of sending a full line even if
            the socket is non-blocking. It's assumed that lines will be small
            and if the network buffer is full this code won't end up as a
            bottleneck. (Otherwise you would have to check the number of bytes
            returned every time you sent a line which is quite annoying.)
            """
            ret = self.send(msg, send_all=1, timeout=timeout)

            return ret
        except Exception as e:
            self.debug_print("Send line closing" + str(e))
            error = parse_exception(e)
            log_exception(error_log_path, error)
            self.close()
            return 0
Exemple #6
0
    def recv_line(self, timeout=5):
        # Socket is disconnected.
        if not self.connected:
            return u""

        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        # Return existing reply.
        if len(self.replies):
            temp = self.replies[0]
            self.replies = self.replies[1:]
            return temp

        try:
            future = time.time() + (timeout or self.timeout)
            while True:
                self.update()

                # Socket is disconnected.
                if not self.connected:
                    return u""

                # Non-blocking.
                if not ((not len(self.replies) or len(
                        self.buf) >= self.max_buf) and self.blocking):
                    break

                # Timeout elapsed.
                if time.time() >= future and self.blocking:
                    break

                # Avoid 100% CPU.
                time.sleep(0.002)

            if len(self.replies):
                temp = self.replies[0]
                self.replies = self.replies[1:]
                return temp

            return u""
        except Exception as e:
            self.debug_print("recv line error")
            error = parse_exception(e)
            self.debug_print(error)
            log_exception(error_log_path, error)
    def recv_line(self, timeout=5):
        # Socket is disconnected.
        if not self.connected:
            return u""

        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        # Return existing reply.
        if len(self.replies):
            temp = self.replies[0]
            self.replies = self.replies[1:]
            return temp

        try:
            future = time.time() + (timeout or self.timeout)
            while True:
                self.update()

                # Socket is disconnected.
                if not self.connected:
                    return u""

                # Non-blocking.
                if not ((not len(self.replies)
                         or len(self.buf) >= self.max_buf) and self.blocking):
                    break

                # Timeout elapsed.
                if time.time() >= future and self.blocking:
                    break

                # Avoid 100% CPU.
                time.sleep(0.002)

            if len(self.replies):
                temp = self.replies[0]
                self.replies = self.replies[1:]
                return temp

            return u""
        except Exception as e:
            self.debug_print("recv line error")
            error = parse_exception(e)
            self.debug_print(error)
            log_exception(error_log_path, error)
Exemple #8
0
    def send(self, msg, send_all=0, timeout=5, encoding="ascii"):
        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        try:
            # Convert to bytes Python 2 & 3
            # The caller should ensure correct encoding.
            if type(msg) == type(u""):
                msg = encode_str(msg, "ascii")

            # Work out stop time.
            if send_all:
                future = time.time() + (timeout or self.timeout)
            else:
                future = 0

            repeat = 1
            total_sent = 0
            msg_len = len(msg)
            while repeat:
                repeat = 0
                while True:
                    # Attempt to send all.
                    # This won't work if the network buffer is already full.
                    try:
                        bytes_sent = self.s.send(
                                msg[total_sent:self.chunk_size])
                    except socket.timeout as e:
                        err = e.args[0]
                        if err == "timed out":
                            return 0
                    except socket.error as e:
                        err = e.args[0]
                        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
                            break
                        else:
                            # Connection closed or other problem.
                            self.debug_print("Con send closing other")
                            self.close()
                            return 0

                    # Connection broken.
                    if not bytes_sent or bytes_sent is None:
                        self.close()
                        return 0

                    # How much has been sent?
                    total_sent += bytes_sent

                    # Avoid looping forever.
                    if self.blocking and not send_all:
                        break

                    # Everything sent.
                    if total_sent >= msg_len:
                        break

                    # Don't block.
                    if not send_all:
                        break

                    # Avoid 100% CPU.
                    time.sleep(0.001)

                # Avoid looping forever.
                if send_all:
                    if time.time() >= future:
                        repeat = 0
                        break

                # Send the rest if blocking:
                if total_sent < msg_len and send_all:
                    repeat = 1

            return total_sent
        except Exception as e:
            self.debug_print("Con send: " + str(e))
            error = parse_exception(e)
            log_exception(error_log_path, error)
            self.close()
Exemple #9
0
    def recv(self, n, encoding="unicode", timeout=5):
        # Sanity checking.
        assert n

        # Disconnect.
        if not self.connected:
            if encoding == "unicode":
                return u""
            else:
                return b""

        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        # Check socket is in correct blocking mode.
        if self.debug:
            blocking = self.s.gettimeout()
            if self.blocking:
                assert (blocking >= 1 or blocking is None)
            else:
                assert (blocking == 0.0)

        try:
            # Save current buffer state.
            temp_buf = self.buf[:]

            # Clear buffer.
            self.buf = u""

            # Get data.
            future = time.time() + (timeout or self.timeout)
            while True:
                self.get_chunks(n, encoding=encoding)
                if not (len(self.buf) < n and self.connected and self.blocking):
                    break

                # Avoid 100% CPU.
                time.sleep(0.002)

                # Avoid looping forever.
                if time.time() >= future:
                    break

            # Save current buffer.
            ret = self.buf[:]

            # Restore old buffer.
            self.buf = temp_buf

            # Return results.
            if encoding != "unicode":
                # Convert from unicode string with latin-1 encoding
                # To a byte string.
                if sys.version_info >= (3, 0, 0):
                    codes = []
                    for ch in ret:
                        codes.append(ord(ch))

                    if len(codes):
                        return bytes(codes)
                    else:
                        return b""
                else:
                    byte_str = b""
                    for ch in ret:
                        byte_str += chr(ord(ch))

                    return byte_str

            return ret
        except Exception as e:
            self.debug_print("Recv closign e" + str(e))
            error = parse_exception(e)
            log_exception(error_log_path, error)
            self.close()
            if encoding == "unicode":
                return u""
            else:
                return b""
Exemple #10
0
    def send(self, msg, send_all=0, timeout=5):
        # Sanity check.
        assert (len(msg))
        # Not connected.
        if not self.connected:
            return 0

        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        # Check socket is in correct blocking mode.
        if self.debug:
            blocking = self.s.gettimeout()
            if self.blocking:
                assert (blocking >= 1 or blocking is None)
            else:
                assert (blocking == 0.0)

        try:
            # Convert to bytes Python 2 & 3
            if sys.version_info >= (3, 0, 0):
                if type(msg) == str:
                    msg = msg.encode("ascii")
            else:
                if type(msg) == unicode:
                    msg = str(msg)

            repeat = 1
            total_sent = 0
            future = time.time() + (timeout or self.timeout)
            while repeat:
                repeat = 0
                while True:
                    # Attempt to send all.
                    # This won't work if the network buffer is already full.
                    try:
                        self.debug_print("Attempting to send: ")
                        self.debug_print(
                                str(len(msg[total_sent:self.chunk_size])))
                        self.debug_print(
                                "Blocking mode = " + str(self.s.gettimeout()))
                        bytes_sent = self.s.send(
                                msg[total_sent:self.chunk_size])
                    except socket.timeout as e:
                        err = e.args[0]
                        self.debug_print("Con send: " + str(e))
                        self.debug_print(err)
                        if err == "timed out":
                            return 0
                    except socket.error as e:
                        err = e.args[0]
                        self.debug_print("Con send: " + str(e))
                        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
                            break
                        else:
                            # Connection closed or other problem.
                            self.debug_print("Con send closing other")
                            self.close()
                            return 0

                    # Connection broken.
                    if not bytes_sent or bytes_sent is None:
                        self.debug_print(bytes_sent)
                        self.debug_print("Con send bytes none!")
                        self.close()
                        return 0

                    # How much has been sent?
                    total_sent += bytes_sent

                    # Avoid looping forever.
                    if self.blocking and not send_all:
                        break

                    # Everything sent.
                    if total_sent >= len(msg):
                        break

                    # Don't block.
                    if not send_all:
                        break

                    # Avoid 100% CPU.
                    time.sleep(0.002)

                # Avoid looping forever.
                if time.time() >= future:
                    repeat = 0
                    break

                # Send the rest if blocking:
                if total_sent < len(msg) and send_all:
                    repeat = 1

            self.alive = time.time()
            return total_sent
        except Exception as e:
            self.debug_print("Con send: " + str(e))
            error = parse_exception(e)
            log_exception(error_log_path, error)
            self.close()
    def send(self, msg, send_all=0, timeout=5, encoding="ascii"):
        # Update timeout.
        if timeout != self.timeout and self.blocking:
            self.set_blocking(self.blocking, timeout)

        try:
            # Convert to bytes Python 2 & 3
            # The caller should ensure correct encoding.
            if type(msg) == type(u""):
                msg = encode_str(msg, "ascii")

            # Work out stop time.
            if send_all:
                future = time.time() + (timeout or self.timeout)
            else:
                future = 0

            repeat = 1
            total_sent = 0
            msg_len = len(msg)
            while repeat:
                repeat = 0
                while True:
                    # Attempt to send all.
                    # This won't work if the network buffer is already full.
                    try:
                        bytes_sent = self.s.send(
                            msg[total_sent:self.chunk_size])
                    except socket.timeout as e:
                        err = e.args[0]
                        if err == "timed out":
                            return 0
                    except socket.error as e:
                        err = e.args[0]
                        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
                            break
                        else:
                            # Connection closed or other problem.
                            self.debug_print("Con send closing other")
                            self.close()
                            return 0

                    # Connection broken.
                    if not bytes_sent or bytes_sent is None:
                        self.close()
                        return 0

                    # How much has been sent?
                    total_sent += bytes_sent

                    # Avoid looping forever.
                    if self.blocking and not send_all:
                        break

                    # Everything sent.
                    if total_sent >= msg_len:
                        break

                    # Don't block.
                    if not send_all:
                        break

                    # Avoid 100% CPU.
                    time.sleep(0.001)

                # Avoid looping forever.
                if send_all:
                    if time.time() >= future:
                        repeat = 0
                        break

                # Send the rest if blocking:
                if total_sent < msg_len and send_all:
                    repeat = 1

            return total_sent
        except Exception as e:
            self.debug_print("Con send: " + str(e))
            error = parse_exception(e)
            log_exception(error_log_path, error)
            self.close()