Esempio n. 1
0
def send(conn, addr, ms):
    user_to = recv_msg(conn).decode()
    context = recv_msg(conn).decode()
    user_from = get_user_by_addr(addr, USERS)

    if len(context) > MAX_MSG_LEN:
        send_msg(
            conn, "Massage is too long! Max length = {}!".format(
                MAX_MSG_LEN).encode())
        print(
            "[-] '{}'({}) sended message of length {}!".format(
                user_from, addr_to_str(addr)), len(context))
        return False

    if not user_from:
        send_msg(conn, b"U aren't registered!")
        print("[-] User isn't regitered!")
        return False

    if user_to not in USERS:
        send_msg(conn, "User '{}' doesn't exist!".format(user_to).encode())
        print("[-] There are not user '{}' in system!".format(user_to))
        return True

    ms.add_message(user_from, user_to, context)
    send_msg(conn, b"Message added to storage!")
    print("[+] Message ('{}') from '{}'({}) sent to '{}'".format(
        context, user_from, addr_to_str(addr), user_to))
    return True
Esempio n. 2
0
    def start(self, connections):
        with socket() as s:
            s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            s.bind(self.addr)
            s.listen(connections)

            print("[+] Server starts on {}".format(addr_to_str(self.addr)))
            while True:
                conn, addr = s.accept()
                conn.settimeout(10)
                print("[+] {} connected!".format(addr_to_str(addr)))
                thread = threading.Thread(target=handler,
                                          args=(conn, addr, self.ms))
                thread.daemon = True
                thread.start()
Esempio n. 3
0
def logout(conn, addr, ms):
    user = get_user_by_addr(addr, USERS)
    if user:
        del USERS[user]
    ms.get_messages_for_user(user)
    send_msg(conn, b"U've been successfully logouted")
    print("[+] {}({}) logouted".format(user, addr_to_str(addr)))
Esempio n. 4
0
def handler(conn, addr, ms):
    try:
        while True:
            msg = recv_msg(conn)
            print("[+] '{}' from {}".format(msg.decode(), addr_to_str(addr)))
            if msg == b"register":
                if not register(conn, addr):
                    break
            elif msg == b"users":
                get_users(conn, addr)
            elif msg == b"logout":
                logout(conn, addr, ms)
            elif msg == b"send":
                if not send(conn, addr, ms):
                    break
            elif msg == b"receive":
                receive(conn, addr, ms)
            elif msg == b"sendall":
                sendall(conn, addr, ms)
            else:
                break
    except error:
        print("[-] Can't read more from {}".format(addr))
    except Exception as ex:
        print("[-] Exception: {}".format(ex))
    finally:
        conn.close()
Esempio n. 5
0
    def tojson(self):
        etype = self.elem_type()
        j = {
            'start': addr_to_str(self.start),
            etype: [],
            'successors': [],
            'predecessors': []
        }

        for elem in self.elems:
            j[etype].append(elem.tojson())

        for succ in self.successors:
            j['successors'].append(addr_to_str(succ.start))

        for pred in self.predecessors:
            j['predecessors'].append(addr_to_str(pred.start))

        return j
Esempio n. 6
0
    def connectionLost(self, reason):
        """Event handler of losing the connection to the client.

        Call Control to handle it.
        """
        if self.authenticated:
            logging.info("client connection lost: " +
                         addr_to_str(self.transport.getPeer()))
        self.authenticated = False
        self.initiator.client_lost(self.i)
Esempio n. 7
0
    def connectionLost(self, reason):
        """Event handler of losing the connection to the client.

        Call Control to handle it.
        """
        if self.authenticated:
            logging.info("client connection lost: " +
                         addr_to_str(self.transport.getPeer()))
        self.authenticated = False
        self.initiator.client_lost(self)
Esempio n. 8
0
File: cfg.py Progetto: SamL98/MyDeco
    def tojson(self):
        j = {
                'entry': addr_to_str(self.entry.start),
                'blocks': {}
            }

        def convert_block_to_json(blk):
            j['blocks'][addr_to_str(blk.start)] = blk.tojson()

        self.dfs_(self.entry,
                  set(),
                  pre_fn=convert_block_to_json)

        return j
Esempio n. 9
0
    def tojson(self):
        j = {
                'id': id(self),
                'addr': addr_to_str(self.addr),
                'mnemonic': self.mnemonic,
                'inputs': []
            }

        for inpt in self.inputs:
            j['inputs'].append(inpt.tojson())

        if self.has_output():
            j['output'] = self.output.tojson()

        return j
Esempio n. 10
0
    def write(self, data, conn_id, index):
        """Encrypt and write data the client.

        Encrypted packets should be separated by split_char.
        Raw packet structure:
            type    (1 byte)   (0 for normal data packet)
            id      (2 bytes)
            index   (6 bytes)
            data
        """

        to_write = self.cipher.encrypt("0" + conn_id + index + data) +\
            self.split_char
        logging.debug("sending %d bytes to client %s with id %s" % (len(data),
                                                                    addr_to_str(
                                                                        self.transport.getPeer()),
                                                                    conn_id))
        self.transport.write(to_write)
Esempio n. 11
0
    def proxy_write(self, conn_id):
        """Forward all the data pending for the ID to the HTTP proxy."""

        while conn_id in self.proxy_write_queues and self.proxy_write_queues_index[conn_id] in self.proxy_write_queues[conn_id]:
            data = self.proxy_write_queues[conn_id].pop(
                self.proxy_write_queues_index[conn_id])
            self.next_write_index(conn_id)
            if data is not None and len(data) > 0:
                conn = self.proxy_connectors[conn_id]
                if not conn.transport:
                    self.proxy_lost(conn_id)
                else:
                    logging.debug("sending %d bytes to proxy %s from id %s" % (
                        len(data),
                        addr_to_str(conn.transport.getPeer()),
                        conn_id))
                    conn.transport.write(data)
        if self.proxy_write_queues_index[conn_id] + 7 in self.proxy_write_queues[conn_id]:
            logging.debug("lost frame in connection " + conn_id)
Esempio n. 12
0
    def write(self, data, conn_id, index):
        """Encrypt and write data the client.

        Encrypted packets should be separated by split_char.
        Raw packet structure:
            type    (1 byte)   (0 for normal data packet)
            id      (2 bytes)
            index   (6 bytes)
            data
        """
        if index < 100000:
            index = '0' * (6 - len(str(index))) + str(index)
        else:
            index = str(index)
        # get current time with base 36 as a string in a certain length .
        to_write = self.cipher.encrypt("0" + conn_id + index + data) +\
            self.split_char
        logging.debug(
            "sending %d bytes to client %s with id %s" %
            (len(data), addr_to_str(self.transport.getPeer()), conn_id))
        self.transport.write(to_write)
Esempio n. 13
0
def register(conn, addr):
    login = recv_msg(conn)

    try:
        login = login.decode()
    except Exception:
        send_msg(conn, b"Can't decode login!")
        print("[-] Can't decode login!")
        return False

    if not login:
        send_msg(conn, b"Bad login!")
        print("[-] ({}) empty login!".format(addr_to_str(addr)))
        return False

    if len(login) > MAX_USER_LEN:
        send_msg(conn, b"Login is too long!")
        print("[-] ({}) Username '{}' is greater then {} chars!".format(
            addr_to_str(addr), login, MAX_USER_LEN))
        return False

    if login not in USERS:
        if addr[0] not in USERS.values():
            USERS[login] = addr[0]
            send_msg(conn, "Hello, {}".format(login).encode())
            print("[+] '{}'({}) registered!".format(login, addr_to_str(addr)))
            return True
        else:
            user = get_user_by_addr(addr, USERS)
            send_msg(conn,
                     "{} was used before!".format(addr_to_str(addr)).encode())
            print("[-] '{}'({}) used address of {}!".format(
                login, addr_to_str(addr), user))
            return False
    elif USERS.get(login, "") == addr[0]:
        send_msg(conn, "Nice to see you, {}".format(login).encode())
        print("[+] '{}'({}) logined!".format(login, addr_to_str(addr)))
        return True
    else:
        send_msg(conn, "'{}' already exists!".format(login).encode())
        print("[-] '{}'({}) already exists!".format(login, addr_to_str(addr)))
        return False
Esempio n. 14
0
    def proxy_write(self, conn_id):
        """Forward all the data pending for the ID to the HTTP proxy."""

        while conn_id in self.proxy_write_queues_dict and self.proxy_write_queues_index_dict[conn_id] in self.proxy_write_queues_dict[conn_id]:
            data = self.proxy_write_queues_dict[conn_id].pop(
                self.proxy_write_queues_index_dict[conn_id])
            self.next_write_index(conn_id)
            if data is not None and len(data) > 0:
                conn = self.proxy_connectors_dict[conn_id]
                if not conn.transport:
                    self.proxy_lost(conn_id)
                else:
                    logging.debug("sending %d bytes to proxy %s from id %s" % (
                        len(data),
                        addr_to_str(conn.transport.getPeer()),
                        conn_id))
                    conn.transport.write(data)
            if self.proxy_write_queues_index_dict[conn_id] % self.req_num == 0:
                self.client_write(str(self.proxy_write_queues_index_dict[conn_id]),
                                  conn_id, 30)
        if self.proxy_write_queues_index_dict[conn_id] + 7 in self.proxy_write_queues_dict[conn_id]:
            logging.debug("lost frame in connection " + conn_id)
Esempio n. 15
0
    def write(self, data, conn_id, index):
        """Encrypt and write data the client.

        Encrypted packets should be separated by split_char.
        Raw packet structure:
            type    (1 byte)   (0 for normal data packet)
            id      (2 bytes)
            index   (6 bytes)
            data
        """
        if index < 100000:
            index = '0' * (6 - len(str(index))) + str(index)
        else:
            index = str(index)
        # get current time with base 36 as a string in a certain length .
        to_write = self.cipher.encrypt("0" + conn_id + index + data) +\
            self.split_char
        logging.debug("sending %d bytes to client %s with id %s" % (len(data),
                                                                    addr_to_str(
                                                                        self.transport.getPeer()),
                                                                    conn_id))
        self.transport.write(to_write)
Esempio n. 16
0
File: cfg.py Progetto: SamL98/MyDeco
 def convert_block_to_json(blk):
     j['blocks'][addr_to_str(blk.start)] = blk.tojson()
Esempio n. 17
0
 def connectionMade(self):
     """Event handler of being successfully connected to the client."""
     logging.info("connected to client " +
                  addr_to_str(self.transport.getPeer()))
     self.transport.write(self.generate_auth_msg() + self.split_char)
Esempio n. 18
0
 def connectionMade(self):
     """Event handler of being successfully connected to the client."""
     logging.info("connected to client " +
                  addr_to_str(self.transport.getPeer()))
     self.transport.write(self.generate_auth_msg())
Esempio n. 19
0
 def __repr__(self):
     addr_str = '%s: ' % addr_to_str(self.start)
     return '\n'.join([addr_str + str(self.insns[0])] +
                      [(' ' * len(addr_str)) + str(insn)
                       for insn in self.insns[1:]])
Esempio n. 20
0
 def connectionMade(self):
     """Event handler of being successfully connected to HTTP proxy."""
     logging.info("connected to proxy %s with id %s" %
                  (addr_to_str(self.transport.getPeer()), self.conn_id))
Esempio n. 21
0
 def __repr__(self):
     addr_str = '%s: ' % addr_to_str(self.addr)
     return '\n'.join([addr_str + str(self.pcode[0])] + [(' ' * len(addr_str)) + str(pcop) for pcop in self.pcode[1:]])
Esempio n. 22
0
 def draw_vertex(self, g):
     g.node(self.name, addr_to_str(self.start))
Esempio n. 23
0
def get_users(conn, addr):
    send_msg(conn, str(len(USERS)).encode())
    for user in USERS:
        send_msg(conn, user.encode())
    print("[+] users sended to {}".format(addr_to_str(addr)))
Esempio n. 24
0
 def connectionMade(self):
     """Event handler of being successfully connected to HTTP proxy."""
     logging.info("connected to proxy %s with id %s" %
                  (addr_to_str(self.transport.getPeer()), self.conn_id))
Esempio n. 25
0
 def __repr__(self):
     return '%s: STMT' % addr_to_str(self.addr)