Esempio n. 1
0
def check_msg(payload, command):
    """
  Function to check if the message exists(1) or not(0).
  And if the command is delete it also returns the hash value and the message
  :param payload: payload sap message
  :param command: command can be add or delete
  :return:
  """

    Newmsg = sap.Message()
    Newmsg.setPayload(payload)

    # check if the message exists or not
    for msg in msg_list:
        msgHashId = msg._msg_hash
        Newmsg.setSource(myaddr)
        Newmsg.setMsgHash(msgHashId)

        if msg.__eq__(Newmsg):
            if command == "add":
                return 1
            else:
                return 1, msgHashId, msg

    if command == "add":
        return 0
    else:
        return 0, "", ""
Esempio n. 2
0
def send_info():
    msg = sap.Message()
    msg.setSource(myaddr)
    msg.setPayload(SDP)
    msg.setMsgHash(1)
    print "Sending SAP packet"
    data = msg.pack()
    sock_tx.sendto(data, (sap.DEF_ADDR, sap.DEF_PORT))
Esempio n. 3
0
def check_msg(payload, command):
    Newmsg = sap.Message()
    Newmsg.setPayload(payload)

    # comprobamos si existe algun mensaje igual
    for msg in msg_list:
        msgHashId = msg._msg_hash
        Newmsg.setSource(myaddr)
        Newmsg.setMsgHash(msgHashId)

        if msg.__eq__(Newmsg):
            # si existe un mensaje igual se retorna un 1
            if command == "add":
                return 1
            else:
                return 1, msgHashId, msg
    # sino ha encontondrado un mensaje igual se retorna un 0
    if command == "add":
        return 0
    else:
        return 0, "", ""
def main():

    # Prepare the socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("", sap.DEF_PORT))
    mreq = struct.pack("4sl", socket.inet_aton(sap.DEF_ADDR),
                       socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    # todo  poner que es este tiempo
    garbage_collector_period = 5

    # initialize the satellite registry
    SatReg = SatRegister()

    if (sapdebug != 1):
        SatPanel = Panel(SatReg)
        SatPanel.drawMainPanel('Main Panel')

    while True:

        inputs = [sock, sys.stdin]

        # select will wake up when data enters or the garbage_collector_period runs out
        readable, writable, exceptional = select.select(
            inputs, [], [], garbage_collector_period)

        if len(readable) != 0:

            # if there is keyboard input
            if sys.stdin in readable:
                if (sapdebug != 1):
                    k = SatPanel.wobj.getch()
                    # with the q key, go back
                    if k == ord('q'):
                        curses.endwin()
                        break

                    # Check if we are showing the mainPanel with the summary list of satellites
                    if SatPanel.active == SatPanel._MainPanel:
                        maxsats = len(SatReg._SatRegister)
                        # Check if key ascii code is in the range from '0' (ascii 48) to ascii maxsats + 48:
                        # In other words ... check if keypressed a number between 0  and maxsats-1
                        if (k - 48) > -1 and (k - 48) < maxsats:
                            # Display Detailed information of satellite indexed by the keypressed
                            SatPanel.StatusInfo("Satellite idx %s" % (k - 48))
                            SatPanel.drawInfoPanel(k - 48)

                    # If we are showing Satellite Details Panel, then go back to the MainPanel
                    elif SatPanel.active == SatPanel._InfoPanel:
                        SatPanel.drawMainPanel("Main Panel")
                else:
                    pass
                continue

            # if the data that comes in comes from the socket
            if sock in readable:
                data = sock.recv(4096)
                msg = sap.Message()
                msg.unpack(data)

                # build the sdp package
                sdp = ""
                for i in range(1, len(data.split('\n')) - 2):
                    sdp = sdp + data.split('\n')[i] + "\n"
                sdp_parser = SDPParser(sdp.splitlines())
                sdp_parser.run()
                SdpSatSession = SDPSession(sdp_parser.outbox)

            if len(msg_list) == 0:

                # point to the last hour the package arrived in sdp
                SdpSatSession.setLast_timestamp(time.time())
                # add the sdp to the list of satellites
                SatReg.add_satellite(SdpSatSession)
                # point to the last hour the package arrived in message
                msg.setLast_timestamp(time.time())
                msg_list.append(msg)

                if (sapdebug != 1):
                    SatPanel.drawMainPanel("Main Panel")
                else:
                    print SatReg._SatRegister
                del SdpSatSession

            else:
                # to check if the message exists
                exist = False

                for k, SdpSatObj in SatReg._SatRegister.items():
                    # check if the message exists, then the message is not added
                    if SdpSatObj == SdpSatSession:
                        exist = True

                        if SdpSatObj == SdpSatSession:
                            # check if the message is marked for deletion
                            if msg._deletion:
                                SatReg.del_satellite(SdpSatObj)

                                for ms in msg_list:
                                    if ms == msg:
                                        msg_list.remove(ms)

                                if (sapdebug != 1):
                                    SatPanel.drawMainPanel("Main Panel")

                                else:
                                    print SatReg._SatRegister
                                continue

                            else:
                                # We have received a SAP for an existing SDP Sat Session
                                # update timestamp in this SDPSatObj:
                                for ms in msg_list:
                                    if ms == msg:
                                        ms.setLast_timestamp(time.time())

                                SdpSatObj.setLast_timestamp(time.time())
                                continue

                if exist == False:
                    # add the message

                    SdpSatSession.setLast_timestamp(time.time())
                    SatReg.add_satellite(SdpSatSession)

                    if (sapdebug != 1):
                        SatPanel.drawMainPanel("Main Panel")

                    else:
                        print SatReg._SatRegister
                    del SdpSatSession

                    msg.setLast_timestamp(time.time())
                    msg_list.append(msg)

        # if in select garbage_collector_period is over
        if not (readable or writable):
            # check if you have to delete a satellite if it has not been
            # received in the stipulated time
            for ms in msg_list:
                delete = ms.intervalPacket(time.time())
                if delete == 1:
                    msg_list.remove(ms)

                    if (sapdebug != 1):
                        SatPanel.drawMainPanel("Main Panel")
                else:
                    pass

            # check if you have to delete a satellite if it has not been
            # received in the stipulated time
            for SdpSatObj in SatReg._SatRegister.values():

                delete = SdpSatObj.intervalPacket(time.time())
                if delete == 1:
                    SatReg.del_satellite(SdpSatObj)

                    if (sapdebug != 1):
                        SatPanel.drawMainPanel("Main Panel")

                else:
                    pass
Esempio n. 5
0
	return 0



if __name__ == "__main__":

	# Prepare the socket
	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
	sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, sap.DEF_TTL)
	# Grab some info
	myaddr = socket.gethostbyname(socket.gethostname())

	msg_list = []
	HashTable = HashRegister()

	msg = sap.Message()
	msg.setSource(myaddr)
	msg.setPayload(SDP)
	msg.setMsgHash(0)
	print "el mensaje a chekear", msg
	check_msg(msg)
	del msg

	msg = sap.Message()
	msg.setSource(myaddr)
	msg.setPayload(SDP2)
	msg.setMsgHash(0)
	check_msg(msg)
	del msg

	msg = sap.Message()
Esempio n. 6
0
def tcp_handler(data):
    """
  Function to handle the sap package. Separates the command from the sap,
  with the command choose if it add or remove.
  Return returns 1 to recalculate the timeout(package added or deleted)
  or 0 to not recalculate it.
  :param data: sap message
  """
    global msg_list

    command = data.split('\n')[0]
    # RECOGIDA DEL PAYLOAD (PARTE DEL SDP)
    sdp = ""
    for i in range(1, len(data.split('\n'))):
        sdp = sdp + data.split('\n')[i] + "\n"

    Newmsg = sap.Message()
    Newmsg.setSource(myaddr)
    Newmsg.setPayload(sdp)

    if command == "add":

        if len(msg_list) == 0:
            hashid = add_hash()
            Newmsg.setMsgHash(hashid)

            #print "msg is the first in the system\n"
            #print Newmsg
            #print "\n\n"
            msg_list.append(Newmsg)
            del Newmsg
            return 1

        else:
            exists = check_msg(sdp, command)

            if exists == 1:

                pass
                #print "msg and newMsg are the same messages\n"
            else:
                print "msg and newMsg are different messages\n"
                hashid = add_hash()

                if hashid == "There is no connection available.":
                    #print hashid
                    del Newmsg

                else:
                    Newmsg.setMsgHash(hashid)
                    msg_list.append(Newmsg)
                    del Newmsg
                    return 1

    elif command == "delete":
        #print "vamos a borrar, el tamnyo ahora es ", len(msg_list)

        if len(msg_list) == 0:
            del Newmsg

        else:
            exists, hashid, msg = check_msg(sdp, command)
            if exists == 0:
                #print "There is no message that is the same as the Newmsg\n"
                pass

            else:
                print "The message has been delete.\n"
                Delete_Hash(hashid, msg)
                #print "despues de borrar, el tamanyo es ", len(msg_list)
                del Newmsg
        return 1

    else:
        print "The command is not correct."
        del Newmsg
    return 0
Esempio n. 7
0
def tcp_handler(data):  # es el New msg
    global msg_list

    command = data.split('\n')[0]
    # RECOGIDA DEL PAYLOAD (PARTE DEL SDP)
    sdp = ""
    print(len(data.split('\n')))
    for i in range(1, len(data.split('\n'))):
        sdp = sdp + data.split('\n')[i] + "\n"

    Newmsg = sap.Message()
    Newmsg.setSource(myaddr)
    Newmsg.setPayload(sdp)

    if command == "add":

        if len(msg_list) == 0:
            # si la lista esta vacia anyadimos un hash
            hashid = add_hash()  #inicializar hash
            Newmsg.setMsgHash(hashid)

            print "msg is the first in the system\n"
            print Newmsg
            print "\n\n"
            msg_list.append(Newmsg)
            del Newmsg

            # retornanos un 1 para recalcular el tiempo
            return 1
        else:
            # Comprobamos si el sdp ya existe
            exists = check_msg(
                sdp, command)  # TODO VER SI FALLA POR DEVOLVER DOS COSAS

            if exists == 1:
                print "msg and newMsg are the same messages\n"
            else:
                print "msg and newMsg are different messages\n"
                hashid = add_hash()

                if hashid == "No hay ninguna conexion disponible.":
                    print hashid
                    del Newmsg
                else:
                    Newmsg.setMsgHash(hashid)
                    # data = Newmsg.pack() todo mirar pero creo que fuera
                    msg_list.append(Newmsg)
                    del Newmsg

                    # retornanos un 1 para recalcular el tiempo
                    return 1

    elif command == "delete":
        print "vamos a borrar, el tamnyo ahora es ", len(msg_list)

        if len(msg_list) == 0:
            # si la lista esta vacia no hacemos nada
            print "No hay ningun mensaje en la lista"
            del Newmsg

        else:
            # comprobamos si existe algun mensaje igual, devuelve el hash y el mensaje
            exists, hashid, msg = check_msg(sdp, command)
            if exists == 0:
                # si no existe ningun mensaje igual no hacemos nada
                print "No existe ningun mensaje igual que Newmsg\n"
            else:
                print "Se ha borrado el mensaje.\n"
                Delete_Hash(hashid, msg)
                print "despues de borrar, el tamanyo es ", len(msg_list)
                del Newmsg
        return 1

    else:
        print "El comando no es correcto."
        del Newmsg
    return 0
Esempio n. 8
0
def main():
    # Prepare the socket

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("", sap.DEF_PORT))
    mreq = struct.pack("4sl", socket.inet_aton(sap.DEF_ADDR),
                       socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    garbage_collector_period = 5

    SatReg = SatRegister()
    if (sapdebug != 1):
        SatPanel = Panel(SatReg)
        SatPanel.drawMainPanel('Main Panel')

    while True:
        try:

            inputs = [sock, sys.stdin]

            outputs = []
            message_queues = {}

            readable, writable, exceptional = select.select(
                inputs, [], [], garbage_collector_period)
            # print "Event"
            if len(readable) != 0:
                # Check if socket is ready to be read
                if sock in readable:
                    # print "Reading socket"
                    data = sock.recv(4096)
                    msg = sap.Message()
                    msg.unpack(data)
                    sdp_parser = SDPParser(msg._payload.splitlines())
                    sdp_parser.run()
                    # print sdp_parser.outbox
                    SdpSatSession = SDPSession(sdp_parser.outbox)
                    # print SdpSatSession
                    for k, SdpSatObj in SatReg._SatRegister.items():
                        # print SdpSatSession.__eq__(SdpSatObj)
                        # print "Dump of SdpSatObj numb %d" % k
                        # print SdpSatObj
                        if SdpSatObj == SdpSatSession:
                            if msg._deletion:
                                SatReg.del_satellite(SdpSatObj)
                                if (sapdebug != 1):
                                    SatPanel.drawMainPanel("Main Panel")
                                else:
                                    print SatReg._SatRegister
                                continue
                            else:
                                # We have received a SAP for an existing SDP Sat Session
                                # update timestamp in this SDPSatObj:
                                SdpSatObj.setLast_timestamp(time.time())
                                continue
                    # Here, we have a SAP for an unexising SDP Sat Session
                    if msg._deletion:
                        continue
                    SdpSatSession.setLast_timestamp(time.time())
                    SatReg.add_satellite(SdpSatSession)
                    if (sapdebug != 1):
                        SatPanel.drawMainPanel("Main Panel")
                    else:
                        print SatReg._SatRegister
                    del SdpSatSession

                # Check if keyboard is has a keypressed waiting to be read
                if sys.stdin in readable:
                    if (sapdebug != 1):
                        k = SatPanel.wobj.getch()
                        if k == ord('q'):
                            curses.endwin()
                            break
                        # Check if we are showing the mainPanel with the summary list of satellites
                        if SatPanel.active == SatPanel._MainPanel:
                            maxsats = len(SatReg._SatRegister)
                            # Check if key ascii code is in the range from '0' (ascii 48) to ascii maxsats + 48:
                            # In other words ... check if keypressed a number between 0  and maxsats-1
                            if (k - 48) > -1 and (k - 48) < maxsats:
                                # Display Detailed information of satellite indexed by the keypressed
                                SatPanel.StatusInfo("Satellite idx %s" %
                                                    (k - 48))
                                SatPanel.drawInfoPanel(k - 48)
                        # If we are showing Satellite Details Panel, then go back to the MainPanel
                        elif SatPanel.active == SatPanel._InfoPanel:
                            SatPanel.drawMainPanel("Main Panel")
                    else:
                        pass

                # print "time out "
                for SdpSatObj in SatReg._SatRegister.values():
                    # mira si hay que borrar algun paquete
                    # print "dentro del borra de timeout"
                    delete = SdpSatObj.intervalPacket(time.time())
                    if delete == 1:
                        # print "borrado del "
                        # si devuelve 1 borara el paquete
                        SatReg.del_satellite(SdpSatObj)
                        if (sapdebug != 1):
                            SatPanel.drawMainPanel("Main Panel")

                    else:
                        pass
                # print "no se borra"

        except Exception as e:
            if (sapdebug != 1):
                if SatPanel.active == SatPanel._MainPanel:
                    SatPanel.drawMainPanel("Main Panel")
                elif SatPanel.active == SatPanel._InfoPanel:
                    SatPanel.drawInfoPanel(SatPanel._InfoPanel)
            else:
                print(e)