#! /usr/bin/env python # -*- coding: UTF-8 -*- """ PyShare: programma per trasferire i file creato da Frafra (francesco.it@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. """ # Descrizione del file __module_name__ = "PyShare" __module_version__ = __revision__ = versione = "0.2.3-server" __module_description__ = "Trasferimento file" # Importazione delle librerire import os, sys, socket, time, thread, md5 from itertools import cycle def load(txt): """ Barra di caricamento """ print txt, " ", while 1: for x in cycle("|/-\\"): sys.stdout.write("\b"+x) sys.stdout.flush() time.sleep(0.2) if end: thread.exit_thread() def getline(conn): """ Funzione per ricevere dati """ buf = [] while 1: data = conn.recv(1) if not data: print "Errore" sys.exit(1) if data == "\n": break buf.append(data) return "".join(buf) # Verifica dei dati immessi if len(sys.argv) != 2: print "Usare: %s porta" % (sys.argv[0]) sys.exit(1) try: porta = sys.argv[1] porta = int(porta) except: print "Paramentro \"porta\" non valido." sys.exit(1) # Inizializzazione s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("", porta)) s.listen(1) conn, addr = s.accept() # Contrattazione recvfn = getline(conn) filesize = int(getline(conn)) print addr[0], "vuole inviarti \"" + recvfn + "\", di", filesize, "bytes." if raw_input("Accettare? [y/n] ").lower() != "y": conn.send("0") sys.exit(1) conn.send("1") loc = raw_input("In che cartella salvare? ") if loc[-1] != os.sep: loc += os.sep fd = os.open(loc+recvfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0600) recvbytes = 0 # Trasferimento end = 0 thread.start_new_thread(load, ("Trasferimento in corso...",)) start = time.time() while 1: if recvbytes < filesize: break buf = conn.recv(4096) if not buf: print "\nErrore." sys.exit(1) os.write(fd, buf) recvbytes = recvbytes + len(buf) os.close(fd) end = 1 # Verifica end = 0 thread.start_new_thread(load, ("\nVerifica intergrità...",)) res = getline(conn) myres = md5.new(open(loc+recvfn,"rb").read()).hexdigest() if res != myres: print "\nMd5 errato. Ritrasferire il file." conn.send("0") sys.exit(1) conn.send("1") end = 1 # Risultato sec = time.time()-start print "\nTrasferiti %d bytes in %f secondi a %f kb/s." % (filesize, sec, filesize/1024/sec) # Chiusura conn.close()