示例#1
0
文件: Peer.py 项目: ArtPes/P2P
    def share(self):
        """
        Aggiunge un file alla directory rendendolo disponibile agli altri peer per il download
        """
        found = False
        while not found:
            print('\nSelect a file to share (\'c\' to cancel):')
            for idx, file in enumerate(self.files_list):
                print(str(idx) + ": " + file.name)

            try:
                option = input()  # Selezione del file da condividere tra quelli disponibili (nella cartella shareable)
            except SyntaxError:
                option = None
            if option is None:
                print('Please select an option!')
            elif option == "c":
                break
            else:
                try:
                    int_option = int(option)
                except ValueError:
                    print("A number is required!")
                else:
                    for idx, file in enumerate(self.files_list):  # Ricerca del file selezionato
                        if idx == int_option:
                            found = True
                            print("Adding file " + file.name)
                            msg = 'ADDF' + self.session_id + file.md5 + file.name.ljust(100)
                            print('Share message: ' + msg)

                            response_message = None
                            try:
                                c = Connection(self.dir_ipv4, self.dir_ipv6, self.dir_port)  # Creazione connessione con la directory
                                c.connect()
                                self.directory = c.socket
                                self.directory.send(msg.encode('utf-8'))  # Richeista di aggiunta del file alla directory, deve contenere session id, md5 e nome del file
                                print('Message sent, waiting for response...')
                                response_message = self.directory.recv(7).decode('ascii')  # Risposta della directory, deve contenere AADD ed il numero di copie del file già condivise
                                print('Directory responded: ' + response_message)
                            except socket.error as msg:
                                print("######################################################")
                                print('Socket Error during ADDF : ' + str(msg))
                                print("######################################################")
                            except Exception as e:
                                print("######################################################")
                                print('Unknown Error during ADDF : ' + str(e))
                                print("######################################################")
                            else:
                                if response_message is None:
                                    print('No response from directory.')
                                else:
                                    print("Copies inside the directory: " + response_message[-3:])  # Copie del file nella directory
                                self.directory.close()

                    if not found:
                        print('Option not available')
示例#2
0
文件: Peer.py 项目: ArtPes/P2P
    def logout(self):
        """
        Esegue il logout dalla directory a cui si è connessi
        """
        print('Logging out...')
        msg = 'LOGO' + self.session_id
        print('Logout message: ' + msg)

        response_message = None
        try:
            c = Connection(self.dir_ipv4, self.dir_ipv6, self.dir_port)  # Creazione connessione con la directory
            c.connect()
            self.directory = c.socket
            self.directory.send(msg.encode('utf-8'))  # Richeista di logout
            print('Message sent, waiting for response...')
            response_message = self.directory.recv(7).decode('ascii')  # Risposta della directory, deve contenere ALGO e il numero di file che erano stati condivisi
            print('Directory responded: ' + response_message)
        except socket.error as msg:
            print("######################################################")
            print('Socket Error during Logout: ' + str(msg))
            print("######################################################")
        except Exception as e:
            print("######################################################")
            print('Unknown Error during Logout: ' + str(e))
            print("######################################################")
        else:
            if response_message is None:
                print("########################################")
                print('No response from directory.\nLogout failed!')
                print("########################################")
            elif response_message[0:4] == 'ALGO':
                self.session_id = None
                number_file = int(response_message[4:7])  # Numero di file che erano stati condivisi
                print('You\'d shared ' + str(number_file) + ' files')
                self.directory.close()  # Chiusura della connessione
                print('Logout completed')
            else:
                print("#######################################")
                print('Error: unknown response from directory.\n')
                print("#######################################")
示例#3
0
文件: Peer.py 项目: ArtPes/P2P
    def login(self):
        """
        Esegue il login alla directory specificata
        """

        print('Logging in...')
        msg = 'LOGI' + self.my_ipv4 + '|' + self.my_ipv6 + self.my_port
        print('Login message: ' + msg)

        response_message = None
        try:
            self.directory = None
            c = Connection(self.dir_ipv4, self.dir_ipv6, self.dir_port)  # Creazione connessione con la directory
            c.connect()
            self.directory = c.socket
            self.directory.send(msg.encode('utf-8'))  # Richiesta di login
            print('Message sent, waiting for response...')
            response_message = self.directory.recv(20).decode('ascii')  # Risposta della directory, deve contenere ALGI e il session id
            print('Directory responded: ' + response_message)
            self.directory.close()
        except socket.error as msg:
            print("######################################################")
            print('Socket Error during Login: '******'Unknown Error during Login: '******'No response from directory. Login failed!')
            else:
                self.session_id = response_message[4:20]
                if self.session_id == '0000000000000000' or self.session_id == '':
                    print("######################################################")
                    print('Troubles with the login procedure.\nPlease, try again.')
                    print("######################################################")
                else:
                    print('Session ID assigned by the directory: ' + self.session_id)
                    print('Login completed')
示例#4
0
文件: Peer.py 项目: ArtPes/P2P
    def search(self):
        """
        Esegue la ricerca di una parola tra i file condivisi nella directory.
        Dai risultati della ricerca sarà possibile scaricare il file.
        Inserendo il termine '*' si richiedono tutti i file disponibili
        """
        print('Insert search term:')
        try:
            term = input()  # Inserimento del parametro di ricerca
        except SyntaxError:
            term = None
        if term is None:
            print('Please select an option')
        else:
            print("Searching files that match: " + term)

            msg = 'FIND' + self.session_id + term.ljust(20)
            print('Find message: ' + msg)
            response_message = None
            try:
                c = Connection(self.dir_ipv4, self.dir_ipv6, self.dir_port)  # Creazione connessione con la directory
                c.connect()
                self.directory = c.socket
                self.directory.send(msg.encode('utf-8'))  # Richeista di ricerca, deve contenere il session id ed il paramentro di ricerca (20 caratteri)
                print('Message sent, waiting for response...')

                response_message = self.directory.recv(4).decode('ascii')  # Risposta della directory, deve contenere AFIN seguito dal numero di identificativi md5
                print(response_message)
                # disponibili e dalla lista di file e peer che li hanno condivisi
                print('Directory responded: ' + response_message)
            except socket.error as msg:
                print("######################################################")
                print('Socket Error during FIND: ' + str(msg))
                print("######################################################")
            except Exception as e:
                print("######################################################")
                print('Unknown Error during FIND: ' + str(e))
                print("######################################################")

            if not response_message == 'AFIN':
                print("#######################################")
                print('Error: unknown response from directory.\n')
                print("#######################################")
            else:
                idmd5 = None
                try:
                    idmd5 = self.directory.recv(3).decode('ascii')  # Numero di identificativi md5
                except socket.error as e:
                    print("######################################################")
                    print('Socket Error in IDmd5: ' + str(e))
                    print("######################################################")
                except Exception as e:
                    print("######################################################")
                    print('Unknown Error in IDmd5: ' + str(e))
                    print("######################################################")

                if idmd5 is None:
                    print("#####################")
                    print('Error: IDmd5 is blank')
                    print('#####################')
                else:
                    try:
                        idmd5 = int(idmd5)
                    except ValueError:
                        print("#####################")
                        print("IDmd5 is not a number")
                        print("#####################")
                    else:
                        if idmd5 == 0:
                            print("No results found for search term: " + term)
                        elif idmd5 > 0:  # At least one result
                            available_files = []

                            try:
                                for idx in range(0, idmd5):  # Per ogni identificativo diverso si ricevono:
                                    # md5, nome del file, numero di copie, elenco dei peer che l'hanno condiviso

                                    file_i_md5 = self.directory.recv(32).decode('ascii')  # md5 dell'i-esimo file (32 caratteri)
                                    file_i_name = self.directory.recv(100).strip().decode('ascii')  # nome dell'i-esimo file (100 caratteri compresi spazi)
                                    file_i_copies = self.directory.recv(3).decode('ascii')  # numero di copie dell'i-esimo file (3 caratteri)
                                    file_owners = []
                                    for copy in range(0, int(file_i_copies)):  # dati del j-esimo peer che ha condiviso l'i-esimo file
                                        owner_j_ipv4 = self.directory.recv(16).decode('ascii').replace("|", "") # indirizzo ipv4 del j-esimo peer
                                        #owner_j_ipv4 = self.directory.recv(16).decode('ascii')
                                        owner_j_ipv6 = self.directory.recv(39).decode('ascii')  # indirizzo ipv6 del j-esimo peer
                                        owner_j_port = self.directory.recv(5).decode('ascii')  # porta del j-esimo peer

                                        file_owners.append(Owner(owner_j_ipv4, owner_j_ipv6, owner_j_port))

                                    available_files.append(SharedFile(file_i_name, file_i_md5, file_owners))
                            except socket.error as msg:
                                print("######################################################")
                                print('Socket Error while retrieving files details : ' + str(msg))
                                print("######################################################")
                            except Exception as e:
                                print("######################################################")
                                print('Unknown Error while retrieving files details: ' + str(e))
                                print("######################################################")
                            if len(available_files) == 0:
                                print("No results found for search term: " + term)
                            else:
                                print("Select a file to download ('c' to cancel): ")
                                for idx, file in enumerate(available_files):  # visualizza i risultati della ricerca
                                    print(str(idx) + ": " + file.name)

                                selected_file = None
                                while selected_file is None:
                                    try:
                                        option = input()  # Selezione del file da scaricare
                                    except SyntaxError:
                                        option = None

                                    if option is None:
                                        print('Please select an option')
                                    elif option == 'c':
                                        return
                                    else:
                                        try:
                                            selected_file = int(option)
                                        except ValueError:
                                            print("A number is required")

                                file_to_download = available_files[
                                    selected_file]  # Recupero del file selezionato dalla lista dei risultati

                                print("Select a peer ('c' to cancel): ")
                                for idx, file in enumerate(
                                        available_files):  # Visualizzazione la lista dei peer da cui è possibile scaricarlo
                                    if selected_file == idx:
                                        for idx2, owner in enumerate(file.owners):
                                            print(
                                                str(idx2) + ": " + owner.ipv4 + " | " + owner.ipv6 + " | " + owner.port)

                                selected_peer = None
                                while selected_peer is None:
                                    try:
                                        option = input()  # Selezione di un peer da cui scaricare il file
                                    except SyntaxError:
                                        option = None

                                    if option is None:
                                        print('Please select an option')
                                    elif option == 'c':
                                        return
                                    else:
                                        try:
                                            selected_peer = int(option)
                                        except ValueError:
                                            print("A number is required")

                                for idx2, owner in enumerate(file_to_download.owners):  # Download del file selezionato
                                    if selected_peer == idx2:
                                        print("Downloading file from: " + owner.ipv4 + " | " + owner.ipv6 + " " + owner.port)
                                        self.directory.close()
                                        c = Connection(self.dir_ipv4, self.dir_ipv6, self.dir_port)  # Creazione connessione con la directory
                                        c.connect()
                                        self.directory = c.socket
                                        get_file(self.session_id, owner.ipv4, owner.ipv6, owner.port, file_to_download, self.directory)
                                        self.directory.close()

                        else:
                            print("###############################")
                            print("Unknown error, check your code!")
                            print("###############################")
示例#5
0
文件: Peer.py 项目: ArtPes/P2P
    def remove(self):
        """
        Rimuove un file condiviso nella directory
        """

        found = False
        while not found:
            print("\nSelect a file to remove ('c' to cancel):")
            for idx, file in enumerate(self.files_list):
                print(str(idx) + ": " + file.name)
            try:
                option = input()  # Selezione del file da rimuovere tra quelli disponibili (nella cartella shareable)
            except SyntaxError:
                option = None
            except Exception:
                option = None

            if option is None:
                print('Please select an option')
            elif option == "c":
                break
            else:
                try:
                    int_option = int(option)
                except ValueError:
                    print("A number is required")
                else:
                    for idx, file in enumerate(self.files_list):  # Ricerca del file selezionato
                        if idx == int_option:
                            found = True

                            print("Removing file " + file.name)
                            msg = 'DELF' + self.session_id + file.md5
                            print('Delete message: ' + msg)

                            response_message = None
                            try:
                                c = Connection(self.dir_ipv4, self.dir_ipv6, self.dir_port)  # Creazione connessione con la directory
                                c.connect()
                                self.directory = c.socket
                                self.directory.send(msg.encode('utf-8'))  # Richiesta di rimozione del file dalla directory, deve contenere session id e md5
                                print('Message sent, waiting for response...')

                                response_message = self.directory.recv(7).decode('ascii')  # Risposta della directory, deve contenere ADEL e il numero di copie rimanenti
                                print('Directory responded: ' + response_message)
                            except socket.error as msg:
                                print("######################################################")
                                print('Socket Error during DELF : ' + str(msg))
                                print("######################################################")
                            except Exception as e:
                                print("######################################################")
                                print('Unknown Error during DELF: ' + str(e))
                                print("######################################################")
                            else:
                                if response_message[-3:] == '999':  # Il file selezionato nella directory
                                    print("The file you chose doesn't exist in the directory")
                                else:
                                    print("Copies left in the directory: " + response_message[-3:])  # Numero di copie rimanenti
                                self.directory.close()

                    if not found:
                        print('Option not available')
示例#6
0
Does all the fancy stuff contained in the modules diectory in a central location
The script is intended to be scheduable by something like chron and customizable in the config file
"""

if __name__ == "__main__":
    
    #First, setup the argument parser
    args = argparse.ArgumentParser(description="Connects to ParentConnect and outputs grades in multiple formats")
    args.add_argument("-c", "--config", nargs=1, type=str, metavar="path",  help="path for configuration file")
    args = args.parse_args()

    #Load configuration options from file
    if args.config:
        #TODO: implement fancy path evaluation
        pass
    else:
        config = Config.getConfig()
    
    #Read grades (in raw html) from parent connection
    grades = Connection.readGrades(config)
    

    #Parse through html and create a list of grade objects
    gradelist = Grades.parseGrades(config, grades)

    #Run each specified output module
    outputmodules = config["Output"]["Modules"].split(",")
    for module in outputmodules:
        print("\n")
        eval("output." + module.strip()).output(gradelist)
示例#7
0
文件: PeerServer.py 项目: ArtPes/P2P
    def run(self):
        """
        Gestisce le connessioni in entrata creando per ognuna un nuovo thread che effettua l'upload del file richiesto
        """

        c = Connection(
            self.ps_ipv4, self.ps_ipv6, self.ps_port
        )  # Inizializzazione della socket in ascolto per le richieste degli altri peer
        c.listen_v4()
        self.ps_socket_v4 = c.socket
        c.listen_v6()
        self.ps_socket_v6 = c.socket

        try:
            while self.allow_run:
                input_ready, read_ready, error_ready = select.select(
                    [self.ps_socket_v4, self.ps_socket_v6], [],
                    [])  # Ricezione di un input dalle due socket

                for s in input_ready:
                    if s == self.ps_socket_v4:  # Controllo della provenienza della richiesta
                        try:
                            conn, addr = self.ps_socket_v4.accept(
                            )  # Attesa della connessione di un peer sulla socket ipv4
                            print('Peer connected on: ', addr)

                            peer = PeerHandler(
                                conn, addr, self.file_list
                            )  # Creazione di un thread che si occupa dell'upload del file
                            peer.start()
                            self.threads.append(
                                peer
                            )  # Inserimento del thread nella lista dei thread attivi
                        except Exception as e:
                            print(
                                "######################################################"
                            )
                            print("Unknown Error: " + str(e))
                            print(
                                "######################################################"
                            )

                    elif s == self.ps_socket_v6:  # Controllo della provenienza della richiesta
                        try:
                            conn, addr = self.ps_socket_v6.accept(
                            )  # Attesa della connessione di un peer sulla socket ipv6
                            print('Peer connected on: ', addr)

                            peer = PeerHandler(
                                conn, addr, self.file_list
                            )  # Creazione di un thread che si occupa dell'upload del file
                            peer.start()
                            self.threads.append(
                                peer
                            )  # Inserimento del thread nella lista dei thread attivi
                        except Exception as e:
                            print(
                                "######################################################"
                            )
                            print("Unknown Error: " + str(e))
                            print(
                                "######################################################"
                            )
        except Exception as e:
            # cose strane
            print('\n')
示例#8
0
def get_file(session_id, host_ipv4, host_ipv6, host_port, file, directory):
    """
    Effettua il download di un file da un altro peer
    :param session_id: id sessione corrente assegnato dalla directory
    :type session_id: str
    :param host_ipv4: indirizzo ipv4 del peer da cui scaricare il file
    :type host_ipv4: str
    :param host_ipv6: indirizzo ipv6 del peer da cui scaricare il file
    :type host_ipv6: str
    :param host_port: porta del peer da cui scaricare il file
    :type host_port: str
    :param file: file da scaricare
    :type file: file
    :param directory: socket verso la directory (per la segnalazione del download)
    :type directory: object
    """

    c = Connection(
        host_ipv4, host_ipv6,
        host_port)  # Inizializzazione della connessione verso il peer
    c.connect()
    download = c.socket

    msg = 'RETR' + file.md5
    print('Download Message: ' + msg)
    try:
        download.send(msg.encode('utf-8'))  # Richiesta di download al peer
        print('Message sent, waiting for response...')
        response_message = download.recv(
            10
        )  # Risposta del peer, deve contenere il codice ARET seguito dalle parti del file
    except socket.error as e:
        print("######################################################")
        print('Socket Error in sending RETR message: ' + str(e))
        print("######################################################")
    except Exception as e:
        print("######################################################")
        print('Unknown Error in sending RETR message: ' + str(e))
        print("######################################################")

    else:
        if response_message[:4].decode('ascii') == 'ARET':
            n_chunks = response_message[4:10].decode(
                'ascii')  # Numero di parti del file da scaricare

            filename = file.name
            fout = open(
                'received/' + filename, "wb"
            )  # Apertura di un nuovo file in write byte mode (sovrascrive se già esistente)

            n_chunks = int(
                str(n_chunks).lstrip('0')
            )  # Rimozione gli 0 dal numero di parti e converte in intero

            for i in range(0, n_chunks):
                if i == 0:
                    print('Download started...')

                update_progress(
                    i, n_chunks, 'Downloading ' +
                    fout.name)  # Stampa a video del progresso del download

                try:
                    chunk_length = recvall(download, 5).decode(
                        'ascii'
                    )  # Ricezione dal peer la lunghezza della parte di file
                    data = recvall(download, int(
                        chunk_length))  # Ricezione dal peer la parte del file
                    fout.write(data)  # Scrittura della parte su file
                except socket.error as e:
                    print(
                        "######################################################"
                    )
                    print('Socket Error in download file: ' + str(e))
                    print(
                        "######################################################"
                    )
                    break
                except IOError as e:
                    print(
                        "######################################################"
                    )
                    print('IOError in download file: ' + str(e))
                    print(
                        "######################################################"
                    )
                    break
                except Exception as e:
                    print(
                        "######################################################"
                    )
                    print('Unknown Error in download file: ' + str(e))
                    print(
                        "######################################################"
                    )
                    break
            fout.close()  # Chiusura file a scrittura ultimata
            update_progress(n_chunks, n_chunks, 'Downloading ' + file.name)
            print('\nDownload completed!')

            warns_directory(
                session_id, file.md5, directory
            )  # Invocazione del metododo che segnala il download alla directory
            print('Checking file integrity...')
            downloaded_md5 = hashfile(open(fout.name, 'rb'), hashlib.md5(
            ))  # Controllo dell'integrità del file appena scarcato tramite md5
            print(file.md5)
            print(downloaded_md5)
            if file.md5 == downloaded_md5:
                print('The downloaded file is intact')
            else:
                print("#############################################")
                print('Something is wrong. Check the downloaded file')
                print("#############################################")
        else:
            print('Error: unknown response from directory.\n')