Ejemplo n.º 1
0
def test_default():
    messages.db.delete('messages', where='to_userid=2')
    msgid = messages.send_message(1, 2, 'test message')

    msg = messages.get_message(msgid)
    assert msg.content == 'test message'

    msgs = messages.get_messages(2)
    assert len(list(msgs)) == 1

    messages.read_message(msgid)
    msg = messages.get_message(msgid)
    assert msg.unread == 0
Ejemplo n.º 2
0
 def handle_ADDR(self, addr):
     try:
         nodes = messages.read_message(addr)['nodes']
         print("Recieved addr list from peer " + self.remote_nodeid)
         for node in nodes:
             print(" " + node[0] + " " + node[1])
             if node[0] == self.nodeid:
                 print(" [!] Not connecting to " + node[0] + ": thats me!")
                 return
             if node[1] != "SPEAKER":
                 print(" [ ] Not connecting to " + node[0] + ": is " +
                       node[1])
                 return
             if node[0] in self.factory.peers:
                 print(" [ ] Not connecting to " + node[0] +
                       ": already connected")
                 return
             print(" [ ] Trying to connect to peer " + node[0] + " " +
                   node[1])
             host, port = node[0].split(":")
             point = TCP4ClientEndpoint(reactor, host, int(port))
             d = connectProtocol(
                 point, MyProtocol(self.factory, "SENDHELLO", "SPEAKER"))
             d.addCallback(gotProtocol)
     except messages.InvalidSignatureError:
         print(addr)
         print("ERROR: Invalid addr sign ", self.remote_ip)
         self.transport.loseConnection()
Ejemplo n.º 3
0
 def handle_ADDR(self, addr):
     try:
         nodes = messages.read_message(addr)['nodes']
         _print(" [<] Recieved addr list from peer " + self.remote_nodeid)
         #for node in filter(lambda n: nodes[n][1] == "SEND", nodes):
         for node in nodes:
             _print("     [*] " + node[0] + " " + node[1])
             if node[0] == self.nodeid:
                 _print(" [!] Not connecting to " + node[0] + ": thats me!")
                 return
             if node[1] != "SEND":
                 _print(" [ ] Not connecting to " + node[0] + ": is " +
                        node[1])
                 return
             if node[0] in self.factory.peers:
                 _print(" [ ] Not connecting to " + node[0] +
                        ": already connected")
                 return
             _print(" [ ] Trying to connect to peer " + node[0] + " " +
                    node[1])
             # TODO: Use [2] and a time limit to not connect to "old" peers
             host, port = node[0].split(":")
             point = TCP4ClientEndpoint(reactor, host, int(port))
             d = connectProtocol(point,
                                 NCProtocol(ncfactory, "SENDHELLO", "SEND"))
             d.addCallback(gotProtocol)
     except messages.InvalidSignatureError:
         print addr
         _print(" [!] ERROR: Invalid addr sign ", self.remote_ip)
         self.transport.loseConnection()
Ejemplo n.º 4
0
 def handle_HELLO(self, hello):
     try:
         hello = messages.read_message(hello)
         self.remote_nodeid = hello['nodeid']
         self.remote_lsnport = hello['listenPort']
         if self.remote_nodeid == self.nodeid:
             _print(" [!] Found myself at", self.host_ip)
             self.transport.loseConnection()
         else:
             if self.state == "GETHELLO":
                 my_hello = messages.create_hello_1(self.nodeid,
                                                    self.lsnport,
                                                    self.VERSION)
                 self.transport.write(my_hello + "\n")
             self.add_peer()
             self.state = "READY"
             self.print_peers()
             #self.write(messages.create_ping(self.nodeid))
             if self.kind == "INBOUND":
                 # The listener pings it's audience
                 _print(" [P2P] Starting pinger to " + self.remote_nodeid)
                 self.lc_ping.start(PING_INTERVAL, now=False)
                 # Tell new audience about my peers
                 self.send_ADDR()
     except messages.InvalidSignatureError:
         _print(" [!] ERROR: Invalid hello sign ", self.remoteip)
         self.transport.loseConnection()
Ejemplo n.º 5
0
    def handle_ADDR(self, addr):
        try:
            nodes = messages.read_message(addr)['nodes']
            _print(" [<] Recieved addr list from peer " + self.remote_nodeid)
            #for node in filter(lambda n: nodes[n][1] == "SEND", nodes):
            for node in nodes:
                _print("     [*] " + node[0] + " " + node[1])
                host, port = node[1].split(":")
                remote_lsnport = str(node[2])
                if node[0] == self.nodeid:
                    _print(" [!] Not connecting to " + node[0] + ": thats me!")
                    continue
                if node[3] == "INBOUND":
                    port = remote_lsnport
                    _print(" [P2P] INBOUND connecting to " + host + ":" +
                           remote_lsnport)
                if node[0] in self.factory.peers:
                    _print(" [P2P] Not connecting to " + node[0] +
                           ": already connected")
                    continue
                _print(" [P2P] Trying to connect to peer " + node[0] + " " +
                       node[1])
                point = TCP4ClientEndpoint(reactor, host, int(port))
                d = connectProtocol(
                    point, NCProtocol(self.factory, "SENDHELLO", "OUTBOUND"))
                d.addCallback(runProtocol)

        except messages.InvalidSignatureError:
            print(addr)
            _print(" [!] ERROR: Invalid addr sign ", self.remote_ip)
            self.transport.loseConnection()
Ejemplo n.º 6
0
 def handle_PONG(self, pong):
     pong = messages.read_message(pong)
     _print(" [<] PONG from", self.remote_nodeid, "at", self.remote_ip)
     # hacky
     addr, kind, listenPort = self.factory.peers[self.remote_nodeid][:3]
     self.factory.peers[self.remote_nodeid] = (addr, kind, listenPort,
                                               time())
Ejemplo n.º 7
0
def client_send_message(client_socket, message):
    """
    Send a message and try to get a receive
    """
    messages.send_message(client_socket, message)
    message = messages.read_message(client_socket)
    echo("[Client] Received: %s", message)
Ejemplo n.º 8
0
    def handle_HELLO(self, hello):
        try:
            hello = messages.read_message(hello)
            self.remote_nodeid = hello['nodeid']
            self.remote_node_protocol_version = hello["protocol"]

            if self.remote_nodeid == self.nodeid:
                logg("[!] Found myself at %s" % self.host_ip)
                self.transport.loseConnection()
            else:
                if self.state == "GETHELLO":
                    my_hello = messages.create_hello(self.nodeid, self.VERSION,
                                                     self.ProtocolVersion)
                    self.transport.write(my_hello + "\n")
                self.add_peer()
                self.state = "READY"
                self.print_peers()
                #self.write(messages.create_ping(self.nodeid))
                if self.kind == "LISTENER":
                    # The listener pings it's audience
                    logg("[ ] Starting pinger to %s" % self.remote_ip)
                    self.lc_ping.start(PING_INTERVAL, now=False)
                    # Tell new audience about my peers
                    self.send_ADDR()
                self.lc_sync.start(SYNC_INTERVAL, now=True)
        except messages.InvalidSignatureError:
            _print(" [!] ERROR: Invalid hello sign ", self.remote_ip)
            self.transport.loseConnection()
Ejemplo n.º 9
0
    def handle_HELLO(self, hello):
        try:
            print("Получил HELLO")
            hello = messages.read_message(hello)
            self.remote_nodeid = hello[
                'nodeid']  #nodeid того,кто прислал письмо

            if self.remote_nodeid == self.nodeid:  #если я  сам себе прислал
                print(" [!] Found myself at", self.host_ip)
                self.transport.loseConnection()

            else:  #если я не сам себе прислал
                if self.state == "GETHELLO":  #если я в состоянии GETHELLO
                    my_hello = messages.create_hello(
                        self.nodeid,
                        self.VERSION)  #собираю свое Hello- сообщение
                    self.sendLine(my_hello + "\n")  #отправляю

                self.add_peer()  # добавить данный пир в List
                self.state = "READY"  #ставлю себе состояние READY

                if self.kind == "LISTENER":  #если я СЛУШАЮ, то начинаю пинговать Пира
                    print(" [ ] Starting pinger to " + self.remote_nodeid)
                    self.lc_ping.start(PING_INTERVAL, now=False)
                    # Рассказываю данному ноду о моих пирах.
                    self.send_ADDR()

        except messages.InvalidSignatureError:  #если в ходе передачи были искажены данные
            print(" [!] ERROR: Invalid hello sign ", self.remoteip)
            self.transport.loseConnection()
Ejemplo n.º 10
0
def modify(message_id):
    if users.login_id() == 0:
        return render_template("index.html", login="******")
    else:
        content = messages.read_message(message_id)
        return render_template("modify.html",
                               message_id=message_id,
                               content=content)
Ejemplo n.º 11
0
def client1(address):

    # creating socket ...
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # ... and connecting to the server
    client_socket.connect(address)

    # send hello message and receive echo
    client_send_message(client_socket, "Hello")

    # shutting down sending
    client_socket.shutdown(socket.SHUT_WR)
    # getting bye message from the server
    echo("[Client] Received: %s", messages.read_message(client_socket))
    
    # waiting for the server to shut down
    if messages.read_message(client_socket) is None:
        echo("[Client] Got EOF from Server")

    client_socket.close()
Ejemplo n.º 12
0
def readMessagesLoop():
    while True:
        data = read_message()
        logger.debug("data :'{}'".format(data))
        # logger.debug("Data: " + data)
        output = process_input(data)
        if output:
            write_message(output)
        else:
            # If processing returns None, was HUP. End processing.
            break
        # Reduce busywaiting.
        time.sleep(INPUT_RATE_DETECTION_GAP_MS/1000)
Ejemplo n.º 13
0
def reply(message_id):
    if users.login_id() == 0:
        return render_template("index.html", login="******")
    else:
        user_id = messages.get_user_id(message_id)
        author = users.get_useralias(user_id)
        message = messages.read_message(message_id)
        topic_id = messages.get_topic_id(message_id)
        return render_template("reply.html",
                               content="",
                               message_id=message_id,
                               author=author,
                               message=message)
Ejemplo n.º 14
0
    def server_connection_thread_target(connection_socket, address):
        """
        Client-Server message loop. Just receiving messages and echoing back to the client.
        Special message "Bye" closes the connection
        WARNING: we assume that clients don't abuse the connection, i.e a client should end the connection, not the server
        """
        can_send = True

        try:

            while True:
                # reading one message from the client
                message = messages.read_message(connection_socket)
                if message is None:
                    # message is None, that means that the client has stopped sending data to the server
                    echo("[Server] Got EOF from Client")
                    # in that case we can shutdown reading
                    connection_socket.shutdown(socket.SHUT_RD)

                    # lets check if the server shut down sending first
                    if can_send:
                        # send bye message to the client ...
                        messages.send_message(connection_socket, "Bye bye Client")
                        # ... and shut down sending
                        connection_socket.shutdown(socket.SHUT_WR)

                    # nothing to send, nothing to receive, we can leave the message loop now
                    break

                echo("[Server] Received [%s]: %s", address, message)

                # lets check if the server can send messages
                if can_send:
                    # echoing message from the client
                    messages.send_message(connection_socket, message)

                    # if we received special message from the client
                    if message == "Bye":
                        # shut down sending to the client and start only to listen for the remaining client messages
                        connection_socket.shutdown(socket.SHUT_WR)
                        can_send = False

        except Exception:
            echo("[Server] Connection error")
        finally:
            echo("[Server] Closing socket")
            # close the socket
            connection_socket.close()
Ejemplo n.º 15
0
    def handle_SYNC(self, line):
        logg("[>] Got reply about sync message from %s" % self.remote_nodeid)
        data = messages.read_message(line)

        if data["bestheight"] > CBlockchain().getBestHeight():
            # we have missing blocks
            diffrence = data["bestheight"] - CBlockchain().getBestHeight()
            logg("We need sync, we are behind %d blocks" % diffrence)
            self.factory.dialog = "Need sync"
            syncme = messages.create_ask_blocks(self.nodeid,
                                                CBlockchain().GetBestHash())
            self.write(syncme)

        elif data["bestheight"] == CBlockchain().getBestHeight():
            self.factory.dialog = "Synced"
            logg("we are synced")
Ejemplo n.º 16
0
 def handle_SENDBLOCKS(self, line):
     logg("[>] Got sendblocks message from %s" % self.remote_nodeid)
     data = messages.read_message(line)
     try:
         thisHeight = CBlockIndex(data["besthash"]).Height()
     except Exception as e:
         self.transport.loseConnection()
     else:
         # be sure that we are not behind, and peer has genesis block
         if thisHeight < CBlockchain().getBestHeight() and thisHeight >= 1:
             data_block, pblock, nonce = CaBlock(thisHeight + 1).dump()
             cblock = pickle.dumps(pblock)
             cdatablock = pickle.dumps(data_block)
             message = messages.create_send_block(self.nodeid, cdatablock,
                                                  cblock, nonce)
             self.write(message)
             logg("block %d send to %s" %
                  (thisHeight + 1, self.remote_nodeid))
Ejemplo n.º 17
0
def modify2(message_id, user_search, topic_search, text_search):
    if users.login_id() == 0:
        return render_template("index.html", login="******")
    else:
        user_search = user_search.strip()
        topic_search = topic_search.strip()
        text_search = text_search.strip()
        content = messages.read_message(message_id)
        if user_search == "":
            user_search = "%20"
        if topic_search == "":
            topic_search = "%20"
        if text_search == "":
            text_search = "%20"
        return render_template("modify2.html",
                               message_id=message_id,
                               content=content,
                               user_search=user_search,
                               topic_search=topic_search,
                               text_search=text_search)
Ejemplo n.º 18
0
    def handleRECEIVEDBLOCK(self, line):
        data = messages.read_message(line)
        logg("Proccesing block %d from %s" %
             (CBlockchain().getBestHeight() + 1, self.remote_nodeid))
        data_block = pickle.loads(data["raw"])
        pblock = pickle.loads(data["pblock"])
        nonce = data["bnonce"]

        # transactions are hashed via dict,
        # when a dict changes order produces diffrent tx hash
        # ordering to avoid diffrent hashes
        for x in xrange(len(pblock.vtx)):
            r = OrderedDict(pblock.vtx[x])
            pblock.vtx[x] = dict(r.items())

        # procces this block
        if Proccess().thisBlock(data_block, pblock, nonce):
            logg("Block accepted\n")
            if CBlockchain().WriteBlock(pblock, data_block, nonce):
                logg("Block successfull added to database")
Ejemplo n.º 19
0
def send_reply(message_id):
    if users.login_id() == 0:
        return render_template("index.html", login="******")
    else:
        author_id = messages.get_user_id(message_id)
        topic_id = messages.get_topic_id(message_id)
        author = users.get_useralias(author_id)
        message = messages.read_message(message_id)
        ref_msg = author + " kirjoitti: \n" + message
        content = request.form["content"]
        if isBlank(content):
            return render_template("reply.html",
                                   content="",
                                   message_id=message_id,
                                   author=author,
                                   message=message,
                                   error="Tyhjä kenttä, viestiä ei talletettu")
        if messages.insert(topic_id, content, ref_msg):
            return redirect("/messages/" + str(topic_id))
        else:
            return render_template("error.html",
                                   message="Viestin talletus ei onnistunut")
Ejemplo n.º 20
0
def client2(address):

    # creating socket ...
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # ... and connecting to the server
    client_socket.connect(address)

    # send hello message and receive echo
    client_send_message(client_socket, "Hello")

    # send bye message
    client_send_message(client_socket, "Bye")
    # the server should sent EOF
    if messages.read_message(client_socket) is None:
        echo("[Client] Got EOF from server")

        # shutting down read
        client_socket.shutdown(socket.SHUT_RD)
        # sending bye message to the server
        messages.send_message(client_socket, "Bye bye Server")
        messages.send_message(client_socket, "Have a good day")
        client_socket.shutdown(socket.SHUT_WR)

    client_socket.close()
Ejemplo n.º 21
0
 def handle_PING(self, ping):
     if messages.read_message(ping):
         pong = messages.create_pong(self.nodeid)
         self.sendLine(pong)
Ejemplo n.º 22
0
 def handle_PONG(self, pong):
     pong = messages.read_message(pong)
     logg("[<] PONG from %s at %s" % (self.remote_nodeid, self.remote_ip))
     # hacky
     addr, kind = self.factory.peers[self.remote_nodeid][:2]
     self.factory.peers[self.remote_nodeid] = (addr, kind, time())
Ejemplo n.º 23
0
 def test_hello(self):
     hello = messages.create_hello(self.nodeid, 0)
     # check that InvalidSignatureError is not raised
     return messages.read_message(hello)
Ejemplo n.º 24
0
 def test_pong(self):
     pong = messages.create_pong(self.nodeid)
     # exceptions?
     return messages.read_message(pong)
Ejemplo n.º 25
0
 def test_ackhello(self):
     ackhello = messages.create_ackhello(self.nodeid)
     return messages.read_message(ackhello)
Ejemplo n.º 26
0
 def test_ackhello(self):
     ackhello = messages.create_ackhello(self.nodeid)
     return messages.read_message(ackhello)
Ejemplo n.º 27
0
 def test_ping(self):
     ping = messages.create_ping(self.nodeid)
     # check that InvalidSignatureError isn't raised
     return messages.read_message(ping)
Ejemplo n.º 28
0
 def handle_PONG(self, pong):
     pong = messages.read_message(pong)
     print("PONG from", self.remote_nodeid, "at", self.remote_ip)
     addr, kind = self.factory.peers[self.remote_nodeid][:2]
     self.factory.peers[self.remote_nodeid] = (addr, kind, time())
Ejemplo n.º 29
0
 def test_ping(self):
     ping = messages.create_ping(self.nodeid)
     # check that InvalidSignatureError isn't raised
     return messages.read_message(ping)
Ejemplo n.º 30
0
 def test_pong(self):
     pong = messages.create_pong(self.nodeid)
     # exceptions?
     return messages.read_message(pong)
Ejemplo n.º 31
0
 def test_hello(self):
     hello = messages.create_hello(self.nodeid, 0)
     # check that InvalidSignatureError is not raised
     return messages.read_message(hello)