Exemplo n.º 1
0
    def run(self):
        Util.printLog('\n\nApertura thread NEAR\n\n')
        db = dataBase()

        self.lock.acquire()

        res = db.retrivenSearch(self.pid, self.pack[20:75])
        if (res == 0):  # Richiesta già conosciuta
            Util.printLog("Eseguo NEAR per: " + self.ipRequest)

            db.insertRequest(self.pid, self.pack[20:75], time.time())
            self.lock.release()
            if self.ttl > 1:  # Inoltro richiesta ai vicini

                self.ttl = str(self.ttl - 1).zfill(2)
                self.pack = ''.join((self.pack[:80], self.ttl))

                neighborhood = db.retrieveNeighborhood(self.config)

                for neighbor in neighborhood:

                    params = Util.ip_deformatting(neighbor[0], neighbor[1],
                                                  None)

                    if params[0] != self.ipRequest and params[
                            1] != self.ipRequest and params[0] != self.ipv4:
                        self.con = Conn(params[0], params[1], params[2])
                        try:
                            self.con.connection()
                            self.con.s.send(self.pack.encode())
                            self.con.deconnection()
                            Util.printLog("vicino inoltro NEAR: " + params[0])
                        except IOError as e:
                            print("Inoltro vicino fallito")

            self.pack = 'ANEA' + self.pid + self.myIPP
            Util.printLog('ANEA a: ' + str(self.pack))
            Util.printLog('ANEA CONN: ' + self.ipv4 + self.ipv6 +
                          str(self.port))
            self.con = Conn(self.ipv4, self.ipv6, self.port)
            #print('Con ANEA ', self.ipv4, self.ipv6, self.port)
            try:
                self.con.connection()
                self.con.s.send(self.pack.encode())
                self.con.deconnection()
            except IOError as e:
                print("Risposta diretta fallita")

        else:
            self.lock.release()
            Util.printLog("NEAR per: " + self.ipRequest + ". Già eseguita")
        Util.printLog('\n\nChiusura thread NEAR\n\n')
Exemplo n.º 2
0
 def __init__(self, sessionid, ipp2p_dir_4, ipp2p_dir_6):
     self.ipp2p_dir_4 = ipp2p_dir_4
     self.ipp2p_dir_6 = ipp2p_dir_6
     self.sID = sessionid
     self.pack = 'FIND' + sessionid
     self.con = Conn(self.ipp2p_dir_4, self.ipp2p_dir_6, 3000)
     self.bytes_read = 0
Exemplo n.º 3
0
	def answer(self, file_list, pktid, ip, my_ipv4, my_ipv6, my_port, portB):
		dict_list = self.convert_md5(file_list)
		#stabilisco una connessione con il peer che ha iniziato
		addr = Util.ip_deformatting(ip, portB, None)
	
		ip6 = ipad.ip_address(ip[16:])

		self.con = Conn(addr[0], str(ip6), addr[2])
		
		my_ip_port = Util.ip_formatting(my_ipv4, my_ipv6, my_port)

		try:
			self.con.connection()
			for index in dict_list:
				md5_file_name = dict_list[index].ljust(132,' ')
				answer = "AQUE"+pktid+my_ip_port+md5_file_name
				#print(answer)
				self.con.s.send(answer.encode())
				Util.printLog(answer)
				#print(str(answer.encode())+"\n")
				#print(str(len(answer.encode()))+"\n")
			self.con.deconnection()
		except IOError as expt:
			print("Errore di connessione")
			print(expt)
			sys.exit(0)
		Util.printLog('QUER:fine answer')
Exemplo n.º 4
0
    def test_sales(self):

        id = [7, 8, 9, 10]
        client = ["Alex Green", "James Brown", "Robert Gray", "Jessy Blue"]

        products = [[
            "Hamburguer de Frango", "Hamburguer de Frango",
            "Hamburguer de Picanha", "Hamburguer de Picanha"
        ], ["Hamburguer Vegano", "Hamburguer de Picanha", "Pizza Calabresa"],
                    ["Pizza Calabresa", "Refrigerante"],
                    ["Pizza de Frango", "Batata Frita", "Refrigerante"]]

        qtd = [[2, 3, 1, 2], [1, 2, 1], [1, 2, 3], [1, 3, 3]]
        value = [90.5, 75.5, 50.9, 101.3]

        fields = "id,client,product,quantity,value"
        for i, _ in enumerate(id):
            for j, product in enumerate(products[i]):
                values = f"'{id[i]}','{client[i]}','{product}','{qtd[i]}','{value[i]}'"
                try:
                    conn = Conn()
                    self.assertEqual(
                        conn._insertItem(fields, values, table="sale"), True)
                except Exception as e:
                    print("TEST_CLIENT============>", e)
Exemplo n.º 5
0
    def query(self, config):

        db = dataBase()
        pktid = ''.join(random.choice(string.ascii_uppercase+string.digits) for _ in range(16))
        
        ipp2p_pp2p = Util.ip_formatting(self.ipv4, self.ipv6, self.port)
        
        # richiesta vicini
        near = Vicini(config, self.port)
        # thread per ascolto di riposta dei vicini
        
        #th_near_stop = th.Event()
        th_near = Vicini_res(self.port, self.lock)
        th_near.start()

        # partenza richiesta dei vicini
        near.searchNeighborhood()
        
        #th_near_stop.set()
        Util.printLog("PRE JOIN POSSIBILE INVIO DI CAZZATE")
        th_near.join()
        
        db.insertRequest(pktid, ipp2p_pp2p[:55], time.time())

        self.research = "QUER" + pktid + ipp2p_pp2p + str(self.ttl).zfill(2) + (self.search+(' '*(20-len(self.search))))

        # retrieve neighbors from database
        self.neighbors = db.retrieveNeighborhood(config)
        Util.printLog("SONO NELLA RICERCA PRIMA DI RETR")
        #thread in ascolto per ogni ricerca
        retr = Retr(self.port, config, self.lock)
        #th_quer_stop = th.Event()
        retr.start()

        Util.printLog("SONO NELLA RICERCA DOPO RETR")

        #sending query to roots and neighbors
        for n in self.neighbors:
            addr = Util.ip_deformatting(n[0], n[1], self.ttl)
            
            #ip4 = ipad.ip_address(n[0][:15])
            ip6 = ipad.ip_address(n[0][16:])

            self.con = Conn(addr[0], str(ip6), addr[2])
            try:
                Util.printLog("QUER --------------------------------")
                Util.printLog(self.research)
                Util.printLog(str(len(self.research)))
                Util.printLog(addr[0])
                Util.printLog("-------------------------------------")
                self.con.connection()
                self.con.s.send(self.research.encode())
                self.con.deconnection()
            except IOError as expt:
                print("Errore di connessione")
                print(expt)
                sys.exit(0)
        
        del db
        return pktid
Exemplo n.º 6
0
 def __init__(self, ipp2p_4, ipp2p_6, pp2p, dict_filesystem, sid):
     self.ipp2p_4 = ipp2p_4
     self.ipp2p_6 = ipp2p_6
     self.pp2p = pp2p
     self.sid = sid
     self.dict_filesystem = dict_filesystem
     self.con = Conn(self.ipp2p_4, self.ipp2p_6, self.pp2p)
Exemplo n.º 7
0
    def download(self):
        print("\n--- DOWNLOAD ---\n")

        self.con = Conn(self.ipp2p_B_4, self.ipp2p_B_6, int(self.pp2p_B))
        self.con.connection()

        to_peer = "RETR" + self.md5

        self.con.s.send(to_peer.encode('ascii'))

        self.first_packet = self.con.s.recv(10)
        self.bytes_read_f = len(self.first_packet)
        while (self.bytes_read_f < 10):
            self.first_packet += self.con.s.recv(10 - self.bytes_read_f)
            self.bytes_read_f = len(self.first_packet)

        if (self.first_packet[:4].decode() == "ARET"):
            i = self.first_packet[4:10].decode()  # n di chunk o indice del ciclo for

            for j in range(int(i)):
                self.chunk_length = self.con.s.recv(5)  # lunghezza del primo chunk

                self.bytes_read_l = len(self.chunk_length)
                while (self.bytes_read_l < 5):       # controllo che siano stati realmente letti i bytes richiesti
                    self.chunk_length += self.con.s.recv(5 - self.bytes_read_l)
                    self.bytes_read_l = len(self.chunk_length)

                self.chunk = self.con.s.recv(int(self.chunk_length))  # dati
                #self.data_recv.append(self.chunk)
                self.bytes_read = len(self.chunk)

                while (self.bytes_read < int(self.chunk_length)):        # controllo che siano stati realmente letti i bytes richiesti
                    self.chunk += self.con.s.recv(int(self.chunk_length) - self.bytes_read)
                    self.bytes_read = len(self.chunk)
                    #self.data_recv.append(buffer)
                self.data_recv.append(self.chunk)
        self.con.deconnection()

        path_file = "img/" + self.filename
        check_file = Path(path_file)

        if (check_file.is_file()):
            choice_file = input("\nIl file esiste già nel tuo file system, vuoi sovrascriverlo? (Y,n): ")
            if(choice_file == "Y"):
                os.remove(path_file)
                file_recv = open(path_file, "ab")
                for i in self.data_recv:
                    file_recv.write(i)
                file_recv.close()
            else:
                return
        else:
            file_recv = open(path_file,"ab")
            for i in self.data_recv:
                file_recv.write(i)
            file_recv.close()
Exemplo n.º 8
0
    def __init__(self, config, sid):

        db = dataBase()

        self.t_ipv4 = config.trackerV4
        self.t_ipv6 = config.trackerV6
        self.t_port = config.trackerP
        self.sid = sid
        self.lenpart = db.retrieveConfig(('lenPart',)).zfill(6)
        self.con = Conn(self.t_ipv4, self.t_ipv6, self.t_port)
    def research(self):
        db = dataBase()
        #generating packet
        search_extended = self.search + (' ' * (20 - len(self.search)))
        pack = "FIND" + self.sid + search_extended

        #retreive address of superpeer
        if (Util.mode in ["normal", "logged"]):
            super_ip = db.retrieveSuperPeers()
            sIpv4, sIpv6, sPort = Util.ip_deformatting(super_ip[0][0],
                                                       super_ip[0][1])
            #connection to superpeer
            con = Conn(sIpv4, sIpv6, sPort)

        else:
            config = db.retrieveConfig(("selfV4", "selfV6"))
            #connection to superpeer
            con = Conn(config.selfV4, config.selfV6, 3000)

        if con.connection():

            Util.printLog('Incipit corretto')
            con.s.send(pack.encode())

            recv_type = con.s.recv(4)
            if (len(recv_type) != 0):
                self.bytes_read = len(recv_type)
                while (self.bytes_read < 4):
                    recv_type += con.s.recv(4 - self.bytes_read)
                    self.bytes_read = len(recv_type)

            if (recv_type.decode() == "AFIN"):
                recv_packet = con.s.recv(3)  # numero di md5 ottenuti
                self.bytes_read = len(recv_packet)
                Util.printLog("RICEVUTO AFIN")
                while (self.bytes_read < 3):
                    recv_packet += con.s.recv(3 - self.bytes_read)
                    self.bytes_read = len(recv_packet)

                recv_afin = Recv_Afin(int(recv_packet.decode()), con.s)
                recv_afin.start()
        else:
            Util.printLog('Incipit fallito')
Exemplo n.º 10
0
    def searchNeighborhood(self):
        db = dataBase()
        nears = db.retrieveNeighborhood(self.config)

        for near in nears:
            data = Util.ip_deformatting(near[0], near[1])
            connRoot = Conn(data[0], data[1], data[2])
            connRoot.connection()
            connRoot.s.send(self.pack.encode())
            connRoot.deconnection()
Exemplo n.º 11
0
    def __init__(self, ipp2p_dir_v4, ipp2p_dir_v6, my_ipv4, my_ipv6, pp2p_bf):
        self.ip_dir_4 = ipp2p_dir_v4
        self.ip_dir_6 = ipp2p_dir_v6
        self.dir_port = 3000

        self.my_ipv4 = my_ipv4
        self.my_ipv6 = my_ipv6
        self.pp2p_bf = pp2p_bf

        self.con = Conn(self.ip_dir_4, self.ip_dir_6, self.dir_port)
Exemplo n.º 12
0
	def run(self):

		c = Conn(port=self.port)

		peer = c.initializeSocket()

		while True: # Ciclo di connessioni

			other_peer, addr = peer.accept()

			t = Worker(other_peer)
			t.start()
Exemplo n.º 13
0
    def searchNeighborhood(self):

        db = dataBase()
        nears = db.retrieveNeighborhood(self.config)

        for near in nears:
            Util.printLog("NEAR ------")
            Util.printLog(str(near))
            Util.printLog(self.pack)
            Util.printLog("-----------")
            data = Util.ip_deformatting(near[0], near[1], None)
            connRoot = Conn(data[0], data[1], data[2])
            connRoot.connection()
            connRoot.s.send(self.pack.encode())
            connRoot.deconnection()
Exemplo n.º 14
0
    def run(self):

        c = Conn(port=3000)
        peersocket = c.initializeSocket()

        while True:

            other_peersocket, addr = peersocket.accept()

            totalBit = int(other_peersocket.recv(8).decode())

            tot = totalBit
            byte = []

            # Blocchi completi
            while totalBit >= 8:

                byte.append(255)
                totalBit -= 8

            # Blocco incompleto (finale)
            if totalBit > 0:

                lastBlock = (1 << totalBit) - 1

                byte.append(int('{:08b}'.format(lastBlock)[::-1], 2))

            ###################

            # INSERISCI QUI ALTRI BLOCCHI PER POTER AVERE PESI DIVERSI

            ###################

            box = ceil(tot / 8)
            print('peers pronti: ', str(len(byte) // box).zfill(5))
            other_peersocket.send(str(box).zfill(8).encode())  # Numero blocchi
            other_peersocket.send(str(tot).zfill(8).encode())  # Numero bit
            other_peersocket.send(str(len(byte) //
                                      box).zfill(8).encode())  # Numero peers

            charAscii = ''
            for el in byte:

                charAscii = charAscii + chr(el)

            a = other_peersocket.send(codecs.encode(charAscii, 'iso-8859-1'))
            print('scritto: ', a)
            other_peersocket.close()
Exemplo n.º 15
0
    def search_neighbors(self, db, ip_request, new_quer):
        self.neighbors = db.retrieveSuperPeers()  #mi tiro giù i vicini super
        for n in self.neighbors:
            addr = Util.ip_deformatting(n[0], n[1])
            ip6 = ipad.ip_address(n[0][16:])
            self.con = Conn(addr[0], str(ip6), addr[2])

            if ((addr[0] != ip_request) and (str(ip6) != ip_request)
                    and (new_quer[20:35] != addr[0])):
                if (self.con.connection()):
                    self.con.s.send(new_quer.encode())
                    Util.printLog(new_quer)
                    self.con.deconnection()
                else:
                    Util.printLog("[QUER] Errore inoltro al superpeer " +
                                  addr[0])
Exemplo n.º 16
0
    def test_client(self):

        name = ["Alex Green","James Brown","Robert Gray","Jessy Blue"]

        points = [600, 100, 500, 1000]

        email = ["*****@*****.**",
        "*****@*****.**",
        "*****@*****.**",
        "*****@*****.**"]
        fields = "name,points,email"
        for i, _ in enumerate(name):
            values=f"'{name[i]}','{points[i]}','{str(email[i])}'"
            try:
                conn = Conn()
                self.assertEqual(conn._insertItem(fields, values, table="client"), True)
            except Exception as e:
                print("TEST_CLIENT============>", e)
Exemplo n.º 17
0
    def answer(self, db, file_list, pktid, ip, portB):
        addr = Util.ip_deformatting(ip, portB)
        ip6 = ipad.ip_address(ip[16:])
        Util.printLog("PARAMETRI VARI PER L'AQUE ========> " + str(addr[0]) +
                      " " + str(str(ip6)) + " " + str(addr[2]))
        self.con = Conn(addr[0], str(ip6), addr[2])

        if (self.con.connection()):
            for file in file_list:
                peer_info = db.retrieveLOGIN(file[0])
                answer = "AQUE" + pktid + peer_info[0] + peer_info[1] + file[
                    1] + file[2]
                Util.printLog("AQUE REINVIATO :::: " + str(answer))
                self.con.s.send(answer.encode())
                Util.printLog(answer)
            self.con.deconnection()
        else:
            Util.printLog("[AQUE] Errore invio risposta al peer " + addr[0])
Exemplo n.º 18
0
def conn_line_filter(line, user, range_st_obj, range_end_obj):
    fields = line.split(CSV_SEP)

    # check username
    username = fields[USER_FIELD]
    if not check_username(user, username):
        raise ValueError("Username no coincide")

    # check MAC
    mac = fields[MAC_FIELD]
    if not check_mac(mac):
        raise ValueError("Error parseando mac address")

    # check conn date
    conn_st = fields[CONN_ST_FIELD]
    conn_end = fields[CONN_END_FIELD]
    if not check_date(range_st_obj, range_end_obj, conn_st, conn_end):
        raise ValueError("Error parseando fecha")

    return Conn(user, mac, conn_st, conn_end)
Exemplo n.º 19
0
    def testData(self):
        name = [
            "Hamburguer de Frango", "Hamburguer de Picanha",
            "Hamburguer Vegano", "Pizza Calabresa", "Pizza de Frango",
            "Batata Frita", "Refrigerante"
        ]

        price = [12.90, 15.90, 12.90, 19.90, 17.90, 9.90, 4.90]

        description = [
            "Mussum Ipsum, cacilds vidis litro abertis. Sapien in monti palavris qui num significa nadis i pareci latim. Detraxit consequat et quo num tendi nada. Manduma pindureta quium dia nois paga. Diuretics paradis num copo é motivis de denguis.",
            "Mussum Ipsum, cacilds vidis litro abertis. Diuretics paradis num copo é motivis de denguis. Si u mundo tá muito paradis? Toma um mé que o mundo vai girarzis! Quem num gosta di mim que vai caçá sua turmis! Nec orci ornare consequat. Praesent lacinia ultrices consectetur. Sed non ipsum felis.",
            "Mussum Ipsum, cacilds vidis litro abertis. Detraxit consequat et quo num tendi nada. Quem manda na minha terra sou euzis! Leite de capivaris, leite de mula manquis sem cabeça. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.",
            "Mussum Ipsum, cacilds vidis litro abertis. Aenean aliquam molestie leo, vitae iaculis nisl. Si u mundo tá muito paradis? Toma um mé que o mundo vai girarzis! Viva Forevis aptent taciti sociosqu ad litora torquent. Vehicula non. Ut sed ex eros. Vivamus sit amet nibh non tellus tristique interdum.",
            "Mussum Ipsum, cacilds vidis litro abertis. Vehicula non. Ut sed ex eros. Vivamus sit amet nibh non tellus tristique interdum. Quem num gosta di mé, boa gentis num é. Praesent vel viverra nisi. Mauris aliquet nunc non turpis scelerisque, eget. Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis.",
            "Mussum Ipsum, cacilds vidis litro abertis. Nec orci ornare consequat. Praesent lacinia ultrices consectetur. Sed non ipsum felis. Pra lá , depois divoltis porris, paradis. Aenean aliquam molestie leo, vitae iaculis nisl. Si num tem leite então bota uma pinga aí cumpadi!",
            "Mussum Ipsum, cacilds vidis litro abertis. Quem num gosta di mé, boa gentis num é. Praesent vel viverra nisi. Mauris aliquet nunc non turpis scelerisque, eget. Pra lá , depois divoltis porris, paradis. Copo furadis é disculpa de bebadis, arcu quam euismod magna."
        ]

        image = [
            "https://exame.com/wp-content/uploads/2020/09/the-sandwich-popeyes-burger-king-e1599567751664.jpg?quality=70&strip=info&w=1024",
            "https://upload.wikimedia.org/wikipedia/commons/6/62/NCI_Visuals_Food_Hamburger.jpg",
            "https://aletp.com.br/wp-content/uploads/2017/10/mcvegan.jpg",
            "https://www.alegrafoods.com.br/wp-content/uploads/2020/07/9-img-blog.png",
            "https://www.hojetemfrango.com.br/wp-content/uploads/2019/01/shutterstock_333724454.jpg",
            "https://s2.glbimg.com/6TYFXwek9ZpNXFeOzas09KizMKk=/0x0:1280x853/924x0/smart/filters:strip_icc()/i.s3.glbimg.com/v1/AUTH_e84042ef78cb4708aeebdf1c68c6cbd6/internal_photos/bs/2020/T/K/Hh8h2GR96v392DAkAqyA/912c9713-321e-4dfd-bca9-888c05c5ce50.jpeg",
            "http://i.mlcdn.com.br/portaldalu/fotosconteudo/43225.jpg"
        ]

        fields = "name,description,price,image"
        for i, _ in enumerate(name):

            values = f"'{name[i]}','{description[i]}','{str(price[i])}','{image[i]}'"
            try:
                conn = Conn()
                self.assertEqual(
                    conn._insertItem(fields, values, table="product"), True)
            except Exception as e:
                print("TEST_PRODUCT============>", e)
Exemplo n.º 20
0
    def send_login(self):
        con = Conn(self.ip4_t, self.ip6_t, self.port_t)

        if con.connection():

            addr = Util.ip_formatting(self.ip4_l, self.ip6_l, self.port_l)

            packet = "LOGI" + addr

            con.s.send(packet.encode())

            recv_packet = con.s.recv(20)
            if (recv_packet[:4].decode() == 'ALGI'):
                db = dataBase()
                db.updateConfig('sessionId', recv_packet[4:].decode())
                db.updateConfig('mode', 'logged')
                Util.sessionId = recv_packet[4:].decode()
                del db
                Util.mode = "logged"
            else:
                Util.printLog("login failed: " + recv_packet.decode())
        else:
            Util.printLog('Connection refused...')
Exemplo n.º 21
0
	def search_neighbors(self, db, ip_request, new_quer):
		self.neighbors = db.retrieveNeighborhood(self.config) #mi tiro giù i vicini
		Util.printLog("------------------------- Sono tornato nel threadQuer ------------------------")
		for n in self.neighbors:
			addr = Util.ip_deformatting(n[0], n[1], None)
			Util.printLog("------------- Dentro al for di threadQUER -----------------------")
			#ip4 = ipad.ip_address(n[0][:15])
			ip6 = ipad.ip_address(n[0][16:])
			self.con = Conn(addr[0], str(ip6), addr[2])
			try:
				Util.printLog("-----------------Dentro alla connection threadQUER --------------")
				if((addr[0] != ip_request) and (str(ip6) != ip_request) and (new_quer[20:35] != addr[0])):
					self.con.connection()
					self.con.s.send(new_quer.encode())
					Util.printLog('QUER: inoltro richiesta a : ' + str(addr[0]))
					self.con.deconnection()
					#Util.printLog(str(addr[0]))
				Util.printLog('QUER:deconection neighbors')
			except IOError as expt:
				print("Errore di connessione")
				print(expt)
				sys.exit(0)
		Util.printLog('QUER:fine neighbors')
Exemplo n.º 22
0
    def run(self):

        # LOOK

        ers = []  # Lista per il menù

        db = dataBase()
        sessionid = db.retrieveConfig(('sessionId', ))

        con = Conn(self.t_ipv4, self.t_ipv6, self.t_port)
        if con.connection():

            pkt_look = 'LOOK' + sessionid + self.search.ljust(20)

            con.s.send(pkt_look.encode())

            ack_look = con.s.recv(7)  # Ricezione intestazione
            bytes_read = len(ack_look)

            while bytes_read < 7:

                ack_look += con.s.recv(7 - bytes_read)
                bytes_read = len(ack_look)

            nanswer = int(ack_look[4:7].decode())
            list_answers = []

            for _ in range(nanswer):  # Per ogni md5

                answer = con.s.recv(148)
                bytes_read = len(answer)

                while bytes_read < 148:

                    answer += con.s.recv(148 - bytes_read)
                    bytes_read = len(answer)

                md5_lfile_lpart = (answer[:32].decode(),
                                   answer[132:142].decode(),
                                   answer[142:148].decode(),
                                   answer[32:132].decode().strip())
                list_answers.extend(
                    (answer[32:132].decode().strip(), md5_lfile_lpart))

            list_answers.extend(("Abort", None))

            con.deconnection()

            Util.searchLock.acquire()
            Util.activeSearch += 1
            Util.searchLock.release()
            Util.menuLock.acquire()
            # Menù
            md5 = curses.wrapper(Util.menu, list_answers, ['Select a file:'])

            # md5[0] -> md5, md5[1] -> lenFile, md5[2] -> lenPart
            if md5 != None:

                if Path('Files/' + md5[3]).is_file():

                    res = curses.wrapper(
                        Util.menu, ['Yes', True, 'No', False],
                        ['The file requested already exists. Override it?'])

                    if not res:

                        print('Overwrite? Nop')
                        exit()

                pkt_fchu = "FCHU" + sessionid + md5[0]

                lenfile = int(md5[1])
                lenpart = int(md5[2])
                infoFile = md5[3]  # Mi tengo solo il nome del file
                md5 = md5[0]
                nBit = int(math.ceil(lenfile / lenpart))
                Util.printLog(str(len(infoFile)))
            else:

                Util.printLog("Download aborted...")
                Util.menuLock.release()

                Util.searchLock.acquire()
                Util.activeSearch -= 1
                if Util.activeSearch == 0:

                    Util.searchIncoming.acquire()
                    Util.searchIncoming.notify()
                    Util.searchIncoming.release()

                Util.searchLock.release()

                exit()
        else:

            Util.printLog("Error. Unable to connect to the tracker")
            exit()

        Util.menuLock.release()

        Util.searchLock.acquire()
        Util.activeSearch -= 1

        if Util.activeSearch == 0:

            Util.searchIncoming.acquire()
            Util.searchIncoming.notify()
            Util.searchIncoming.release()

        Util.searchLock.release()

        #FINE LOOK

        queue = LifoQueue()  #Coda LIFO
        controllerIsAlive = False  # Stato del controller di download

        ######### CREO LA GRAFICA INIZIALE

        Util.lockGraphics.acquire()

        rowNumber = len(Util.rows)  # Numero di file attualmente visualizzati

        descriptor = 'File' + str(Util.uniqueIdRow)
        Util.uniqueIdRow += 1
        Util.rows.append(
            descriptor)  # Salvo il tag che identifica il file in download

        y1 = Util.offsety + Util.nameFileHeight + (Util.heightRow * rowNumber)
        y2 = y1 + Util.heightPart
        for i in range(0, nBit):

            x1 = Util.offsetx + (Util.widthPart * i)
            x2 = Util.offsetx + (Util.widthPart * (i + 1))
            idRec = Util.w.create_rectangle(x1,
                                            y1,
                                            x2,
                                            y2,
                                            fill="red",
                                            width=1,
                                            tags=(descriptor))  # Rettangoli

        # Ridefinizione delle coordinate basate su quelle precedenti
        y1 = y1 + Util.heightPart  # Coordinata Y in alto
        y2 = y2 + Util.heightLine  # Coordinata Y in basso
        for i in range(0, nBit, 10):

            x = Util.offsetx + Util.widthPart * i
            Util.w.create_line(x, y1, x, y2, tags=(descriptor))
            Util.w.create_text(x + Util.LeftPaddingText,
                               y2,
                               anchor="sw",
                               text=str(i + 1),
                               tags=(descriptor))  # Labels

        Util.w.create_text(Util.offsetx,
                           Util.offsety + (Util.heightRow * rowNumber),
                           anchor="nw",
                           text=infoFile,
                           tags=(descriptor))  # Nome file

        dCond = Condition()  # Condizione per fermare il download

        # Bottoni

        #image = Image.open("mazzini.jpeg").resize((20,20), Image.ANTIALIAS)

        b = Button(Util.master, height='10', width='10', image=Util.pause)
        #b.pack()
        b['command'] = lambda: pauseAndplay(b, dCond, queue)
        b.place(x=0, y=Util.offsety + (Util.heightRow * rowNumber))

        b2 = Button(Util.master, height='10', width='10', image=Util.stop)
        #b2.pack(ipadx=20, ipady=Util.offsety + (Util.heightRow * rowNumber))
        b2['command'] = lambda: stop(dCond, queue)
        b2.place(x=20, y=Util.offsety + (Util.heightRow * rowNumber))

        Util.buttonsList.append([b, b2])

        # Statistiche

        Util.w.create_text(Util.labelOffsetx,
                           Util.labelDistance + Util.offsety +
                           (Util.heightRow * rowNumber),
                           anchor="nw",
                           text='Progress: \t\t0%',
                           tags=(descriptor))  # Nome file
        Util.w.create_text(Util.labelOffsetx, (Util.labelDistance * 2) +
                           Util.offsety + (Util.heightRow * rowNumber),
                           anchor="nw",
                           text='Downloaded: \t0',
                           tags=(descriptor))  # Nome file
        Util.w.create_text(Util.labelOffsetx, (Util.labelDistance * 3) +
                           Util.offsety + (Util.heightRow * rowNumber),
                           anchor="nw",
                           text='Total: \t\t' + str(nBit),
                           tags=(descriptor))  # Nome file

        Util.lockGraphics.release()

        #########

        # Risposta di FCHU

        while True:

            c = Conn(self.t_ipv4, self.t_ipv6, self.t_port)

            if not c.connection():

                Util.printLog('Connection Error...')

            else:

                c.s.send(pkt_fchu.encode())

                hitPeers = c.s.recv(7)  # Intestazione pacchetto AFCH
                readB = len(hitPeers)

                listPeers = []  # Tutti i peer
                listStatus = []

                while (readB < 7):
                    hitPeers += c.s.recv(7 - readB)
                    readB = len(hitPeers)

                nBlock = math.ceil(nBit / 8)
                nPeers = int(hitPeers[4:7].decode())
                toReadB = 60 + nBlock  # Ip + stato

                if nPeers == 0:

                    Util.printLog('No peer found...')
                    exit()

                for peer in range(nPeers):  # Per ogni peer

                    infoPeer = c.s.recv(toReadB)
                    readB = len(infoPeer)

                    while (readB < toReadB):
                        infoPeer += c.s.recv(toReadB - readB)
                        readB = len(infoPeer)

                    listPeers.append(infoPeer[:60].decode())  # Peer
                    listStatus.append(list(infoPeer[60:]))  # Stato

                c.deconnection()

                # Creazione di una lista di parti pesata

                statusParts = []  # Lista dello stato delle parti

                for i in range(nBit):
                    statusParts.append([i, 0, []])  # Parte, peso, ip

                for peer in range(nPeers):

                    for block in range(nBlock):

                        bit8 = listStatus[peer][block]  # Isolo il blocco

                        while bit8 > 0:

                            maxBit = 7 - int(log(
                                bit8,
                                2))  # Indice del più alto bit impostato ad 1
                            offset = 8 * block

                            statusParts[maxBit +
                                        offset][1] += 1  # Aumento il peso
                            statusParts[maxBit + offset][2].append(
                                listPeers[peer])  # Inserisco l'ip

                            bit8 = bit8 ^ (1 << (7 - maxBit)
                                           )  # Elimino il bit utilizzato

                shuffle(
                    statusParts
                )  # Mescolo la lista (scelta random delle parti col medesimo peso)

                statusParts = [
                    [part[0], part[2]]
                    for part in sorted(statusParts, key=itemgetter(1))
                ]  # Riordino della lista dalla parte più rara (rarest first)

                if not controllerIsAlive:

                    Util.printLog('DOWNLOAD ATTIVATO')
                    controllerIsAlive = True

                    idPartOne = idRec - (nBit - 1)  # Id del primo rettagolo
                    t = D(statusParts, queue, descriptor, idPartOne, infoFile,
                          lenpart, md5, dCond, b, b2)
                    t.start()

                else:

                    if t.is_alive():

                        queue.put(statusParts)

                    else:

                        print('Terminato')
                        exit()
            sleep(60)
Exemplo n.º 23
0
    def body(self):
        open_conn = Conn(port=3000)
        peersocket = open_conn.initializeSocket()
        db = dataBase()
        c = ['black']
        db.create("tracker")

        # check logged
        pN = plot_net()
        res = db.checkLogged()
        if (res):
            for r in res:
                c.append('green')
                ip = Util.ip_deformatting(r[0], r[1])
                pN.addPeer(ip[0], c)
                pause(0.5)

        while True:
            Util.printLog("###### IN ATTESA DI UNA RICHIESTA #######")
            other_peersocket, addr = peersocket.accept()
            if addr[0][:2] == "::":
                addrPack = addr[0][7:]
                Util.printLog("Richiesta in arrivo da: " + addrPack)
            else:
                addrPack = addr[0]
                Util.printLog("Richiesta in arrivo da: " + addrPack)

            recv_type = other_peersocket.recv(4)

            if (len(recv_type) != 0):
                self.bytes_read = len(recv_type)
                while (self.bytes_read < 4):
                    recv_type += other_peersocket.recv(4 - self.bytes_read)
                    self.bytes_read = len(recv_type)
                Util.printLog("RICHIESTA IN ENTRATA AL TRACKER → " +
                              str(recv_type.decode()))

                # LOGIN ---
                if (recv_type.decode() == "LOGI"):
                    recv_packet = other_peersocket.recv(60)
                    self.bytes_read = len(recv_packet)
                    while (self.bytes_read < 60):
                        recv_packet += other_peersocket.recv(60 -
                                                             self.bytes_read)
                        self.bytes_read = len(recv_packet)

                    th_LOGIN = t_login(other_peersocket, recv_packet.decode())
                    th_LOGIN.start()

                    c.append('green')
                    ip = Util.ip_deformatting(recv_packet[:55].decode(),
                                              recv_packet[55:].decode())
                    pN.addPeer(ip[0], c)
                    pause(1)

                # LOGOUT ---
                if (recv_type.decode() == "LOGO"):
                    recv_packet = other_peersocket.recv(16)
                    self.bytes_read = len(recv_packet)
                    while (self.bytes_read < 16):
                        recv_packet += other_peersocket.recv(16 -
                                                             self.bytes_read)
                        self.bytes_read = len(recv_packet)

                    addr = db.getPeerBySid(recv_packet.decode())
                    if (addr):
                        ip = Util.ip_deformatting(addr[0], addr[1])

                        t_LOGOUT = t_logout(other_peersocket,
                                            recv_packet.decode())
                        t_LOGOUT.start()
                        t_LOGOUT.join()
                        Util.printLog(t_LOGOUT.statusLogout)
                        if (t_LOGOUT.statusLogout == "ALOG"):
                            pN.removePeer(ip[0], c)
                            pause(1)

                # LOOK ---
                if (recv_type.decode() == "LOOK"):
                    Util.printLog("\n→ ARRIVO LOOK ←\n")
                    t_LOOK = t_look(other_peersocket)
                    t_LOOK.start()

                # FCHU ---
                if (recv_type.decode() == "FCHU"):
                    #Util.printLog("\n→ ARRIVO FCHU ←\n")
                    th_FCHU = t_fchu(other_peersocket)
                    th_FCHU.start()

                # ADDR ---
                if (recv_type.decode() == "ADDR"):
                    Util.printLog("\n→ ARRIVO ADDR ←\n")
                    th_ADDR = t_addr(other_peersocket)
                    th_ADDR.start()

                # RPAD ---
                if (recv_type.decode() == "RPAD"):
                    #Util.printLog("\n→ ARRIVO RPAD ←\n")
                    th_RPAD = t_rpad(other_peersocket)
                    th_RPAD.start()
            print(Util.globalDict)
Exemplo n.º 24
0

#mycol = db["CheatSheet"]

#for x in mycol.find():
# print(x)

print("This line will be printed.")
print("------------------------------------------------------------------")

print("This would create first object of CCMP class")
ccmpCode1 = CCMPcode("test1","Cat1",200)
ccmpCode1.displayCCMPcode()

print("This would create first object XX of CCMP class")
ccmpCode2 = Conn("CheatSheet","123")
print("-------------------------------KAROL La Niña de las flores-1--------------------------------")
ccmpCode2.getall()
print("-------------------------------KAROL La Niña de las flores-2--------------------------------")
ccmpCode2.setDB(db)
print("-------------------------------KAROL La Niña de las flores-3--------------------------------")
print(ccmpCode2.db)
print("-------------------------------KAROL La Niña de las flores-4--------------------------------")
#ccmpCode2.getDB(db)
print("-------------------------------KAROL La Niña de las flores---------------------------------")
#pcode = 100
#ccmpCode2.return_code(pcode) 
print("-------------------------------KAROL La Niña de las f---------------------------------")

pcode = 1800
json_codes = ccmpCode2.return_code(pcode)
Exemplo n.º 25
0
    def run(self):
        Util.printLog('\n\nApertura thread SUPE\n\n')
        db = dataBase()

        Util.lock.acquire()

        res = db.retrieveCounterRequest(self.pid, self.pack[20:75])
        if (res == 0):  # Richiesta già conosciuta
            Util.printLog("Eseguo SUPE per: " + self.ipRequest)

            db.insertRequest(self.pid, self.pack[20:75], time.time())

            Util.globalLock.acquire()
            mode = Util.mode  # Prelevo la modalità attuale
            Util.globalLock.release()

            if self.ttl > 1:  # Inoltro richiesta ai vicini

                if mode in ['update', 'updateS']:

                    Util.printLog('Update. Prendo vicini da lista')
                    neighborhood = Util.listPeers

                if mode == 'normal':

                    Util.printLog('Invio SUPE da modalità ::: ' + mode)
                    neighborhood = db.retrievePeers()
                else:

                    Util.printLog('Invio SUPE da modalità ::: ' + mode)
                    neighborhood = db.retrieveSuperPeers()

                Util.lock.release()

                self.ttl = str(self.ttl - 1).zfill(2)
                self.pack = ''.join((self.pack[:80], self.ttl))

                for neighbor in neighborhood:

                    ipv4, ipv6, port = Util.ip_deformatting(
                        neighbor[0], neighbor[1])

                    if ipv4 != self.ipRequest and ipv6 != self.ipRequest and ipv4 != self.ipv4:
                        con = Conn(ipv4, ipv6, port)

                        if con.connection():

                            con.s.send(self.pack.encode())
                            Util.printLog("Inoltro SUPE a vicino ::: " + ipv4)
                            con.deconnection()
                        else:

                            Util.printLog("Inoltro SUPE fallita per ::: " +
                                          ipv4)
            else:

                Util.lock.release(
                )  # Non devo inoltrare, ma devo comunque rilasciare la lock

            if mode in ['updateS', 'super']:  # Sono superpeer e rispondo

                self.pack = 'ASUP' + self.pid + self.myIPP
                Util.printLog('ASUP pacchetto ::: ' + str(self.pack))
                Util.printLog('ASUP verso ::: ' + self.ipv4 + self.ipv6 +
                              str(self.port))

                con = Conn(self.ipv4, self.ipv6, self.port)

                if con.connection():

                    con.s.send(self.pack.encode())
                    Util.printLog('Risposta ASUP a ::: ' + self.ipv4)
                    con.deconnection()
                else:

                    Util.printLog('Risposta ASUP fallita per ::: ' + self.ipv4)

        else:
            Util.lock.release()
            Util.printLog("SUPE per: " + self.ipRequest + ". Già eseguita")
        Util.printLog('\n\nChiusura thread SUPE\n\n')
Exemplo n.º 26
0
    def download(self):
        print("\n--- DOWNLOAD ---\n")

        self.con = Conn(self.ipp2p_B_4, self.ipp2p_B_6, int(self.pp2p_B))
        self.con.connection()

        self.md5 = self.file_signature
        print(self.md5)

        to_peer = "RETR" + self.md5

        self.con.s.send(to_peer.encode('ascii'))

        self.first_packet = self.con.s.recv(10)
        self.bytes_read_f = len(self.first_packet)
        while (self.bytes_read_f < 10):
            self.first_packet += self.con.s.recv(10 - self.bytes_read_f)
            self.bytes_read_f = len(self.first_packet)

        if (self.first_packet[:4].decode() == "ARET"):
            i = self.first_packet[4:10].decode(
            )  # n di chunk o indice del ciclo for

            for j in range(int(i)):
                self.chunk_length = self.con.s.recv(
                    5)  # lunghezza del primo chunk

                self.bytes_read_l = len(self.chunk_length)
                while (
                        self.bytes_read_l < 5
                ):  # controllo che siano stati realmente letti i bytes richiesti
                    self.chunk_length += self.con.s.recv(5 - self.bytes_read_l)
                    self.bytes_read_l = len(self.chunk_length)

                self.chunk = self.con.s.recv(int(self.chunk_length))  # dati
                #self.data_recv.append(self.chunk)
                self.bytes_read = len(self.chunk)

                while (
                        self.bytes_read < int(self.chunk_length)
                ):  # controllo che siano stati realmente letti i bytes richiesti
                    self.chunk += self.con.s.recv(
                        int(self.chunk_length) - self.bytes_read)
                    self.bytes_read = len(self.chunk)
                    #self.data_recv.append(buffer)
                self.data_recv.append(self.chunk)
        self.con.deconnection()

        check_file = Path(self.filename)
        print(check_file)

        if (check_file.is_file()):
            choice = input(
                "\nIl file esiste già nel tuo file system, vuoi sovrascriverlo? (Y,n): "
            )
            if (choice == "Y"):
                os.remove(self.filename)
                file_recv = open(self.filename, "ab")
                for i in self.data_recv:
                    file_recv.write(i)
            else:
                return
        else:
            file_recv = open(self.filename, "ab")
            for i in self.data_recv:
                file_recv.write(i)

        f = open(self.filename, "rb")
        r = f.read()
        print("\n--- FILE DOWNLOADED ---\n")

        self.con2 = Conn(self.ipp2p_dir_4, self.ipp2p_dir_6,
                         int(self.pp2p_dir))
        self.con2.connection()

        self.info_packet = "DREG" + self.sid + self.md5
        self.con2.s.send(self.info_packet.encode('ascii'))

        self.info_recv = self.con2.s.recv(9)
        self.bytes_read_i = len(self.info_recv)
        while (self.bytes_read_i < 9):
            self.info_recv += self.con2.s.recv(9 - self.bytes_read_i)
            self.bytes_read_i = len(self.info_recv)

        if (self.info_recv[:4].decode() == "ADRE"):
            self.num_download = self.info_recv[4:9]

        print(self.num_download)
        self.con2.deconnection()
Exemplo n.º 27
0
def updatePeers():

    globalLock.acquire()
    mode = Util.mode

    if mode == 'normal':
        Util.mode = 'update'
    else:
        Util.mode = 'updateS'
    globalLock.release()

    lock.acquire()
    db = dataBase()

    listNormal = db.retrievePeers()
    listSuper = db.retrieveSuperPeers()

    #db.deletePeers()
    db.deleteSuperPeers()

    config = db.retrieveConfig(('selfV4', 'selfV6', 'selfP', 'ttl'))
    idPacket = ip_packet16()
    ip = ip_formatting(config.selfV4, config.selfV6, config.selfP)

    db.insertRequest(idPacket, ip[:55], time.time())

    lock.release()

    pack = 'SUPE' + idPacket + ip + config.ttl.zfill(2)

    listPeers = listSuper + list(set(listNormal) - set(listSuper))

    globalLock.acquire()
    statusRequest[idPacket] = True
    globalLock.release()

    count = 0

    for peer in listPeers:

        ipv4, ipv6, port = Util.ip_deformatting(peer[0], peer[1])
        con = Conn(ipv4, ipv6, port)

        if con.connection():

            count += 1
            con.s.send(pack.encode())
            printLog("Richiesta SUPE a vicino ::: " + ipv4)
            con.deconnection()

        else:
            printLog("Richiesta SUPE fallita per ::: " + ipv4)

    if count == 0:

        print(
            "                              .-.                                         "
        )
        print(
            "                             (  o)-.                                      "
        )
        print(
            "                              ) )\|\)                                     "
        )
        print(
            "                           _./ (,_                                        "
        )
        print(
            "                          ( '**\"  )                                      "
        )
        print(
            "                          \\\\\   ///                                     "
        )
        print(
            "                           \\\\\|///                                      "
        )
        print(
            "                     _______//|\\\\____________               .           "
        )
        print(
            "                   ,'______///|\\\\\________,'|            \  :  /        "
        )
        print(
            "     _ _           |  ____________________|,'             ' _ '           "
        )
        print(
            "    ' Y ' _ _      | ||              |                -= ( (_) )=-        "
        )
        print(
            "    _ _  ' Y '     | ||              |                    .   .           "
        )
        print(
            "   ' Y '_ _        | ||              |                   /  :  \          "
        )
        print(
            "       ( Y )       | ||              8                      '             "
        )
        print(
            "                   | ||              8                                    "
        )
        print(
            "                   | ||        /\/\  8                                    "
        )
        print(
            "                   | ||      .'   ``/|                                    "
        )
        print(
            "                   | ||      | x   ``|                                    "
        )
        print(
            "                   | ||      |  /. `/`                                    "
        )
        print(
            "                   | ||      '_/|  /```                 .-.               "
        )
        print(
            "                   | ||        (_,' ````                |.|               "
        )
        print(
            "  |J               | ||         |       \             /)|`|(\             "
        )
        print(
            " L|                | ||       ,'         \           (.(|'|)`)            "
        )
        print(
            "  |                | ||     ,','| .'      \           `\`'./'             "
        )
        print(
            "~~~~~~~~~~~~~~~~~~~| ||~~~~~||~~||.        \~~~~~~~~~~~~|.|~~~~~~~~~~~    "
        )
        print(
            "                   | ||     ||  || \        \          ,|`|.              "
        )
        print(
            "  ~~               | ||     \"\"  \"\"  \        \          \"'\"   ~~    "
        )
        print(
            "                   | ||              )   .   )                            "
        )
        print(
            "                   | ||             / ,   ),'|      ~~                    "
        )
        print(
            "             ~~    | ||         ___/ /   ,'  |              (_)           "
        )
        print(
            "      ((__))       | ||   ~~   I____/  ,'    |              /\"/          "
        )
        print(
            "      ( 0 0)       | ||         I____,'      *             ^~^            "
        )
        print(
            "       `\_\\\\       | ||                          ~~                     "
        )
        print(
            "         \"'\"'      | ||                                                 "
        )
        print(
            "  ~~               | ||         ~~                          ~~            "
        )
        print(
            "                   |_|/                                                   "
        )
        print(
            "                                                                          "
        )

        print('\nNobody found after update. Sorry, you\'re on your own\n')
        exit()

    cond = Condition()
    cond.acquire()
    cond.wait(20)
    cond.release()

    globalLock.acquire()
    statusRequest[idPacket] = False
    globalLock.release()

    globalLock.acquire()
    Util.mode = mode
    globalLock.release()
Exemplo n.º 28
0
    def run(self):
        db = dataBase()
        file_find = []
        #ricavo i superpeer a cui sono collegato e inoltro la richiesta nella rete
        superpeers = db.retrieveSuperPeers()
        config = db.retrieveConfig(('selfV4', 'selfV6'))

        Util.globalLock.acquire()
        Util.statusRequest[self.packet[4:20]] = True
        Util.printLog("DIZIONARIO GLOBALE SETTATO ---> " +
                      str(Util.statusRequest[self.packet[4:20]]))
        Util.globalLock.release()

        if (superpeers):
            for sp in superpeers:

                ipv4, ipv6, port = Util.ip_deformatting(sp[0], sp[1])

                if (ipv4 != config.selfV4):
                    conn = Conn(ipv4, ipv6, port)
                    if (conn.connection()):
                        conn.s.send(self.packet.encode())
                        conn.deconnection()
                        Util.printLog("INVIO QUER VERSO " + str(ipv4) +
                                      " RIUSCITO")
                    else:
                        Util.printLog(
                            "INVIO QUER FALLITO VERSO IL SUPER... PROBABILMENTE "
                            + str(ipv4) + " E' OFFLINE")
                        continue

        cond = th.Condition()
        cond.acquire()
        cond.wait(20)
        cond.release()

        Util.globalLock.acquire()
        Util.statusRequest[self.packet[4:20]] = False
        Util.printLog("PASSATI 20 SECONDI.. DIZIONARIO ---> " +
                      str(Util.statusRequest[self.packet[4:20]]))
        Util.globalLock.release()

        #controllo tra i peer loggati a me prima di inoltrare la quer nella rete
        dbS = dataBaseSuper()
        localFile = dbS.findInLocalSP(self.packet[82:])
        Util.printLog("LOCALFILE " + str(localFile))
        #creazione pacchetto di AFIN passati i 20 secondi
        addrPeer = db.retrievePeerSid(self.sid)
        Util.printLog("ADDRPEER " + str(addrPeer))
        resp = db.retrieveResponse(self.packet[4:20])
        ipv4, ipv6, port = Util.ip_deformatting(addrPeer[0][0], addrPeer[0][1])
        for f in resp:
            file_find.append(f[3])
        for ff in localFile:
            file_find.append(ff[1])

        seen = set()
        uniq = []
        for x in file_find:
            if x not in seen:
                uniq.append(x)
                seen.add(x)

        toPeer = "AFIN" + str(len(seen)).zfill(3)

        connP = Conn(ipv4, ipv6, port)
        if (connP.connection()):
            connP.s.send(toPeer.encode())

        buffer_md5 = ''
        for i in resp:
            count = 0
            ll = []
            md5 = i[3]
            if (md5 == buffer_md5):
                continue
            for j in resp:
                if (md5 in j):
                    count = count + 1
                    add = j[1] + j[2]
                    ll.append(add)
            if (count == 1):
                toPeer = md5 + i[4] + str(count).zfill(3) + i[1] + i[2]
                connP.s.send(toPeer.encode())
                Util.printLog("PACCHETTO AFIN 1-----> " + str(toPeer))
            elif (count > 1):
                buffer_md5 = md5
                toPeer = md5 + i[4] + str(count)
                for l in ll:
                    toPeer = toPeer + l
                connP.s.send(toPeer.encode())
                Util.printLog("PACCHETTO AFIN 2+-----> " + str(toPeer))

        buffer_md5_l = ''
        if (localFile):  # se la lista non è vuota entro nel ciclo
            k = 0
            for lf in localFile:
                count = 0
                ll2 = []
                md5 = lf[1]
                Util.printLog("localfile in for " + str(lf))
                addrLocalPeer = db.retrievePeerSid(lf[0])

                if (md5 == buffer_md5_l):
                    continue
                for j in localFile:
                    if (md5 in j):
                        addrLocalPeer_dub = db.retrievePeerSid(j[0])
                        count = count + 1
                        add = addrLocalPeer_dub[0][0] + addrLocalPeer_dub[0][1]
                        ll2.append(add)
                Util.printLog("addrLocalPeer " + str(addrLocalPeer))
                if (count == 1):
                    toPeer = lf[1] + lf[2] + str(1).zfill(
                        3) + addrLocalPeer[0][0] + addrLocalPeer[0][1]
                    k = k + 1
                    connP.s.send(toPeer.encode())
                    Util.printLog("PACCHETTO AFIN 1 LOCAL-----> " +
                                  str(toPeer))
                elif (count > 1):
                    buffer_md5_l = md5
                    toPeer = lf[1] + lf[2] + str(count).zfill(3)
                    for l2 in ll2:
                        toPeer = toPeer + l2
                    connP.s.send(toPeer.encode())
                    Util.printLog("PACCHETTO AFIN 1+ LOCAL-----> " +
                                  str(toPeer))

        connP.deconnection()
Exemplo n.º 29
0
	def run(self):

		Util.w.itemconfig(self.idRect, fill='#0000ff', width=1)
		
		jobDone = False
		for peers in self.listPeers:

			peer = Util.ip_deformatting(peers[:55],peers[55:])
			Util.printLog(str(peer))
			c = Conn(peer[0], peer[1], peer[2]) # ipv4 ipv6 port

			if c.connection():

				packet = 'RETP' + self.md5 + str(self.part).zfill(8) # Preparo il pacchetto RETP

				c.s.send(packet.encode()) # Invio richiesta download

				# Lettura della risposta

				nChunk = c.s.recv(10) # 'AREP' + n° chunks

				readB = len(nChunk)
				while (readB < 10):

					nChunk += c.s.recv(10 - readB)
					readB = len(nChunk)

				nChunk = int(nChunk[4:].decode())

				# Elaborazione dei chunk
				fileDescriptor = open('Files/' + self.fileName, 'r+b')

				fileDescriptor.seek(self.lenPart * (self.part - 1)) # Sposto il puntatore nell'area corretta
				
				for _ in range(nChunk):

					# Estrazione lunghezza chunk

					lenChunk = c.s.recv(5)

					readB = len(lenChunk)
					while (readB < 5):
						lenChunk += c.s.recv(5 - readB)
						readB = len(lenChunk)

					lenChunk = int(lenChunk.decode())

					# Estrazione dati chunk

					dataChunk = c.s.recv(lenChunk)

					readB = len(dataChunk)
					while (readB < lenChunk):
						
						dataChunk += c.s.recv(lenChunk - readB)
						readB = len(dataChunk)
					fileDescriptor.write(dataChunk) # Scrivo il chunk su file

				c.deconnection()
				jobDone = True
				break
			else:
				Util.printLog('Connessione peer fallita...')

		if jobDone: # Job completato
			sleep(uniform(0.2,0.5))
			self.wLock.acquire()
			self.data['downloadedParts'] += 1
			self.wLock.release()

			db = dataBase()
			track = db.retrieveConfig(('trackerV4','trackerV6','trackerP', 'sessionId'))

			c = Conn(track.trackerV4, track.trackerV6, track.trackerP)

			maxNumTracker = 5
			for count in range(maxNumTracker):

				if c.connection():

					c.s.send(('RPAD' + track.sessionId + self.md5 + str(self.part).zfill(8)).encode())

					apad = c.s.recv(8)

					readB = len(apad)

					while(readB < 8):
						apad += c.s.recv(8 - readB)
						readB = len(apad)

				else:

					Util.printLog('Connessione al tracker fallita...')

			percent, parts = Util.w.find_withtag(self.tag)[-3:-1] # Terzultimo e penultimo

			Util.w.itemconfig(percent, text='Progress: \t\t' + '{0:.2f}'.format(self.data['downloadedParts'] / self.data['totalParts'] * 100) + '%')
			Util.w.itemconfig(parts, text='Downloaded: \t' + str(self.data['downloadedParts']))
			Util.w.itemconfig(self.idRect, fill='#00ff00', width=1)
		else: # Fallita connessione al peer per scaricare la parte

			Util.w.itemconfig(self.idRect, fill='#ff0000', width=1)
			
			self.wLock.acquire()
			self.missingParts.append(self.part - 1)
			Util.printLog('job failed for : ' + str(current_thread()))
			self.wLock.release()

		self.wLock.acquire()
		self.data['workers'] -= 1
		self.wLock.release()
		Util.dSem.release()
Exemplo n.º 30
0
 def __init__(self, config):
     self.t_ipv4 = config.trackerV4
     self.t_ipv6 = config.trackerV6
     self.t_port = config.trackerP
     self.sid = Util.sessionId
     self.con = Conn(self.t_ipv4, self.t_ipv6, self.t_port)