示例#1
0
文件: search.py 项目: anon1892/WTP
def searchSHA(ndd):
    # Fonction qui a pour but de chercher le sha256 correspondant
    # au nom de domaine passé en paramètres s'il existe
    BDD.verifExistBDD()
    problem = 0
    sha256 = "0"
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT SHA256 FROM DNS WHERE NDD = ?""", (ndd, ))
        rows = cursor.fetchall()
    except Exception as e:
        conn.rollback()
        logs.addLogs("DNS : ERROR : Problem with the database (searchSHA()):" +
                     str(e))
        problem += 1
    else:
        nbRes = 0
        for row in rows:
            nbRes += 1
            if nbRes > 1:
                # On trouve plusieurs fois le même nom de domaine dans la base
                problem = 5
                logs.addLogs("DNS : ERROR: The domain name " + ndd +
                             " is present several times in the database")
            sha256 = row[0]
    conn.close()
    if problem > 1:
        return problem
    if sha256 == "0":
        return "INCONNU"
    return sha256
示例#2
0
def compterStats(colonne):
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        if colonne == "NbNoeuds":
            cursor.execute("""SELECT NbNoeuds FROM Statistiques""")
        elif colonne == "NbFichiersExt":
            cursor.execute("""SELECT NbFichiersExt FROM Statistiques""")
        elif colonne == "NbSN":
            cursor.execute("""SELECT NbSN FROM Statistiques""")
        elif colonne == "NbFichiers":
            cursor.execute("""SELECT NbFichiers FROM Statistiques""")
        elif colonne == "PoidsFichiers":
            cursor.execute("""SELECT PoidsFichiers FROM Statistiques""")
        elif colonne == "NbEnvsLstNoeuds":
            cursor.execute("""SELECT NbEnvsLstNoeuds FROM Statistiques""")
        elif colonne == "NbEnvsLstFichiers":
            cursor.execute("""SELECT NbEnvsLstFichiers FROM Statistiques""")
        elif colonne == "NbEnvsLstFichiersExt":
            cursor.execute("""SELECT NbEnvsLstFichiersExt FROM Statistiques""")
        elif colonne == "NbEnvsFichiers":
            cursor.execute("""SELECT NbEnvsFichiers FROM Statistiques""")
        elif colonne == "NbPresence":
            cursor.execute("""SELECT NbPresence FROM Statistiques""")
        elif colonne == "NbReceptFichiers":
            cursor.execute("""SELECT NbReceptFichiers FROM Statistiques""")
        else:
            logs.addLogs("ERROR : This statistic is unknown : " + str(colonne))
        conn.close()
    except Exception as e:
        logs.addLogs("ERROR : Problem with database (compterStats()):" +
                     str(e))
    conn.close()
    return str(cursor.fetchone())[1:-2]
def test_username_not_exists_execute_button():
    context = BDD.got_to_web()
    textbox = context.find_element_by_id("username")
    textbox.send_keys('noestiejejdlfodjlkhx')
    button = context.find_element_by_id("button_execute")
    button.click()
    assert BDD.list_is_not_empty(context) == False
示例#4
0
def lsteNoeuds():
    # Fonction qui retourne un file qui contient toutes les
    # IP+PORT des noeuds connus par ce noeud
    # et qui sont dans la BDD, un par ligne
    BDD.verifExistBDD()
    try:
        os.makedirs("HOSTEDFILES")
    except OSError:
        if not os.path.isdir("HOSTEDFILES"):
            raise
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    cursor.execute("""SELECT IP FROM Noeuds WHERE 1""")
    rows = cursor.fetchall()
    fileDir = "HOSTEDFILES/TEMP" + str(time.time())
    # On vide le file au cas où
    vidage = open(fileDir, "wb")
    vidage.write("")
    vidage.close()
    # Puis on commence l'importation
    fluxEcriture = open(fileDir, "ab")
    for row in rows:
        fluxEcriture.write(row[0] + "\n")
    fluxEcriture.close()
    return fileName
示例#5
0
文件: search.py 项目: anon1892/WTP
def chercherInfo(nomTable, info):
    # Fonction qui retourne une information demandée dans la table demandée dans une entrée demandé
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        if nomTable == "Noeuds":
            cursor.execute("""SELECT Fonction FROM Noeuds WHERE IP = ?""",
                           (info, ))
        elif nomTable == "Fichiers":
            cursor.execute("""SELECT id FROM Fichiers WHERE Nom = ?""",
                           (info, ))
        elif nomTable == "FichiersExt":
            cursor.execute("""SELECT IP FROM FichiersExt WHERE Nom = ?""",
                           (info, ))
        elif nomTable == "BlackList":
            cursor.execute("""SELECT Rank FROM BlackList WHERE Name = ?""",
                           (info, ))
        else:
            logs.addLogs("ERROR : The table is unknown in chercherInfo : " +
                         str(nomTable))
            return 0
        conn.commit()
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database (chercherInfo()):" +
                     str(e))
    for row in cursor.fetchall():
        conn.close()
        return row[0]
    return 0
def test_textbox_using_enter():
    context = BDD.got_to_web()
    textbox = context.find_element_by_id("username")
    textbox.send_keys('perezreverte')
    textbox.send_keys(Keys.ENTER)
    time.sleep(4)
    assert BDD.list_is_not_empty(context) == True
def test_username_exists_execute_button():
    context = BDD.got_to_web()
    textbox = context.find_element_by_id("username")
    textbox.send_keys('perezreverte')
    button = context.find_element_by_id("button_execute")
    button.click()
    time.sleep(2)
    assert BDD.list_is_not_empty(context) == True
def test_delete_button_filled_textbox():
    context = BDD.got_to_web()
    textbox = context.find_element_by_id("username")
    textbox.send_keys('perezreverte')
    button = context.find_element_by_id("button_delete")
    button.click()
    time.sleep(2)
    assert BDD.textboxt_empty(context) == True
示例#9
0
    def get_item_listbox(self, event):
        widget = event.widget
        items = widget.curselection()
        print("CMA --> Listbox --> Item: ", items[0])
        print("CMA --> Listbox --> All user: "******"CMA --> Listbox --> Current user: "******"CMA --> Listbox --> Value: ",
              Social_Network_App.__All_User[items[0]])
        data_other_user = Social_Network_App.__All_User[items[0]]

        query_conversation = 'SELECT * FROM conversation'
        data_conversations = BDD.show_bdd(query_conversation)

        reference_conversation = str(
            Social_Network_App.__Current_User[0]) + str(data_other_user[3])
        print("CMA --> Listbox --> Reference_conversation:",
              reference_conversation, data_conversations)

        is_old_conver = False
        for ref_conver in data_conversations:
            if ref_conver[3] == reference_conversation or ref_conver[
                    3] == reference_conversation[::-1]:
                is_old_conver = True
                Social_Network_App.__Current_Conversation = ref_conver

        if is_old_conver:
            print("CMA --> Listbox --> The conversation already exists")
        else:
            print("CMA --> Listbox --> The conversation is created")
            # create_conversation = """
            #                     INSERT INTO
            #                         conversation(user_id1, user_id2, reference_conversation, data)
            #                     VALUES
            #                       ("{}", "{}", "{}", "{}")
            #                     """.format(Social_Network_App.__Current_User[0], data_other_user[3],
            #                                reference_conversation,
            #                                None)
            create_conversation = """
                                            INSERT INTO
                                                conversation(user_id1, user_id2, reference_conversation, data)
                                            VALUES
                                              ("{}", "{}", "{}", null)
                                            """.format(
                Social_Network_App.__Current_User[0], data_other_user[3],
                reference_conversation)
            BDD.execute_query(create_conversation)

            select_new_conversation = """
            SELECT * FROM conversation
            WHERE reference_conversation = "{}"
            """.format(reference_conversation)
            Social_Network_App.__Current_Conversation = BDD.show_bdd(
                select_new_conversation)[0]

        print("CMA --> SHOW __CURRENT_CONVERSATION :",
              Social_Network_App.__Current_Conversation)
        self.Activity_Conversation(data_other_user)
示例#10
0
文件: dns.py 项目: anon1892/WTP
def majDNS(ipportNoeud=""):
    # Fonction pour noeud DNS qui permet de mettre à jour toute sa base avec un autre noeud
    BDD.verifExistBDD()
    problem = 0
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    ipport = ""
    if ipportNoeud == "":
        try:
            cursor.execute(
                """SELECT IP FROM Noeuds WHERE Fonction = 'DNS' ORDER BY RANDOM() LIMIT 1"""
            )
            rows = cursor.fetchall()
            conn.close()
        except Exception as e:
            conn.rollback()
            logs.addLogs(
                "DNS : ERROR : Problem with the database (majDNS()):" + str(e))
            problem += 1
        else:
            for row in rows:
                ipport = row[0]
    else:
        ipport = ipportNoeud
        if ipport != "":
            # Maintenant on va demander au noeud DNS distant d'envoyer toutes ses entrées DNS pour
            # Que l'on puisse ensuite analyser, et ajouter/mettre à jour notre base
            connexion_avec_serveur = autresFonctions.connectionClient(ipport)
            if str(connexion_avec_serveur) != "=cmd ERROR":
                sendCmd = b""
                sendCmd = "=cmd DNS syncBase"
                connexion_avec_serveur.send(sendCmd.encode())
                rcvCmd = connexion_avec_serveur.recv(1024)
                rcvCmd = rcvCmd.decode()
                connexion_avec_serveur.close()
                # Le noeud renvoie le nom du fichier à télécharger
                # Et son IP:PortPrincipal, sinon =cmd ERROR
                if rcvCmd != "=cmd ERROR":
                    # =cmd Filename ****** ipport ******
                    filename = rcvCmd[14:rcvCmd.find(" ipport ")]
                    ipport = rcvCmd[rcvCmd.find(" ipport ") + 8:]
                    ip = ipport[:ipport.find(":")]
                    port = ipport[ipport.find(":") + 1:]
                    error += fctsClient.CmdDemandeFichier(ip, port, filename)
                    if error == 0:
                        echangeListes.filetoTable(filename, "DNS")
                    else:
                        problem += 1
                else:
                    problem += 1
            else:
                problem += 1
        else:
            problem += 1
    return problem
示例#11
0
文件: dns.py 项目: anon1892/WTP
def modifEntree(nomTable, entree, entree1="", entree2=""):
    # Fonction qui permet de supprimer une entrée dans une table
    # Paramètres : Le nom de la table; le nouveau SHA256; le nom de domaine; le mot de passe non hashé
    problem = 0
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        if nomTable == "DNS":
            if entree1 != "" and entree2 != "":
                # On vérifie que le mot de passe hashé est égal à celui de la base de données,
                # et si c'est le cas on peut suprimer la ligne
                cursor.execute("""SELECT PASSWORD FROM DNS WHERE NDD = ?""",
                               (entree1, ))
                rows = cursor.fetchall()
                nbRes = 0
                for row in rows:
                    nbRes += 1
                    if row[0] == hashlib.sha256(
                            str(entree2).encode()).hexdigest():
                        cursor.execute(
                            """UPDATE DNS SET SHA256 = ? WHERE NDD = ?""",
                            (entree, entree1))
                        conn.commit()
                    else:
                        # Le mot de passe n'est pas valide.
                        problem = 5
                if nbRes == 0:
                    logs.addLogs(
                        "DNS : ERROR: The domain name to modify does not exist (modifEntree())"
                    )
                    problem = 8
                    problem += ajouterEntree("DNS", entree1, entree, entree2)
            else:
                logs.addLogs(
                    "DNS : ERROR: There is a missing parameter to perform this action (modifEntree())"
                )
                problem += 1
        else:
            logs.addLogs(
                "DNS : ERROR: The table name was not recognized (modifEntree()) : "
                + str(nomTable))
            problem += 1
        conn.commit()
    except Exception as e:
        conn.rollback()
        logs.addLogs(
            "DNS : ERROR : Problem with the database (modifEntree()):" +
            str(e))
        problem += 1
    else:
        logs.addLogs("DNS : INFO : The domain name " + entree1 +
                     " has been modified.")
    conn.close()
    return problem
def test_delete_button_filled_list():
    context = BDD.got_to_web()
    textbox = context.find_element_by_id("username")
    textbox.send_keys('perezreverte')
    button = context.find_element_by_id("button_execute")
    button.click()
    time.sleep(5)
    button2 = context.find_element_by_id("button_delete")
    button2.click()
    time.sleep(2)
    assert BDD.list_is_not_empty(context) == False
def test_empty_list_when_introduce_non_exist_twitter():
    context = BDD.got_to_web()
    textbox = context.find_element_by_id("username")
    textbox.send_keys('perezreverte')
    button = context.find_element_by_id("button_execute")
    button.click()
    time.sleep(5)
    textbox.send_keys('noestiejejdlfodjlkhx')
    button.click()
    time.sleep(2)
    assert BDD.list_is_not_empty(context) == False
示例#14
0
	def run(self):
		print("Welcome in the Blacklist center !\nWhat do you want to do ?")
		action = autresFonctions.ask("1 : Add something in the BlackList\n2 : Delete something in the BlackList\n3 : Update the Blacklist with an other peer\n4 : Change the BlackList default peer")
		try:
			action = int(action)
		except ValueError as e:
			print(str(c("red")+"Your input isn't correct (between 1 and 4)\nError : "+str(e)+""+str(c(""))))
		if action == 1:
			entree = autresFonctions.ask("What do you want to add in your BlackList ?")
			while 1:
				rank = autresFonctions.ask("What is the rank of this new entry ?")
				try:
					if int(rank) > 0 and int(rank) <= 5:
						break
				except ValueError as e:
					print(str(c("red")+"Your input isn't correct. (between 1 and 5)\nError : "+str(e)+""+str(c(""))))
			error = BDD.ajouterEntree("BlackList", entree, rank)
			if error == 0:
				print(str(c("yellow")+""+str(entree) + " has been added in the BlackList with the rank " + str(rank)+""+str(c(""))))
			else:
				print(str(c("red")+"An error occured. Look at the logs for more informations. ("+str(error)+")"+str(c(""))))
		elif action == 2:
			entree = autresFonctions.ask("What do you want to delete in your BlackList ?")
			error = BDD.supprEntree("BlackList", entree)
			if error == 0:
				print(str(c("yellow")+""+str(entree) + " has been deleted in the BlackList"+str(c(""))))
			else:
				print(str(c("red")+"An error occured. Look at the logs for more informations. ("+str(error)+")"+str(c(""))))
		elif action == 3:
			ipport = str(autresFonctions.ask("With which peer do you want to update? (Press ENTER to update with the default peer : "+str(config.readConfFile("BlackList"))+")"))
			if ipport == "":
				status = loader("Work in progress")
				status.start()
				blacklist.maj()
				status.stop()
				status.join()
			elif autresFonctions.verifIPPORT(IppeerPort): # Si ipport est un ip:port
				status = loader("Work in progress")
				status.start()
				blacklist.maj(ipport)
				status.stop()
				status.join()
			else:
				print(str(c("red")+"This is not a IP:PORT"+str(c(""))))
		elif action == 4:
			value = str(autresFonctions.ask("Which peer do you want to choose to be your default blacklist peer ? (The actual peer is "+str(config.readConfFile("Blacklist"))))
			if autresFonctions.verifIPPORT(value):
				config.modifConfigFile("Blacklist", value)
			else:
				print(str(c("red")+"Your input isn't a IP:PORT"+str(c(""))))
		else:
			print(str(c("red")+"Your input isn't correct."+str(c(""))))
示例#15
0
文件: fctsMntc.py 项目: anon1892/WTP
def checkIntruders():
    # Cette fonction a pour but de vérifier qu'il n'y a pas de fichiers
    # Qui ne devrait pas l'être dans HOSTEDFILES, sinon ils sont supprimés
    for file in os.listdir("HOSTEDFILES/"):
        file = "HOSTEDFILES/" + file
        if os.path.isdir(str(file)) is False:
            # C'est un fichier, on vérifie qu'il existe dans la BDD
            BDD.verifExistBDD()
            conn = sqlite3.connect('WTP.db')
            cursor = conn.cursor()
            try:
                cursor.execute("""SELECT ID FROM Fichiers WHERE Chemin = ?""",
                               (file, ))
                conn.commit()
            except Exception as e:
                conn.rollback()
                logs.addLogs(
                    "ERROR : Problem with database (checkIntruders()):" +
                    str(e))
                error += 1
            rows = cursor.fetchall()
            if str(rows) == "[]":
                # Il n'existe pas, on le déplace vers ADDFILES
                dest = "ADDFILES/" + str(file[12:])
                if file != dest:
                    if os.path.exists(dest) is False:
                        # Exception pour les fichiers temporels :
                        # On les supprime si ils ont plus de 24h
                        if str(file[12:16]) == "TEMP":
                            actTime = str(time.time())
                            if int(file[16:file.find(".")]) < int(
                                    actTime[:actTime.find(".")]) - 86400:
                                os.remove(file)
                                logs.addLogs(
                                    "INFO : A temporary file has been deleted : "
                                    + str(file[12:]))
                        else:
                            try:
                                shutil.copyfile(file, dest)
                            except Exception as e:
                                logs.addLogs(
                                    "ERROR : The file " + file +
                                    " could not be copied in checkIntruders : "
                                    + str(e))
                            else:
                                os.remove(file)
                                logs.addLogs(
                                    "INFO : The file has been moved from HOSTEDFILES to ADDFILES because it was not in the database"
                                )
        else:
            # C'est un dossier, on supprime
            shutil.rmtree(file)
示例#16
0
def comptNbNoeuds():
    # Fonction qui compte le nombre total de neouds connus par le noeud,
    # Puis qui met à jour la base de données avec la fonction adéquate
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT id FROM Noeuds WHERE 1""")
        rows = cursor.fetchall()
    except Exception as e:
        logs.addLogs("ERROR : Problem with the database (comptNbNoeuds()):" +
                     str(e))
    nbTotal = 0
    for row in rows:
        nbTotal += 1
    # On met à jour directement dans la BDD
    modifStats("NbNoeuds", nbTotal)
示例#17
0
def comptTaillFchsTtl():
    # Fonction qui compte la taille totale de tous les files hébergés sur le noeud,
    # Puis qui met à jour la base de données avec la fonction adéquate
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute("""SELECT Taille FROM Fichiers WHERE 1""")
        rows = cursor.fetchall()
    except Exception as e:
        logs.addLogs(
            "ERROR : Problem with the database (comptTaillFchsTtl()):" +
            str(e))
    tailleTotale = 0
    for row in rows:
        tailleTotale += row[0]
    # On met à jour directement dans la BDD
    modifStats("PoidsFichiers", tailleTotale)
示例#18
0
    def Button_Send_Message(self, root):
        try:
            print("CMA -> Click Button Send Message -> Message: ",
                  self.Entry_New_Message_user.get(), " User: "******" Conver: ",
                  Social_Network_App.__Current_Conversation)
            Social_Network_App.__Chat_data = Social_Network_App.__Current_Conversation[
                4]
            print("CMA -> Click Button Send Message -> IsNone?: ",
                  Social_Network_App.__Chat_data)

            if Social_Network_App.__Chat_data is None:
                print("CMA -> Click Button Send Message -> IsNone? YES")
                Set_New_chat = BDD.to_serizable_data([[
                    str(Social_Network_App.__Current_User[0]),
                    self.Entry_New_Message_user.get()
                ]])
                print("-----> ENVIAMOS: ", Set_New_chat)
                query_update_conversation = """UPDATE conversation SET data = "{}" where conversation_id = "{}" """.format(
                    Set_New_chat, Social_Network_App.__Current_Conversation[0])
                BDD.execute_query(query_update_conversation)
            else:
                print("CMA -> Click Button Send Message -> IsNone? NO")
                select_chat_conversation = """
                            SELECT data FROM conversation
                            WHERE conversation_id = "{}"
                            """.format(
                    Social_Network_App.__Current_Conversation[0])
                chat_serizable = BDD.show_bdd(select_chat_conversation)
                Social_Network_App.__Chat_data = BDD.to_not_serizable_data(
                    chat_serizable)
                print("\n VIEW CHAT: ", Social_Network_App.__Chat_data)
                Social_Network_App.__Chat_data.append([
                    str(Social_Network_App.__Current_User[0]),
                    self.Entry_New_Message_user.get()
                ])
                Set_New_chat = BDD.to_serizable_data(
                    Social_Network_App.__Chat_data)
                query_update_conversation = """UPDATE conversation SET data = "{}" where conversation_id = "{}" """.format(
                    Set_New_chat, Social_Network_App.__Current_Conversation[0])
                BDD.execute_query(query_update_conversation)
                print("\n VIEW CHAT: ", Social_Network_App.__Chat_data)
            root.config(state="normal")
            root.delete("1.0", "end")
            for index, item in enumerate(Social_Network_App.__Chat_data):
                if str(Social_Network_App.__Current_User[0]) == item[0]:
                    root.insert(tk.INSERT, f"You: {item[1]}\n")
                else:
                    root.insert(tk.INSERT, f"THEY: {item[1]}\n")
            root.config(state="disabled")

        except Exception as e:
            print(messagebox.showinfo(message="ERROR", title="Warning!"))
            print(f"CMA -> Click Button Send Message -> Error -> {e}")
示例#19
0
def GetResponse():
    if BDD.clientExists(IP=request.remote_addr,
                        USER_AGENT=request.headers.get('User-Agent')):
        return ''
    try:
        responselist = json.loads('[{}]'.format(
            str(request.stream.read(), 'UTF-8')))
        if all(
                int(i) < len(BDD.getQuestions()) and int(i) >= 0
                for i in responselist):
            print('before')
            userid = BDD.createUser(
                IP=request.remote_addr,
                USER_AGENT=request.headers.get('User-Agent'))
            BDD.insertResponse(userid, responselist)
            print('done')
    finally:
        print('exception')
        return ''
示例#20
0
文件: search.py 项目: anon1892/WTP
def searchNoeud(role, nbre=10):
    # Fonction qui  pour but de chercher 'nbre' noeuds ayant pour role 'role'
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    try:
        cursor.execute(
            """SELECT IP FROM Noeuds WHERE Fonction = ? ORDER BY RANDOM() LIMIT ?""",
            (role, nbre))
        conn.commit()
    except Exception as e:
        conn.rollback()
        logs.addLogs("ERROR : Problem with database (aleatoire()):" + str(e))
    rows = cursor.fetchall()
    tableau = []
    for row in rows:
        tableau.append(row)
        # On remplit le tableau avant de le retourner
    conn.close()
    return tableau
示例#21
0
def DemandeNoeuds(IppeerPort):
    #Le paramètre à donner est l'ip suivie du port du Noeud à contacter sous la forme 000.000.000.000:00000
    #Départager l'IP et le port
    error = 0
    if autresFonctions.verifIPPORT(IppeerPort):
        connexion_avec_serveur = autresFonctions.connectionClient(ipport)
        if str(connexion_avec_serveur) == "=cmd ERROR":
            error += 1
        else:
            logs.addLogs(
                "INFO : Connection with peer etablished (DemandeNoeuds())")
            sendCmd = b""
            sendCmd = "=cmd DonListeNoeuds 48"
            sendCmd = sendCmd.encode()
            # On envoie le message
            ConnectionDemande.send(sendCmd)
            ListeNoeudsEnc = ConnectionDemande.recv(1024)
            ListeNoeuds = ListeNoeudsEnc.decode()
            ConnectionDemande.close()
            #Les 48 IP+port sont sous la forme 000.000.000.000:00000 et sont séparés par une virgule
            #Départager les IP et les ports et envoi à la BDD par l'intermédiaire
            # de la fonction spécifique
            for loop in range(ListeNoeuds.count(',') + 1):
                lsteTemp = ListeNoeuds[:ListeNoeuds.find(',')]
                ListeNoeuds = ListeNoeuds[ListeNoeuds.find(',') + 1:]
                if autresFonctions.verifIPPORT(lsteTemp):
                    if blacklist.searchBlackList(lsteTemp) == 0:
                        BDD.ajouterEntree("Noeuds", lsteTemp)
                    else:
                        logs.addLogs(
                            "ERROR : This peer is part of the Blacklist : " +
                            str(lsteTemp))
                else:
                    logs.addLogs(
                        "ERROR : The variable isn't a IP:PORT in DemandeNoeuds() : "
                        + str(lsteTemp))
            logs.addLogs("INFO : Connection closed. (DemandeNoeuds())")
    else:
        error += 1
    return error
示例#22
0
文件: fctsMntc.py 项目: anon1892/WTP
def verifNoeud():
    BDD.verifExistBDD()
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    cursor.execute("""SELECT IP FROM Noeuds WHERE 1""")
    rows = cursor.fetchall()
    for row in rows:
        # Prend un à un chaque noeud de la liste, et lui envoie une request.
        # Si le noeud répond, on le laisse tranquille, sinon on le met dans une autre table.
        IppeerPort = row[0]
        #Départager l'IP et le port
        pos1 = IppeerPort.find(":")
        pos1 = pos1 + 1
        pos2 = len(IppeerPort)
        peerPort = int(IppeerPort[pos1:pos2])
        pos1 = pos1 - 1
        peerIP = IppeerPort[0:pos1]
        # Liaison tcp/ip
        c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # Connection au receveur
        try:
            c.connect((peerIP, peerPort))
        except Exception as erreur:
            # Le noeud est injoignable, on le déplace dans une autre table.
            BDD.ajouterEntree("NoeudsHorsCo", IppeerPort)
            BDD.supprEntree("Noeuds", IppeerPort)
            logs.addLogs("INFO : Connection to the peer impossible : '" +
                         str(erreur) + "' (verifNoeud())")
        else:
            sendCmd = "=cmd DemandePresence"
            sendCmd = sendCmd.encode()
            # On envoie le message
            c.send(sendCmd)
            rcvData = c.recv(1024)
            rcvData = rcvData.decode()
            if rcvData != '=cmd Present':
                # Le noeud n'est pas connecté au réseau, on le déplace dans une autre table.
                BDD.ajouterEntree("NoeudsHorsCo", IppeerPort)
                BDD.supprEntree("Noeuds", IppeerPort)
示例#23
0
def connectionClient(ip, port="", verify=1):
    if port == "":
        port = ip[ip.find(":") + 1:]
        ip = ip[:ip.find(":")]
    if verifIPPORT(str(ip) + ":" + str(port)):
        try:
            conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            conn.settimeout(15)
            #conn = ssl.wrap_socket(conn, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
            conn.connect((ip, int(port)))
        except Exception as e:
            logs.addLogs("INFO : Unable to connect to " + str(ip) + ":" +
                         str(port) + " Reason : " + str(e))
        else:
            return conn
    if verify == 1:
        # On ajoute le noeud dans la liste des noeuds Hors Connection s'il n'y est pas déjà
        # (Mais on ne l'incrémente pas s'il l'est déjà)
        IppeerPort = ip + ":" + str(port)
        BDD.ajouterEntree("NoeudsHorsCo", IppeerPort)
        BDD.supprEntree("Noeuds", IppeerPort)
    return "=cmd ERROR"
示例#24
0
def buildBDDmain(example):
    try:
        bdd = BDD.bdd_init(
            example)  # "python/programoutput/" + uniqid + ".txt"

    except pb.Parse_Error as e:
        ERR_str = "There was an error parsing your file, please check your syntax\n" \
                  + e.value + "\n"
        exit_err()

    if len(bdd["var_order"]) > BDD_VAR_LENGTH:
        ERR_str = "Your formula contains too many variables for the web interface. Please try again with less than 14 variables or download the BDD package and run it on your own machine."
        exit_err()

    if len(pb.print_expr(bdd["expr"])) > 500:
        ERR_str = "Your formula is too long for the web interface. Please try again with a smaller formula or download the BDD package and run it on your own machine."
        exit_err()

    BDD.ite_build(bdd)

    stats = BDD.stat_string(bdd)
    sat_count = BDD.sat_count(bdd)
    variable_order = bdd["var_order"]
    sat_assigns = BDD.all_sat(bdd)
    sat_assigns_string = ""
    for x in sat_assigns:
        sat_assigns_string += str(list(map(lambda y: 0
                                           if '~' in y else 1, x))) + '\n'

    dot_file = uniqid + ".dot"
    #    print("dot_file = ", dot_file)
    #    print("BDD = ", bdd)

    BDD.dot_bdd(bdd, dot_file)
    #print reduce(lambda x, y : x + " " + y, [dot_PATH, dot_ARGS, dot_file, dot_OUT])
    #err = os.system(reduce(lambda x, y : x + " " + y, [dot_PATH, dot_ARGS, dot_file, dot_OUT]))
    #print( rm + " " + dot_file )
    #   print("Dot file left behind as", dot_file)
    #os.system(rm + " " + dot_file)

    #   if err != 0:
    #       ERR_str = "There was an error running dot on the server"
    #       exit_err()

    STAT_str = "Number of satisfying assignments: " + str(sat_count) + "\n"\
                + stats + "\n\nAll satisfying assignments:\n" + "------------------------------\n"\
                + sat_assigns_string
    print("Satisfying string is", STAT_str)
示例#25
0
    def insert_user(self):

        create_user = """
        INSERT INTO
            users(user_name, user_lastname, user_email, user_password)
        VALUES
          ("{}", "{}", "{}", "{}")
        """.format(self.user_name, self.user_lastname, self.user_email,
                   self.user_password)
        print("Logical_Data -> Class Insert_user", create_user)

        #Insert user to DBB
        isReady = BDD.execute_query(create_user)
        return isReady
示例#26
0
文件: blacklist.py 项目: anon1892/WTP
def maj(ipport=""):
    # Fonction pour noeud DNS qui permet de mettre à jour toute sa base avec un autre noeud
    BDD.verifExistBDD()
    error = 0
    if ipport == "":
        ipport = str(config.readConfFile("Blacklist"))
    else:
        if ipport != "":
            connexion_avec_serveur = autresFonctions.connectionClient(ipport)
            if str(connexion_avec_serveur) != "=cmd ERROR":
                sendCmd = b""
                sendCmd = "=cmd BlackList sync"
                connexion_avec_serveur.send(sendCmd.encode())
                rcvCmd = connexion_avec_serveur.recv(1024)
                rcvCmd = rcvCmd.decode()
                connexion_avec_serveur.close()
                # Le noeud renvoie le nom du fichier à télécharger
                # Et son IP:PortPrincipal, sinon =cmd ERROR
                if rcvCmd != "=cmd ERROR":
                    # =cmd Filename ****** ipport ******
                    filename = rcvCmd[14:rcvCmd.find(" ipport ")]
                    ipport = rcvCmd[rcvCmd.find(" ipport ") + 8:]
                    ip = ipport[:ipport.find(":")]
                    port = ipport[ipport.find(":") + 1:]
                    error += fctsClient.CmdDemandeFichier(ip, port, filename)
                    if error == 0:
                        echangeListes.filetoTable(filename, "BlackList")
                    else:
                        error += 1
                else:
                    error += 1
            else:
                error += 1
        else:
            error += 1
            logs.addLogs("ERROR : No peer ip was found in Blacklist.maj()")
    return error
示例#27
0
def lsteFichiers(filesExternes=0):
    # ATTENTION !! IL FAUT CONNAITRE SON IP EXTERNE POUR POUVOIR L'AJOUTER EN FIN DE LIGNE
    # CAR CHAQUE LIGNE EST DE TYPE SHA256file.ext @ IP:Port
    # Fonction qui retourne un file qui contient tous les
    # noms des fichers hébergés par le noeud,
    # et qui sont dans la BDD, un par ligne
    # Si filesExternes = 1, on doit faire la liste des focihers externes connus et non des files hébergés
    BDD.verifExistBDD()
    try:
        os.makedirs("HOSTEDFILES")
    except OSError:
        if not os.path.isdir("HOSTEDFILES"):
            raise
    conn = sqlite3.connect('WTP.db')
    cursor = conn.cursor()
    if filesExternes == 0:
        cursor.execute("""SELECT Nom FROM Fichiers WHERE 1""")
    else:
        cursor.execute("""SELECT Nom FROM FichiersExt WHERE 1""")
    rows = cursor.fetchall()
    fileDir = "HOSTEDFILES/TEMP" + str(time.time())
    # On vide le file au cas où
    vidage = open(fileDir, "wb")
    vidage.write("")
    vidage.close()
    # On cherche notre IP
    monIP = connaitreIP()
    # Puis on commence l'importation
    fluxEcriture = open(fileDir, "ab")
    for row in rows:
        if filesExternes == 0:
            fluxEcriture.write(row[0] + " @ " + monIP + ":" +
                               str(config.readConfFile("defaultPort")) + "\n")
        else:
            fluxEcriture.write(row[0] + " @ " + row[1] + "\n")
    fluxEcriture.close()
    return fileName
示例#28
0
文件: parser.py 项目: anon1892/WTP
 def run(self):
     while self.allume:
         BDD.verifExistBDD()
         conn = sqlite3.connect('WTP.db')
         cursor = conn.cursor()
         try:
             cursor.execute("""SELECT IP FROM Noeuds WHERE 1""")
             rows = cursor.fetchall()
         except Exception as e:
             conn.rollback()
             logs.addLogs("ERREUR : Problem with database (parseAll()) : " +
                          str(e))
         for row in rows:
             if autresFonctions.verifIPPORT(row):  # Si row est un ip:port
                 host = row[:row.find(":")]
                 port = row[row.find(":") + 1:]
                 # Pour chaque noeud on demande la liste de :
                 # tous les files qu'il héberge (=cmd DemandeListeFichiers)
                 fctsClient.CmdDemandeListeFichiers(host, port)
                 # tous les files externes qu'il connait (=cmd DemandeListeFichiersExt)
                 fctsClient.CmdDemandeListeFichiers(host, port, 1)
                 # tous les noeuds qu'il connait (=cmd DemandeListeNoeuds)
                 fctsClient.CmdDemandeListeNoeuds(host, port)
         conn.close()
示例#29
0
    def click_button_login(self, root):
        try:
            print("CMA -> Click Button Login -> User: "******"CMA -> Click Button Login -> Error -> {e}")

        else:
            is_match = False
            for item in dates:
                if self.Entry_Email_user.get(
                ) == item[1] and self.Entry_Password_user.get() == item[2]:
                    print("Match!, Go to Main Activity")
                    Social_Network_App.__Current_User = item
                    self.Activity_Main(root)
                    is_match = True
            if not is_match:
                print(
                    messagebox.showinfo(message="User does not match password",
                                        title="Warning!"))
示例#30
0
    def Activity_Main(self, root):
        print("Open Activity Main")
        root.withdraw()  # --> para cerrar ventana anterior.
        win_Activity_Main = tk.Toplevel()
        win_Activity_Main.geometry("800x800")
        win_Activity_Main.config(bg="ghost white",
                                 padx=15,
                                 pady=15,
                                 bd=4,
                                 relief="groove")
        self.set_label(main=win_Activity_Main,
                       textlabel="CONTACTS",
                       istitle=True)
        self.set_label(main=win_Activity_Main,
                       textlabel=" ",
                       position_anchor="nw")

        query_login = '******'
        dates = BDD.show_bdd(query_login)
        Social_Network_App.__All_User = dates

        self.set_listbox(dates, main=win_Activity_Main)

        win_Activity_Main.mainloop()
示例#31
0
import PyBool_public_interface as pb

ERR_str = ""
STAT_str = ""

def exit_err():
    f = open("python/programoutput/error" + uniqid + ".txt", "w")
    f.write(ERR_str)
    f.close()
    exit(0)
    

if __name__ == "__main__":
   
    try:
        bdd = BDD.bdd_init("python/programoutput/" + uniqid + ".txt")
        
    except pb.Parse_Error as e:
        ERR_str = "There was an error parsing your file, please check your syntax\n" \
                  + e.value + "\n"
        exit_err()
        
    if len(bdd["var_order"]) > 14:
        ERR_str = "Your formula contains too many variables for the web interface. Please try again with less than 14 variables or download the BDD package and run it on your own machine."
        exit_err()
                        
    if len(pb.print_expr(bdd["expr"])) > 500:
        ERR_str = "Your formula is too long for the web interface. Please try again with a smaller formula or download the BDD package and run it on your own machine."
        exit_err()

    BDD.reorder_ite_build(bdd)
示例#32
0
文件: runMe.py 项目: KingsleyZ/PyBool
#Tyler Sorensen
#Sept 18, 2011

#This example shows a simple bit-blasting decision procedure.
#See formula.txt for more info

import sys
sys.path.append("../../include/")
sys.path.append("../../../../PyBool/include/")
import BDD
import pdb

if __name__ == "__main__":
    
    #creating and initializing the BDD
    bdd = BDD.bdd_init("formaula2.txt")


    #building the tree
    BDD.ite_build(x)
    BDD.dot_bdd(x,"dotfile4.dot")

    #find and display all sat assignments
    print("All Sat assignments: ")
    print("----------------------------")#

    b = BDD.all_sat(x)

    for q in b:
        print(q)
示例#33
0
文件: runMe.py 项目: KingsleyZ/PyBool
#Tyler Sorensen
#Sept 18, 2011

#Simple example first example. Shows off public for the BDD.

import sys
sys.path.append("../../include/")
sys.path.append("../../../../PyBool/include/")
import BDD
import pdb

if __name__ == "__main__":
    
    #creating and initializing the BDD
    x = BDD.bdd_init("formula.txt")

    #building the tree
    BDD.ite_build(x)

    #find and display all sat assignments
    print("All Sat assignments: ")
    print("----------------------------")

    b = BDD.all_sat(x)

    for q in b:
        print(q)

    print ""
示例#34
0
文件: runMe.py 项目: KingsleyZ/PyBool
#Tyler Sorensen
#Sept 18, 2011

#This example shows how BDD's can be used to test
#the equivalence of formulas.

import sys
sys.path.append("../../include/")
sys.path.append("../../../../PyBool/include/")
import BDD
import pdb

if __name__ == "__main__":
    
    #creating and initializing the BDD
    x = BDD.bdd_init("xor.txt")

    #building the tree
    BDD.ite_build(x)

    print "Are the formulas the same?"
    if BDD.sat_count(x) == 32:
        print "yes"
    else:
        print "No, Here is a counter example:"
        print ""
        print BDD.any_sat(x)

    #BDD.dot_bdd(x, "myDot.dot")
示例#35
0
文件: RunMe.py 项目: KingsleyZ/PyBool
#!/usr/bin/python2.7

#Tyler Sorensen
#Sept 18, 2011

#This example shows how BDD's can be used to show how many
#4 colorings of a given map are available.

#The relationships are that:
#Navada   <-> Utah
#Navada   <-> Arizona
#Utah     <-> Arizona
#Colorado <-> Arizona
#Colorado <-> Utah

import sys
sys.path.append("../../include/")
sys.path.append("../../../../PyBool/include/")
import BDD

if __name__ == "__main__":

    #creating and initializing the BDD
    x = BDD.bdd_init("constraints.txt")
    
    BDD.build(x)
    print "There are " + str(BDD.sat_count(x)) + " four colorings of the map"
示例#36
0
文件: runMe.py 项目: KingsleyZ/PyBool
#!  /usr/bin/env python2.7

#Tyler Sorensen
#Oct 10, 2011

#Simple BDD script to prove that Babies cannot manage crocodiles
#See Solution.txt for a complete walkthrough.

import sys
sys.path.append("../../include/")
sys.path.append("../../../../PyBool/include/")
import BDD

if __name__ == "__main__":
    
    #creating and initializing the BDD
    x = BDD.bdd_init("BabiesAndCrocs.txt")

    
    #building the tree
    BDD.ite_build(x)

    #Can babies manage crocs? If they can't then we should have
    #No satisfying assignments
    BDD.dot_bdd(x,"dotfile.dot")
    print("Can Babies Manage Crocs?")
    if BDD.sat_count(x) == 0:
        print("No")
    else:
        print("Yes")
示例#37
0
文件: runMe.py 项目: KingsleyZ/PyBool
# Oct 10, 2011

# Simple BDD script to prove that Babies cannot manage crocodiles
# See Solution.txt for a complete walkthrough.

import sys

sys.path.append("../../include/")
sys.path.append("../../../../PyBool/include/")
import BDD
import os

if __name__ == "__main__":

    # creating and initializing the BDD
    x = BDD.bdd_init("build8.txt")
    y = BDD.bdd_init("build8.txt")

    # building the tree
    BDD.build(x)
    BDD.ite_build(y)

    BDD.dot_bdd(x, "dotfile1.dot")
    BDD.dot_bdd(y, "dotfile2.dot")

    if BDD.sat_count(x) != BDD.sat_count(y):
        print "error!"

    if BDD.all_sat(x) != BDD.all_sat(y):
        print "error!"
示例#38
0
文件: runMe.py 项目: KingsleyZ/PyBool
#Tyler Sorensen
#Sept 18, 2011

#This example shows the second more complicated Lewis Carroll puzzle.
#See wiseYoungPigs.txt for the formula.

import sys
sys.path.append("../../include/")
sys.path.append("../../../../PyBool/include/")
import BDD

if __name__ == "__main__":
    
    #creating and initializing the BDD
    x = BDD.bdd_init("wiseYoungPigs.txt")

    #building the tree
    BDD.ite_build(x)


    print "Can wise young pigs go up in balloons?"

    if BDD.sat_count(x) == 0:
        print "No"
    else:
        print "Yes, and here's how:"
        
        print ""
        print BDD.any_sat(x)
        BDD.dot_bdd(x,"my_dot.dot")