Exemple #1
0
def rapportErreur(selection=" "):
    # Sélectionne les lignes ayant le mot clef de la selection ou les mots clefs plus graves
    # Envoie le tout à un serveur
    # INFO < WARNING < ERREUR
    megaStr = ""
    with open("logs.txt") as f:
        for line in f:
            if line.find(selection) != -1:
                megaStr += line
    f.close()
    data = {"text": megaStr}
    try:
        requests.post("https://myrasp.fr/WTP/Logs/index.php", data=data)
    except Exception as e:
        addLogs(
            "ERROR : We could not send the logs to the developers in rapportErreur() : "
            + str(e))
        print(
            c("yellow") +
            "We could not send the logs to the developers... \nCheck your Internet connection."
            + c(""))
    else:
        supprLogs()
        addLogs(
            c("cian") + "INFO : The logs have been sent to the developers." +
            c(""))
Exemple #2
0
def ask(question):
    while 1:
        try:
            result = str(input(str(question) + "\n>>> "))
        except ValueError as e:
            print(
                c("red") + "Your input isn't correct. Error : " + str(e) +
                c(""))
        else:
            return result
Exemple #3
0
def connaitreIP():
    # Fonction qui retourne l'IP externe du noeud qui lance cette fonction
    class AppURLopener(FancyURLopener):
        version = "Mozilla/5.0"

    opener = AppURLopener()
    try:
        page = opener.open("https://myrasp.fr/Accueil/monip.php")
    except Exception as e:
        addLogs(
            "ERROR : We could not know the IP to the developers in connaitreIP() : "
            + str(e))
        print(c("yellow") + "Check your Internet connection." + c(""))
    sortie = page.read().decode("utf-8")
    return sortie
def log_completion(host, port, output, exception=None):
    # Increment the count of complete ops. This will
    # drain the queue, causing subsequent calls of this
    # method to block.
    n = completed.get() + 1
    try:
        tstamp = time.asctime().split()[3] # Current time
        if color.has_colors(sys.stdout):
            progress = color.c("[%s]" % color.B(n))
            success = color.g("[%s]" % color.B("SUCCESS"))
            failure = color.r("[%s]" % color.B("FAILURE"))
            exc = color.r(color.B(str(exception)))
        else:
            progress = "[%s]" % n
            success = "[SUCCESS]"
            failure = "[FAILURE]"
            exc = str(exception)
        if exception is not None:
            print progress, tstamp, failure, host, port, exc
        else:
            print progress, tstamp, success, host, port
        if output:
            print output,
        sys.stdout.flush()
    finally:
        # Update the count of complete ops. This will re-fill
        # the queue, allowing other threads to continue with
        # output.
        completed.put(n)
Exemple #5
0
def log_completion(host, port, output, exception=None):
    # Increment the count of complete ops. This will
    # drain the queue, causing subsequent calls of this
    # method to block.
    n = completed.get() + 1
    try:
        tstamp = time.asctime().split()[3]  # Current time
        if color.has_colors(sys.stdout):
            progress = color.c("[%s]" % color.B(n))
            success = color.g("[%s]" % color.B("SUCCESS"))
            failure = color.r("[%s]" % color.B("FAILURE"))
            exc = color.r(color.B(str(exception)))
        else:
            progress = "[%s]" % n
            success = "[SUCCESS]"
            failure = "[FAILURE]"
            exc = str(exception)
        if exception is not None:
            print progress, tstamp, failure, host, port, exc
        else:
            print progress, tstamp, success, host, port
        if output:
            print output,
        sys.stdout.flush()
    finally:
        # Update the count of complete ops. This will re-fill
        # the queue, allowing other threads to continue with
        # output.
        completed.put(n)
Exemple #6
0
def addNoeudDNS(ipport, ipportNoeud):
    error = 0
    if autresFonctions.verifIPPORT(ipport):
        connexion_avec_serveur = autresFonctions.connectionClient(ipport)
        if str(connexion_avec_serveur) == "=cmd ERROR":
            error += 1
        else:
            logs.addLogs("Connection established with the DNS")
            # =cmd DNS AddDNSExt ipport ******
            request = "=cmd DNS AddDNSExt ipport " + ipportNoeud
            request = request.encode()
            connexion_avec_serveur.send(request)
            message = connexion_avec_serveur.recv(1024)
            connexion_avec_serveur.close()
            if message == "=cmd IPPORTDejaUtilise":
                error = 5
                print(
                    str(c("red")) +
                    "The peer DNS is already known by the receiver." +
                    str(c("")))
            elif message == "=cmd SUCCESS":
                print(
                    str(c("green")) +
                    "The DNS pair has been added to the receiver base." +
                    str(c("")))
            else:
                print(
                    str(c("red")) +
                    "An undetermined error occurred. Please try again later or change DNS peer."
                    + str(c("")))
                error = 1
    else:
        error += 1
    return error
Exemple #7
0
def modifConfig():
    # Fonction qui a pour but de modifier le fichier de configuration.
    verifConfig()
    print("Configuration file path : " + str(os.getcwd()) + "/wtp.conf")
    print("This is the actual configuration file :\n")
    f = open("wtp.conf", "r")
    print(f.read() + "\n")
    f.close()
    print("Enter exit to exit this wizard")
    while 1:
        param = input("What would you want to change ? (exit for quit)\n")
        if param == "exit":
            break
        current = str(readConfFile(param))
        if current == "None":
            print(c("red") + "This parameter is unknown." + c(""))
        else:
            print("The current setting is : " + current)
            value = str(input("By what do you want to replace him ?\n"))
            modifConfigFile(param, value)
            print(c("green") + "Done !" + c(""))
        print("\n")
    print(
        c("cian") + "For the changes to take effect, please restart WTP." +
        c(""))
Exemple #8
0
 def run(self):
     status = loader("The DNS service start")
     status.start()
     host = '127.0.0.1'
     port = int(config.readConfFile("VPNPort"))
     logs.addLogs(
         "INFO : The VPN service has started, he is now listening to the port "
         + str(port))
     try:
         try:
             tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
             #tcpsock = ssl.wrap_socket(tcpsock, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
             tcpsock.bind((host, port))
             tcpsock.settimeout(5)
         except OSError as e:
             logs.addLogs("ERROR : In vpn.py : " + str(e))
             logs.addLogs("FATAL : Shutting down...")
             print(
                 c("red") + "An error occured. Please restart WTP." + c(""))
         else:
             logs.addLogs(
                 "INFO : The VPN service has started, he is now listening to the port "
                 + str(port))
             status.stop()
             status.join()
             while self.serveur_lance:
                 try:
                     tcpsock.listen(10)
                     (clientsocket, (ip, port)) = tcpsock.accept()
                 except socket.timeout:
                     pass
                 else:
                     newthread = ClientThread(ip, port, clientsocket)
                     newthread.start()
     except KeyboardInterrupt:
         print(" pressed: Shutting down ...")
         print("")
     logs.addLogs("INFO : WTP service has been stoped successfully.")
Exemple #9
0
def draw(canvas, bricks, margin=0.5, 
        baseline_color=c("#101010")):
    u"""Draw bricks sequence to the canvas
    
    Arguments:
        canvas          - the target pyx.canvas.canvas instance
        bricks          - the list of Brick subclass instance
        margin          - the margin size of each bricks
        baseline_color  - the color of baseline (pyx.color)
    """
    # Calculate total width
    width = margin
    for brick in bricks:
        width += margin + brick._width()
    # Draw baseline
    canvas.fill(pyx.path.rect(0, -0.25, width, 0.5), [baseline_color])
    # Draw bricks
    offset = margin
    for brick in bricks:
        offset += brick.draw(canvas, offset) + margin
Exemple #10
0
def addNDD(ipport, sha, ndd, password):
    error = 0
    if autresFonctions.verifIPPORT(ipport):  # Si ipport est un ip:port
        connexion_avec_serveur = autresFonctions.connectionClient(ipport)
        if str(connexion_avec_serveur) == "=cmd ERROR":
            error += 1
        else:
            logs.addLogs("Connection established with the DNS")
            # =cmd DNS AddDNS sha ******* ndd ******* pass *******
            request = "=cmd DNS AddDNS sha " + str(sha) + " ndd " + str(
                ndd) + " pass " + str(password)
            request = request.encode()
            connexion_avec_serveur.send(request)
            message = connexion_avec_serveur.recv(1024)
            connexion_avec_serveur.close()
            if message == "=cmd NDDDejaUtilise":
                error = 5
                print(
                    str(c("red")) + "The domain name is already used." +
                    str(c("")) +
                    " If it belongs to you, you can modify it provided you know the password."
                )
            elif message == "=cmd SUCCESS":
                print(
                    str(c("green")) +
                    "The domain name and address SHA256 have been associated."
                    + str(c("")))
            else:
                print(
                    str(c("red")) +
                    "An undetermined error occurred. Please try again later or change DNS peer."
                    + str(c("")))
                error = 1
    else:
        error += 1
    return error
Exemple #11
0
def modifNDD(ipport, ndd, adress, password):
    error = 0
    if autresFonctions.verifIPPORT(ipport):
        connexion_avec_serveur = autresFonctions.connectionClient(ipport)
        if str(connexion_avec_serveur) == "=cmd ERROR":
            error += 1
        else:
            logs.addLogs("Connection established with the DNS")
            # =cmd DNS modifNDD ndd ****** adress ****** pass ******
            request = "=cmd DNS modifNDD ndd " + str(ndd) + " adress " + str(
                adress) + " pass " + str(password)
            request = request.encode()
            connexion_avec_serveur.send(request)
            message = connexion_avec_serveur.recv(1024)
            connexion_avec_serveur.close()
            error = 0
            if message == "=cmd IPPORTDejaUtilise":
                error = 5
                print(
                    str(c("red")) +
                    "Le noeud DNS est déjà connu par le receveur." +
                    str(c("")))
            elif message == "=cmd SUCCESS":
                print(
                    str(c("green")) +
                    "Le noeud DNS a bien été ajouté à la base du receveur." +
                    str(c("")))
            else:
                print(
                    str(c("red")) +
                    "An undetermined error occurred. Please try again later or change DNS peer."
                    + str(c("")))
                error += 1
    else:
        error += 1
    return error
Exemple #12
0
 def run(self):
     rcvCmd = self.clientsocket.recv(1024)
     rcvCmd = rcvCmd.decode()
     # Maintenant, vérifions la demande du client.
     if rcvCmd != '':
         if rcvCmd[:19] == "=cmd DemandeFichier":
             # =cmd DemandeFichier  nom sha256.ext  ipport IP:PORT
             # Dirriger vers la fonction UploadFichier()
             # Le noeud distant demande le file, donc on lui envoi, Up !
             # On va chercher les deux informations qu'il nous faut :
             # Le nom du file (sous forme sha256.ext)
             # L'IP et le port du noeud qui a fait la demande (sous forme IP:PORT)
             fileName = rcvCmd[rcvCmd.find(" nom ") +
                               5:rcvCmd.find(" ipport ")]
             IppeerPort = rcvCmd[rcvCmd.find(" ipport ") + 8:]
             if BDD.verifFichier(fileName):
                 error = 0
                 # Le file est présent dans la BDD, on peut l'envoyer
                 temp = str(time.time())
                 thrdUp = echangeFichiers.upFile(IppeerPort, fileName, temp)
                 thrdUp.start()
                 thrdUp.join()
                 # Lire le fichier temporaire pour savoir si il y a eut des erreurs
                 try:
                     f = open(".TEMP/" + temp, "r")
                     error += int(f.read())
                     f.close()
                     os.remove(".TEMP/" + temp)
                 except Exception as e:
                     error += 1
                     logs.addLogs(
                         c("red") +
                         "ERROR : An error occured in CmdDemandeFichier : "
                         + str(e) + c(""))
                 os.remove(".TEMP/" + temp)
                 if error != 0:
                     stats.modifStats("NbEnvsFichiers")
                 else:
                     logs.addLogs(
                         c("red") + "ERROR : An error occured for upload " +
                         str(fileName) + " in thrdLnch.py (" + str(error) +
                         ")" + c(""))
             else:
                 print(
                     c("red") + "This file isn't on this computer : '" +
                     str(fileName) + "'" + c(""))
         elif rcvCmd[:17] == "=cmd DemandeNoeud":  # Fonction Serveur
             # Dirriger vers la fonction EnvoiNoeuds()
             # Le noeud distant a demandé les noeuds, on lui envoi !
             # On trouve le premier port qui peut être attribué
             IppeerPort = "127.0.0.1:" + str(
                 autresFonctions.portLibre(
                     int(config.readConfFile("miniPort"))))
             sendCmd = IppeerPort  # On envoie au demandeur l'adresse à contacter
             self.clientsocket.send(sendCmd.encode())
             echangeNoeuds.EnvoiNoeuds(IppeerPort)
             stats.modifStats("NbEnvsLstNoeuds")
         elif rcvCmd[:25] == "=cmd DemandeListeFichiers":
             # On va récuperer le nom du file qui contient la liste
             # Ensuite, on la transmet au noeud distant pour qu'il puisse
             # faire la demande de réception du file pour qu'il puisse l'analyser
             if rcvCmd[:28] == "=cmd DemandeListeFichiersExt":
                 file = autresFonctions.lsteFichiers(1)
                 stats.modifStats("NbEnvsLstFichiers")
             else:
                 file = autresFonctions.lsteFichiers()
                 stats.modifStats("NbEnvsLstFichiersExt")
             self.clientsocket.send(file.encode())
         elif rcvCmd[:23] == "=cmd DemandeListeNoeuds":
             # On va récuperer le nom du file qui contient la liste
             # Ensuite, on la transmet au noeud distant pour qu'il puisse
             # faire la demande de réception du file pour qu'il puisse l'analyser
             file = autresFonctions.lsteNoeuds()
             self.clientsocket.send(file.encode())
             stats.modifStats("NbEnvsLstNoeuds")
         elif rcvCmd[:20] == "=cmd DemandePresence":
             # C'est tout bête, pas besoin de fonction
             # Il suffit de renvoyer la request informant que l'on est connecté au réseau.
             sendCmd = "=cmd Present"
             self.clientsocket.send(sendCmd.encode())
             stats.modifStats("NbPresence")
         elif rcvCmd[:15] == "=cmd rechercher":
             # =cmd rechercher nom SHA256.ext
             # Renvoie le retour de la fonction, qui elle même retourne une IP+Port ou 0
             # Chercher le nom du file
             donnee = rcvCmd[20:]
             sendCmd = str(search.rechercheFichierEntiere(donnee))
             self.clientsocket.send(sendCmd.encode())
         elif rcvCmd[:11] == "=cmd status":
             # On demande le statut du noeud (Simple, Parser, DNS, VPN, Main)
             if (config.readConfFile("Parser") == "Oui"):
                 sendCmd = "=cmd Parser"
                 self.clientsocket.send(sendCmd.encode())
             else:
                 sendCmd = "=cmd Simple"
                 self.clientsocket.send(sendCmd.encode())
         elif rcvCmd[:25] == "=cmd newFileNetwork name ":
             # =cmd newFileNetwork name ****** ip ******
             # Un nouveau file est envoyé sur le réseau
             fileName = rcvCmd[25:]
             ipport = rcvCmd[rcvCmd.find(" ip ") + 4:]
             if (config.readConfFile("Parser") == "Oui"):
                 # On prend en charge l'import de files,
                 # On l'ajoute à la base de données et on le télécharge
                 BDD.ajouterEntree("FichiersExt", fileName, ipport)
                 sendCmd = "=cmd fileAdded"
                 self.clientsocket.send(sendCmd.encode())
                 ip = ipport[:ipport.find(":")]
                 port = ipport[ipport.find(":") + 1:]
                 fctsClient.CmdDemandeFichier(ip, port, fileName)
             else:
                 # On ne prend pas en charge l'import de files,
                 # Mais on l'ajoute quand même à la base de données
                 BDD.ajouterEntree("FichiersExt", fileName, ipport)
                 sendCmd = "=cmd noParser"
                 self.clientsocket.send(sendCmd.encode())
         elif rcvCmd[:23] == "=cmd newPeerNetwork ip ":
             # =cmd newPeerNetwork ip ******
             # Un nouveau peer est envoyé sur le réseau
             ipport = rcvCmd[23:]
             if (config.readConfFile("Parser") == "True"):
                 # On prend en charge l'ajout de peers
                 # On l'ajoute à la base de données
                 BDD.ajouterEntree("Noeuds", ipport)
                 sendCmd = "=cmd peerAdded"
                 self.clientsocket.send(sendCmd.encode())
             else:
                 # On ne prend pas en charge l'import de files,
                 # Mais on l'ajoute quand même à la base de données
                 BDD.ajouterEntree("FichiersExt", fileName, ipport)
                 sendCmd = "=cmd noParser"
                 self.clientsocket.send(sendCmd.encode())
         elif rcvCmd[10:] == "BlackList ":
             # Les fonctionnalitées de la BlackList
             rcvCmd = rcvCmd[10:]
             if rcvCmd[:4] == "name":
                 # Le peer veut savoir si cet élément fait partie de la BlackList,
                 # et si oui quel est son rang (de 0 à 5)
                 rank = search.chercherInfo("BlackList", rcvCmd[4:])
                 self.clientsocket.send(rank.encode())
             if rcvCmd[4:] == "sync":
                 # Le peer veut recevoir l'intégralité de cette base
                 # On va donc la mettre dans un fichier
                 filename = echangeListes.tableToFile("BlackList")
                 try:
                     filename = int(filename)
                 except ValueError:
                     # Si c'est un chiffre, c'est un code d'erreur
                     sendCmd = "=cmd Filename " + str(
                         filename) + "ipport " + config.readConfFile(
                             "MyIP") + ":" + config.readConfFile(
                                 "defaultPort")
                 else:
                     sendCmd = "=cmd ERROR"
                 self.clientsocket.send(sendCmd.encode())
         else:
             # Oups... Demande non-reconnue...
             logs.addLogs("ERROR : Unknown request : " + str(rcvCmd))
             self.clientsocket.send("=cmd UNKNOW".encode())
Exemple #13
0
    def stop(self):
        self.serveur_lance = False


try:
    try:
        tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        #tcpsock = ssl.wrap_socket(tcpsock, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
        tcpsock.bind((host, port))
        serveur_lance = True
    except OSError as e:
        logs.addLogs("ERROR : In launcher.py : " + str(e))
        logs.addLogs("FATAL : Shutting down...")
        print(c("red") + "An error occured. Please restart WTP." + c(""))
    else:
        # On lance les programmes externes
        ThrdMntc = Maintenance()
        ThrdMntc.start()
        if (str(config.readConfFile("Parser")) == "True"):
            # Le noeud est un parseur, on lance la fonction.
            ThrdParser = Parser()
            ThrdParser.start()
        if (str(config.readConfFile("DNS")) == "True"):
            # Le noeud est un DNS, on lance la fonction.
            ThrdDNS = ServDNS()
            ThrdDNS.start()
        if (str(config.readConfFile("VPN")) == "True"):
            # Le noeud est un VPN, on lance la fonction.
            ThrdVPN = ServVPN()
Exemple #14
0
def maxi():
    # Affiche la grande documentation interactive (doc)
    print("Welcome to the WTP documentation.")
    print(str(c("highlighted")) + "1. Basics" + str(c("")))
    print(
        "To be able to use WTP from your browser, you need to install the browser extension. Link : "
        + str(c("underline")) +
        "https://github.com/Torzivalds/WTP/tree/master/Extention%20Firefox" +
        str(c("")) + "  A configuration wizard is included.\n")
    print(
        "To add files to the network, you must go to the file named ADDFILES and copy / paste them. Path : "
        + str(os.getcwd()) + "/ADDFILES  WTP will automatically add them. \n" +
        str(c("bold")) +
        "Pro tip : WTP checks this folder every 5 minutes. If you are in a hurry, you can enter this request : checkFiles."
        + str(c("")) + " \n" + str(c("red")) +
        "DISCLAMER : A file can not be deleted from the network. Be careful when you add some."
        + str(c("")))
    print(
        "For more information on the possible commands here, enter the name of the command below.\n"
    )
    print(str(c("highlighted")) + "2. Advenced" + str(c("")))
    print("You found a bug or improvement ? Contact us on our website :\n" +
          str(c("underline")) + "https://myrasp.fr/WTP" + str(c("")))
    print("Developer ressources are in the Wiki part of our GitHub.\n" +
          str(c("underline")) + "https://github.com/Torzivalds/WTP/wiki" +
          str(c("")))
    print(str(c("highlighted")) + "3. Contribute" + str(c("")))
    print(
        "You can contribute by improving the code with us, by talking about Web Transfer Protocol to your friends, your family, your colleagues, and if you can not contribute in these ways, you can donate via PayPal.\nYour contributions make us happy and help us to move forward, thank you!\n"
    )
    print(str(c("highlighted")) + "4. External ressources" + str(c("")))
    print("GitHub : " + str(c("underline")) +
          "https://github.com/Torzivalds/WTP" + str(c("")) + "\nPayPal : " +
          str(c("underline")) + "https://paypal.me/torzivalds" + str(c("")) +
          "\nWebsite : " + str(c("underline")) + "https://myrasp.fr/WTP" +
          str(c("")) + "\nFirefox Extension : " + str(c("underline")) +
          "https://github.com/Torzivalds/WTP/tree/master/Extention%20Firefox" +
          str(c("")))
    while 1:
        print(
            str(c("bold")) + "Enter an order, press enter or enter exit" +
            str(c("")))
        cmd = str(input(str(c("highlighted")) + ">> "))
        print(str(c("")) + "", end="")
        if cmd == "exit":
            break
        elif cmd == "update":
            print(
                "This function allows you to update the source code of WTP, which allows you to add new features and fix bugs. A check is made every 24 hours, and the update is installed as soon as it is detected."
            )
            print(str(c("yellow")) + "A restart may be required" + str(c("")))
        elif cmd == "stats":
            print(
                "This command allows to know some statistics of his peer, which allows to have some information about the use of peer by the network. They are for informational purposes only, they are not necessarily exact, because it is very easy to modify them via the database (WTP.db which is a SQlite database)"
            )
        elif cmd == "config":
            print(
                "This function allows you to modify the wtp.conf configuration file, accessible via this path : "
                + str(os.getcwd()) + "/wtp.conf")
            print("You can also edit it with your favorite text editor.")
            print(
                str(c("bold")) +
                "Think after changing settings to restart WTP for these to take effect."
                + str(c("")))
        elif cmd == "dns":
            print(
                "The DNS is a system for replacing the names of files that are very long with domain names that are much shorter and easier to remember.\nThis command is used to access a program that allows you to add, modify and delete DNS entries. You can do this on your peer (127.0.0.1) or on a remote peer. So you can add your own domain name, for free and very easily.\n"
                + str(c("yellow")) +
                "Be careful, when you add a new domain name, manually check that it does not already exist!"
                + str(c("")))
        elif cmd == "vpn":
            print("This section is being created.")
        elif cmd == "wtp":
            print("Web Transfer Protocol	V" +
                  str(config.readConfFile("Version")))
            print(
                "WTP is a new peer to peer network for the web under the GPL v3 lisence coded by a student on his free time."
            )
            print(
                "This version is not stable. WTP is being created, it's taking  time.  You can contribute by improving the code with us, by talking about Web Transfer Protocol to your friends, your family, your colleagues, and if you can not contribute in these ways, you can donate via PayPal.Your contributions make us happy and help us to move forward, thank you!"
            )
        elif cmd == "license":
            print(
                "WTP is free software, and is under GPL v3 license.This means that you can use, share, modify, redistribute as much as you want WTP. For more information, you can consult the license on the official GNU website :"
            )
            print(
                str(c("underline")) + "https://www.gnu.org/licenses/gpl.html" +
                str(c("")))
        elif cmd == "blacklist":
            print(
                "The blacklist is a system to block the files you want, such as advertisements and explicit documents. You can add or delete files from this list locally, and you can also use the list of a remote peer. This command allows you to modify the BlackList easily."
            )
        elif cmd[:6] == "client":
            print(
                str(c("yellow")) +
                "This command is used to send orders by hand to other peers or yours (IP: 127.0.0.1). Most users should not use this command, but it may be useful in some cases."
                + str(c("")))
            cmd = cmd[7:]
            if cmd == "DemandePresence":
                print(
                    "This command verifies that a peer is still connected to the network. It is done automatically every day. If the peer does not respond, it is moved into a sort of quarantine in the database, and after 10 days, it is permanently deleted."
                )
            elif cmd == "DemandeNoeud":
                print(
                    "This command requests 48 peers IP addresses from the network to a known peer to add them to the database. If you want to receive all the peers in the remote peer's database, prefer to use =cmd DemandeListeNoeuds"
                )
            elif cmd == "DemandeFichier":
                print(
                    "This command is used to download a file. Takes into parameters the ip and the port of the peer, and the name of the file which one wishes to download. If you do not know which peer is hosting the file, use =cmd rechercher"
                )
            elif cmd == "DemandeListeNoeuds":
                print(
                    "This command allows to receive all the peers known by another peer. \n"
                    + str(c("yellow")) +
                    "It can be very long if the peer knows a lot of peers." +
                    str(c("")) +
                    "\nIf you want to know only a few peers (48 to be precise), use =cmd DemandeNoeud"
                )
            elif cmd == "DemandeListeFichiers":
                print(
                    "This command asks a peer for a list of all the files it hosts. The received list is processed and the files are added to the database. \n"
                    + str(c("yellow")) +
                    "Attention, this action could take time if the peer hosts a lot of files."
                    + str(c("")))
            elif cmd == "rechercher":
                print(
                    "This function is used to search for a file on the network. It takes as parameter a domain name, or the exact name of the file. If it finds one of the file locations on the network, it is downloaded."
                )
            else:
                print(
                    str(c("red")) + "Unknown command." + str(c("")) +
                    " Enter client then :")
                print("DemandePresence		DemandeNoeud		DemandeFichier")
                print("DemandeListeNoeuds	DemandeListeFichiers	rechercher")
        elif cmd == "majDNS":
            print(
                "This command makes it easy to update your peer's DNS entries with a trusted remote peer "
                + str(c("yellow")) + "(Beware of phishing)" + str(c("")) +
                ". The DNS is a system for replacing the names of files that are very long with domain names that are much shorter and easier to remember."
            )
        elif cmd == "delAll":
            print(
                str(c("yellow")) +
                "This function deletes all settings, all files, the entire WTP database. It's irreversible."
                + str(c("")))
            print(
                "To be precise, it removes the following folders : .TEMP, ADDFILES, HOSTEDFILES, and the folloing files : .TempMaintenance24H, .TempMaintenance5M, logs, wtp.conf and the database : WTP.db"
            )
        elif cmd == "checkFiles":
            print(
                "This command is used to check if there are new files in ADDFILES. If so, they will be added to the most deleted network from this folder. This command also makes it possible to check that all the files in HOSTEDFILES are well known, otherwise they are sent to ADDFILES so that they are added to the network. And finally, this removes all the old temporary files in .TEMP"
            )
        elif cmd == "folder tree":
            print("WTP is on this path : " + str(os.getcwd()))
            print("In there, you can find :")
            print(
                "WTP source files that allow it to work. If you modify or delete it, WTP will not work properly."
            )
            print(str(c("bold") + ".TEMP" + str(c(""))))
            print(
                "This folder contains a number of small temporary files. Normally, they are very quickly removed."
            )
            print(
                str(c("yellow")) +
                "If you delete the folder or files inside, WTP may not be doing what it is doing or even crashing."
                + str(c("")))
            print(str(c("bold") + "ADDFILES" + str(c(""))))
            print(
                "This is a folder for you! This is the folder in which you can put all the files you want. After a few minutes, they will be available on the network. If you do not want to wait, you can start the checkFiles command. \n"
                + str(c("bold")) +
                "Once the files on the network, they are deleted from this folder. Remember to save them elsewhere! Attention, so that the files are sent on the network, they must not be in a subfolder of ADDFILES, otherwise they will be removed."
                + str(c("")) + " \n" + str(c("red")) +
                "Once a file is on the network, no one can delete it. Pay attention !"
                + str(c("")))
            print(str(c("bold") + "HOSTEDFILES" + str(c(""))))
            print(
                "This folder contains all the files that your peer knows. If you delete them, WTP will have to download them again if you need them. Deleting the contents of this folder frees disk space, but it takes longer if you want to access the file again. If you delete files, they will most certainly be accessible on the network thanks to other peers."
            )
        else:
            # On affiche toutes les commandes possibles ici
            # Chaque commande permet d'afficher une documentation précise, plus que help
            print("Here are all the possible commands here :")
            print("update			vpn			majDNS")
            print("stats			wtp			delAll")
            print("config			license			checkFiles")
            print("dns			blacklist		client <cmd>")
            print("folder tree")
Exemple #15
0
def verifMAJ(force=0):
    # Fonction qui a pour but de vérifier si il y a des mises à jour à faire
    # Elle va regarder sur une page de myrasp.fr la dernière version du protocol
    # Et si elle a une version différente, on télécharge le file zip contenant les nouvelles sources
    # Si force = 1, il indique une version obsolète pour forcer la MAJ
    if force == 1:
        versionActuelle = "0.0.1"
    else:
        versionActuelle = "0.0.9"

    class AppURLopener(FancyURLopener):
        version = "Mozilla/5.0"

    opener = AppURLopener()
    page = opener.open("https://static.myrasp.fr/WTP/latestWTP.html")
    latest = page.read().decode("utf-8")
    if versionActuelle != latest:
        # Il faut mettre à jour
        logs.addLogs("INFO : Démmarage de la mise à jour de V" +
                     str(versionActuelle) + " à V" + latest)
        # Le file zip a un nom de forme WTPversion.zip Ex : WTP0.0.1.zip
        fileName = "WTP" + latest + ".zip"
        url = 'https://myrasp.fr/WTP/Maj/' + fileName
        try:
            os.makedirs(".MAJ")
        except OSError:
            if not os.path.isdir(".MAJ"):
                raise
        with open('.MAJ/' + fileName, 'wb') as archive:
            archive.write(opener.open(url).read())
        # Le téléchargement des nouvelles sources est terminé
        # Extraction dans .MAJ/version Ex : .MAJ/0.0.1/
        # Vérifier si le dossier .MAJ/version existe, sinon le créer
        try:
            os.makedirs(".MAJ/" + latest)
        except OSError:
            if not os.path.isdir(".MAJ/" + latest):
                logs.addLogs(
                    "ERROR : The zip file isn't present in verifMAJ()")
        with zipfile.ZipFile(".MAJ/" + fileName, "r") as zip_ref:
            zip_ref.extractall(".MAJ/" + latest + "/")
        # Extraction terminée
        # Maintenant il faut remplacer les anciens files par les nouveaux
        liste = os.listdir(".MAJ/" + latest + "/")
        nbFichiers = len(liste)
        for x in range(nbFichiers):
            newFichier = ".MAJ/" + latest + "/" + liste[x]
            oldFichier = liste[x]
            # On copie le contenu du nouveau file
            file = open(newFichier, "rb")
            contenuNewFichier = file.read()
            file.close()
            # On remplace l'ancien par la copie
            file = open(oldFichier, "wb")
            file.write(contenuNewFichier)
            file.close()
            logs.addLogs("INFO : The file " + oldFichier + " has been updated")
        logs.addLogs("INFO : The update is complete")
        # Il faut redemarrer le protocol
        print(
            c("cian") + "The update is complete. Please restart WTP." + c(""))
    else:
        logs.addLogs("INFO : Pas de mise à jour disponible")
Exemple #16
0
 def run(self):
     print(
         "Welcome in the DNS center !\nWhat do you want to do ? (exit for quit this wizard)"
     )
     try:
         action = int(
             autresFonctions.ask(
                 "1 : Add a domain name\n2 : Modify a domain name\n3 : Delete a domain name"
             ))
     except ValueError:
         print(c("red") + "Your input isn't correct." + c(""))
     else:
         if action == 1:
             ipport = autresFonctions.ask(
                 "Enter the IP and the Port of the DNS (format : IP:Port)")
             ndd = autresFonctions.ask("Enter the nomain name")
             sha = autresFonctions.ask(
                 "Enter the adress of the file (format : sha256.extention)")
             password = autresFonctions.ask("Enter the password")
             error = dns.addNDD(ipport, sha, ndd, password)
             if error != 0:
                 # Error occured
                 print(
                     c("red") + "An error occurred : " + str(error) + c(""))
             else:
                 print(c("green") + "Wonderful ! It succeeded !" + c(""))
         elif action == 2:
             ipport = autresFonctions.ask(
                 "Enter the IP and the Port of the DNS (format : IP:Port)")
             ndd = autresFonctions.ask("Enter the nomain name")
             sha = autresFonctions.ask(
                 "Enter the adress of the file (format : sha256.extention)")
             password = autresFonctions.ask("Enter the password")
             error = dns.modifNDD(ipport, ndd, sha, password)
             if error != 0:
                 # Error occurred
                 print(
                     c("red") + "An error occurred : " + str(error) + c(""))
             else:
                 print(c("green") + "Wonderful ! It succeeded !" + c(""))
         elif action == 3:
             ipport = autresFonctions.ask(
                 "Enter the IP and the Port of the DNS (format : IP:Port)")
             ndd = autresFonctions.ask("Enter the nomain name")
             password = autresFonctions.ask("Enter the password")
             error = dns.supprNDD(ipport, ndd, password)
             if error != 0:
                 # Error occurred
                 print(
                     c("red") + "An error occurred : " + str(error) + c(""))
             else:
                 print(c("green") + "Wonderful ! It succeeded !" + c(""))
         else:
             print(c("red") + "Your input isn't correct." + c(""))
Exemple #17
0
def cmdLauncher(userCmd):
    error = 0
    if userCmd == "help":
        # Afficher toutes les options
        documentation.mini()
    elif userCmd == "update":
        # Vérifier les MAJ
        status = loader("Work in progress")
        status.start()
        #maj.verifMAJ()
        #maj.verifSources()
        status.stop()
        status.join()
        print(c("green") + "Done." + c(""))
    elif userCmd == "stats":
        # Affiche les statistiques
        print("Number of peers in the database : " +
              str(stats.compterStats("NbNoeuds")))
        print("Number of special peers in the database : " +
              str(stats.compterStats("NbSN")))
        print("Number of external files in the database : " +
              str(stats.compterStats("NbFichiersExt")))
        print("Number of files on this hard drive : " +
              str(stats.compterStats("NbFichiers")))
        print("Size of all files : " +
              str(stats.compterStats("PoidsFichiers")))
        print("Number of peers lists sent : " +
              str(stats.compterStats("NbEnvsLstNoeuds")))
        print("Number of file lists sent : " +
              str(stats.compterStats("NbEnvsLstFichiers")))
        print("Number of external file lists sent : " +
              str(stats.compterStats("NbEnvsLstFichiersExt")))
        print("Number of files sent : " +
              str(stats.compterStats("NbEnvsFichiers")))
        print("Number of presence requests received : " +
              str(stats.compterStats("NbPresence")))
        print("Number of files received : " +
              str(stats.compterStats("NbReceptFichiers")))
    elif userCmd == "config":
        # Modifier le fichier de configuration
        config.modifConfig()
    elif userCmd == "dns":
        # Entrer dans le programme de configuration du DNS
        thrdDNS = DNSConfig()
        thrdDNS.start()
        thrdDNS.join()
    elif userCmd == "exit":
        # On arrète WTP
        print(
            "Pro tip : You can also stop WTP at any time by pressing Ctrl + C."
        )
        return -1
    elif userCmd == "doc":
        # On affiche la documentation
        documentation.maxi()
    elif userCmd == "checkFiles":
        # On vérifie immédiatement dans ADDFILES, HOSTEDFILES et .TEMP
        status = loader("Work in progress")
        status.start()
        fctsMntc.checkIntruders()
        fctsMntc.creerFichier()
        fctsMntc.supprTemp()
        status.stop()
        status.join()
        print(c("green") + "Done." + c(""))
    elif userCmd == "delAll":
        print(
            "Are you sure you want to delete everything ?\nAll configuration, database, hosted files will be lost."
        )
        print("You will not be able to go back.")
        if str(input("If you are sure, enter DeleteAll\n>> ")) == "DeleteAll":
            print(
                "We are sorry to see you go.\nWe hope to see you very soon !\nIf you have comments to send to you, please contact us via our website :\nhttps://myrasp.fr/WTP"
            )
            status = loader("Work in progress")
            status.start()
            shutil.rmtree(str(os.getcwd()) + "/HOSTEDFILES")
            shutil.rmtree(str(os.getcwd()) + "/ADDFILES")
            os.remove(str(os.getcwd()) + "/.extinctionWTP")
            os.remove(str(os.getcwd()) + "/.TempMaintenance24H")
            os.remove(str(os.getcwd()) + "/.TempMaintenance5M")
            logs.rapportErreur()
            os.remove(str(os.getcwd()) + "/logs.txt")
            os.remove(str(os.getcwd()) + "/wtp.conf")
            status.stop()
            status.join()
            return -1
        print(
            "You scared us!\nFortunately, you have not passed the dark side of the force!"
        )
    elif userCmd == "majDNS":
        print(
            "You want to update the DNS database.\nIf you are crazy, you can enter crazy to update with a random peer."
        )
        ipport = str(
            input("With which DNS do you want to update ? (IP:Port)\n>> "))
        # Vérifier le noeud
        if autresFonctions.verifIPPORT(ipport):
            # C'est un IPPort
            co = autresFonctions.connectionClient(ipport)
            if co != "=cmd ERROR":
                sendCmd = "=cmd status"
                co.send(sendCmd.encode())
                rcvCmd = co.recv(1024).decode()
                co.close()
                if rcvCmd == "=cmd DNS":
                    e = dns.majDNS(ipport)
                    if int(e) > 0:
                        print(c("red") + "An error occured." + c(""))
                    else:
                        print(c("green") + "Done." + c(""))
                else:
                    print(c("red") + "This peer isn't DNS." + c(""))
            print(c("red") + "Unable to connect to this peer." + c(""))
        elif ipport == "crazy":
            print(
                "DISCLAMER : Some peers can be controlled by malicious people who can perform phishing attacks"
            )
            rep = str(input("Are you sure ? (y/N)\n>>"))
            if rep == "y" or rep == "Y":
                e = dns.majDNS()
                if int(e) > 0:
                    print(c("red") + "An error occured." + c(""))
                else:
                    print(c("green") + "Done." + c(""))
            else:
                print(
                    "You scared us!\nFortunately, you have not passed the dark side of the force!"
                )
        else:
            print(c("red") + "It's not an ip:port" + c(""))
    elif userCmd == "client":
        # Possibilité de faire des demandes en console
        error = 0
        sendCmd = ""
        print(
            "You can now write requests and send them to the peers you want.")
        print("Exit this wizard and enter doc for more information.")
        while sendCmd != "exit":
            sendCmd = str(
                input(
                    "What is your request ? (exit for quit this wizard)\n>> "))
            if sendCmd == "doc":
                documentation.maxi()
            elif sendCmd != "exit":
                host = str(
                    input(
                        "What is the IP of the peer that you want to contact ? > "
                    ))
                try:
                    port = int(
                        input(
                            "What is the Port of the peer that you want to contact ? > "
                        ))
                except ValueError:
                    print(
                        c("red") + "It isn't a port (between 1024 and 65535)" +
                        c(""))
                else:
                    if sendCmd == "=cmd DemandeNoeud":
                        error += fctsClient.CmdDemandeNoeud(host, port)
                    elif sendCmd[:19] == "=cmd DemandeFichier":
                        # =cmd DemandeFichier nom sha256.ext
                        error += fctsClient.CmdDemandeFichier(
                            host, port, sendCmd[24:])
                    elif sendCmd == "=cmd DemandeListeNoeuds":
                        error += fctsClient.CmdDemandeListeNoeuds(host, port)
                    elif sendCmd == "=cmd DemandeListeFichiers":
                        error += fctsClient.CmdDemandeListeFichiers(host, port)
                    elif sendCmd[:19] == "=cmd rechercher nom":
                        # =cmd rechercher nom SHA256.ext
                        sortie = search.rechercheFichierEntiere(sendCmd[20:])
                        ipport = sortie[:sortie.find(";")]
                        sha = sortie[sortie.find(";") + 1:]
                        if autresFonctions.verifIPPORT(ipport):
                            # C'est un IPPort
                            # On envoi vers la fonction qui télécharge le file
                            ip = ipport[:ipport.find(":")]
                            port = int(ipport[ipport.find(":") + 1:])
                            error += fctsClient.CmdDemandeFichier(
                                ip, int(port), sha)
                        else:
                            # C'est une erreur
                            print(sortie)
                            error += 1
                    else:
                        error = 0
                        connexion_avec_serveur = autresFonctions.connectionClient(
                            host, port)
                        if str(connexion_avec_serveur) == "=cmd ERROR":
                            error += 1
                        else:
                            connexion_avec_serveur.send(sendCmd.encode())
                            rcvCmd = connexion_avec_serveur.recv(1024).decode()
                            connexion_avec_serveur.close()
                            print(rcvCmd)
                    if int(error) == 0:
                        print(c("green") + "Done." + c(""))
                    else:
                        print(
                            c("red") + "An error occured. (" + str(error) +
                            ")" + c(""))
            else:
                break
    elif userCmd == "add":
        # L'utilisateur veut ajouter quelque chose
        categorie = str(input("What do you want to add ?\n>>> "))
        if categorie == "peer":
            ipport = str(input("What is the IP:Port of the peer ?\n>>> "))
            error = BDD.ajouterEntree("Noeud", ipport)
            if error == 0:
                print(c("green") + "Done." + c(""))
            else:
                print(c("red") + "An error occured (" + str(error) + ").")
        else:
            print(c("red") + "Your input is unknown." + c(""))
            print(
                c("cian") + "You can enter help for more information." + c(""))
    elif userCmd == "blacklist":
        blckLst = clientBlacklist.configBlckLst()
        blckLst.start()
        blckLst.join()
    else:
        print(c("red") + "Unknown request." + c(""))
    return 0
Exemple #18
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(""))))