def __init__(self): """ Costruttore della classe Peer """ # Searching for shareable files for root, dirs, files in os.walk("shareable"): for file in files: file_md5 = helpers.hashfile(open("shareable/" + file, 'rb'), hashlib.md5()) new_file = SharedFile(file, file_md5) self.files_list.append(new_file)
def run(self): running = 1 while running: conn = self.client cmd = conn.recv(4) if cmd == "FIND": print "received command: " + str(cmd) sessionId = conn.recv(16) print "received sessionID: " + str(sessionId) term = conn.recv(20) print "received search term: " + str(term) # Finta risposta dalla directory # Number of different md5 idmd5 = None response = 'AFIN' + str(2).zfill(3) for root, dirs, files in os.walk("./share"): for file in files: filemd5 = helpers.hashfile(open("./share/" + file, 'rb'), hashlib.md5()) filename = file.ljust(100) copies = str(2).zfill(3) response += filemd5 response += filename response += copies # 2 copie response += '127.000.000.001|0000:0000:0000:0000:0000:0000:0000:0001' response += '03000' response += '172.030.008.003|fc00:0000:0000:0000:0000:0000:0008:0003' response += '03000' conn.send(response) elif cmd == "LOGI": msg = conn.recv(55) print "received command: " + str(cmd) print "received ipv4: " + msg[:4] print "received ipv6: " + msg[4:] print "received porta: " response = 'ALGI' + '1234567891234567' print response conn.sendall(response) elif cmd == "GREG": response = 'ADRE' + '002' print response conn.send(response) elif cmd == 'LOGO': print "received command: " + str(cmd) sessionid = conn.recv(16) print "peer: " + sessionid response = 'ALGO' + '003' print response conn.send(response) elif cmd == 'ADDF': response = 'RADD' + '003' print response conn.send(response) elif cmd == 'DELF': response = 'RDEL' + '003' print response conn.send(response) elif cmd == 'RETR': fileRemoteMd5 = conn.recv(32) for root, dirs, files in os.walk("share"): for file in files: fileMd5 = helpers.hashfile(open("share/" + file, 'rb'), hashlib.md5()) if fileRemoteMd5 == fileMd5: print "Nome file dal client: ", file length = os.stat("share/" + file).st_size print "Lunghezza file", length numChunks = length / 1024 + 1 strChunks = str(numChunks).zfill(6) conn.send('ARET'+strChunks) msg = '' with open("share/" + file, 'rb') as f: l = f.read(1024) while (l): lenChunk = len(str(l)) strLenChunk = str(lenChunk).zfill(5) msg += strLenChunk msg += l l = f.read(1024) f.close() conn.send(msg) elif cmd == 'DREG': conn.recv(48) print response conn.send('ADRE' + str(5).zfill(5))
def get_board(name): """ /boards/ handler """ form = PostForm(request.form) if form.validate_on_submit(): board_id, is_board_locked, max_threads = g.db.execute('''select id, locked, max_threads from boards where name = %s''', name).first() if is_board_locked: flash('Board is locked!') return redirect(url_for('get_board', name=name)) # select how many threads there already are nr_threads = g.db.execute('''select count(*) from posts where board_id = %s and parent_id = 0''', board_id).first()[0] # grab threads, oldest first # TODO: maybe spare sticked? revisit! thread_ids = g.db.execute('''select id from posts where board_id = %s and parent_id = 0 order by stickied asc, bumped asc''', board_id) if nr_threads >= max_threads: # this should hopefully only always be one, but delete as many as necessary to adjust to max threads for i in range(nr_threads - max_threads): helpers.delete_thread(board_id, thread_ids[i]) # TODO: ezt a részt lehetne egy külön metódusba átvinni file = request.files['file'] file_id = None if file: # fájl mentése, validálás, new filename = '' try: filename = img.save(request.files['file'], name=str(int(time.mktime(datetime.datetime.now().timetuple())))+'.') imagefile = Image.open(os.path.join(UPLOADED_FILES_DEST, 'image' , filename)) outimg = resize(imagefile, (150, 150)) outimg.save(os.path.join(UPLOADED_FILES_DEST, 'thumbs' , filename)) except UploadNotAllowed: return 'NEM BAZMEG' ext = filename[filename.rfind('.'):] # TODO: fix, hashing broken file_h = open(os.path.join(UPLOADED_FILES_DEST, 'image' , filename), 'r') filehash = helpers.hashfile(file_h) file_h.close() filesize = os.path.getsize(os.path.join(UPLOADED_FILES_DEST, 'image' , filename)) g.db.execute('''insert into files (filename, extension, original_filename, size, md5, content_type) values (%s, %s, %s, %s, %s, %s)''', filename, ext, secure_filename(file.filename), filesize, filehash, file.content_type) file_id = g.db.execute('''select LAST_INSERT_ID()''').first()[0] # új poszt adatainak beillesztése actual_email = form.email.data if form.email.data == app.config['NOKO_STRING']: # or form.email.data == app.config['SAGE_STRING']: actual_email = None date_now = datetime.datetime.now() g.db.execute('''insert into posts (board_id, parent_id, name, subject, message, date, email) values (%s, 0, %s, %s, %s, %s, %s)''', str(board_id), form.name.data, form.subject.data, markup_engine(form.message.data), date_now, actual_email) post_id = g.db.execute('''select LAST_INSERT_ID()''').first()[0] if file: # poszt img-idjének frissítése g.db.execute('''update posts set file_id = %s where id = %s''', file_id, post_id) # finally return user to their thread return redirect(url_for('get_thread', board_name=name, thread_id=post_id)) board = g.db.execute('''select * from boards where name = %s''', str(name)).first() board_names = [x[0] for x in g.db.execute('''select name from boards''').fetchall()] op_posts = g.db.execute('''select * from posts where board_id = %s and parent_id = 0 order by stickied desc, bumped desc, date desc limit %s''', int(board['id']), int(board['threads_per_page'])).fetchall() threads = [] for i in op_posts: op_post = dict(i) if op_post['file_id']: op_post['file'] = g.db.execute('''select * from files where id = %s''', op_post['file_id']).first() replies = []#[dict(x).__setitem__('file', g.db.execute('''select * from files where id = %s''', x['file_id']).first()) if x['file_id'] else dict(x) for x in g.db.execute('''select * from posts where board_id = %s and parent_id = %s order by date desc limit 5''', int(board['id']),int(i['id'])).fetchall()] replies_with_image = 0 for k in g.db.execute('''select * from posts where board_id = %s and parent_id = %s order by date desc limit 5''', int(board['id']),int(i['id'])).fetchall(): reply = dict(k) if reply['file_id']: replies_with_image += 1 reply['file'] = g.db.execute('''select * from files where id = %s''', reply['file_id']).first() replies.append(reply) threads.append({ 'op_post': op_post, 'replies': replies[::-1], 'num_unshown_posts': g.db.execute('''select COUNT(*)-5 from posts where board_id = %s and parent_id = %s order by date asc''', int(board['id']), int(i['id'])).first()[0], # TODO: fix, inner join vagy valami faszság :( 'num_unshown_files': g.db.execute('''select COUNT(*)-(select COUNT(*) from posts where board_id = %s and parent_id = %s and file_id != 0 order by date limit 5) from posts where board_id = %s and parent_id = %s and file_id != 0 order by date asc''', int(board['id']), int(i['id']), int(board['id']), int(i['id'])).first()[0] }) return render_template('board.html', board_name=board['name'], board_title=board['title'], board_names=board_names, threads=threads, default_name=board['default_name'], force_default=board['force_default'], form=form, board_locked=board['locked'])
def get_thread(board_name, thread_id): """ /boards/thread/ handler """ form = PostForm(request.form) if form.validate_on_submit(): board_id, max_replies = g.db.execute('''select id, max_replies from boards where name = %s''', board_name).first() nr_replies = g.db.execute('''select count(id) from posts where parent_id = %s''', thread_id).first()[0] is_admin_unlocked, locked = g.db.execute('''select admin_unlocked, locked from posts where id = %s''', thread_id).first() # thread lockolva if locked: flash('thread locked') return redirect(url_for('get_board', name=board_name)) # thread full, és admin nem unlockolta if nr_replies >= max_replies and not is_admin_unlocked: flash('thread full') return redirect(url_for('get_board', name=board_name)) file = request.files['file'] file_id = None if file: # fájl mentése, validálás, new filename = '' try: filename = img.save(request.files['file'], name=str(int(time.mktime(datetime.datetime.now().timetuple())))+'.') imagefile = Image.open(os.path.join(UPLOADED_FILES_DEST, 'image' , filename)) outimg = resize(imagefile, (150, 150)) outimg.save(os.path.join(UPLOADED_FILES_DEST, 'thumbs' , filename)) except UploadNotAllowed: return 'NEM BAZMEG' ext = filename[filename.rfind('.'):] # TODO: fix, hashing broken file_h = open(os.path.join(UPLOADED_FILES_DEST, 'image' , filename), 'r') filehash = helpers.hashfile(file_h) file_h.close() filesize = os.path.getsize(os.path.join(UPLOADED_FILES_DEST, 'image' , filename)) g.db.execute('''insert into files (filename, extension, original_filename, size, md5, content_type) values (%s, %s, %s, %s, %s, %s)''', filename, ext, secure_filename(file.filename), filesize, filehash, file.content_type) file_id = g.db.execute('''select LAST_INSERT_ID()''').first()[0] date_now = datetime.datetime.now() # új poszt adatainak beillesztése actual_email = form.email.data if form.email.data == app.config['NOKO_STRING']: # or form.email.data == app.config['SAGE_STRING']: actual_email = '' g.db.execute('''insert into posts (board_id, parent_id, name, subject, message, date, email) values (%s, %s, %s, %s, %s, %s, %s)''', str(board_id), str(thread_id), form.name.data, form.subject.data, markup_engine(form.message.data), date_now, actual_email) if file: post_id = g.db.execute('''select LAST_INSERT_ID()''').first()[0] # poszt img-idjének frissítése g.db.execute('''update posts set file_id = %s where id = %s''', file_id, post_id) # parent poszt bumpolása if form.email.data != app.config['SAGE_STRING']: g.db.execute('''update posts set bumped = %s where id = %s and parent_id = 0 and board_id = %s''', date_now, thread_id, board_id) # noko, vissza a thread-be if form.email.data == app.config['NOKO_STRING']: return redirect(url_for('get_thread', board_name=board_name, thread_id=thread_id)) else: return redirect(url_for('get_board', name=board_name)) # invalid poszt elif request.method == 'POST' and not form.validate(): # sem kép, sem szöveg if form.errors.keys()[0] == 'message': return 'need image or msg, lul' else: return ':(' board = g.db.execute('''select * from boards where name = %s''', str(board_name)).first() posts = [dict(x) for x in g.db.execute('''select * from posts where board_id = %s AND (parent_id = %s OR (parent_id = 0 AND id = %s)) order by date''', board['id'], thread_id, thread_id).fetchall()] for i in range(len(posts)): if posts[i]['file_id'] != 0: file_details = g.db.execute('''select * from files where id = %s''', posts[i]['file_id']).first() posts[i]['file'] = file_details thread = { 'op_post': posts[0], 'replies': posts[1:] } board_names = [x[0] for x in g.db.execute('''select name from boards''').fetchall()] return render_template('thread.html', board_name=board['name'], board_title=board['title'], board_names=board_names, thread=thread, default_name=board['default_name'], force_default=board['force_default'], form=form)
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.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) # 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 'Error: ' + e.message except Exception as e: print 'Error: ' + e.message else: if response_message[:4] == 'ARET': n_chunks = response_message[4:10] # Numero di parti del file da scaricare #tmp = 0 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...' helpers.update_progress(i, n_chunks, 'Downloading ' + fout.name) # Stampa a video del progresso del download try: chunk_length = recvall(download, 5) # 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 'Socket Error: ' + e.message break except IOError as e: print 'IOError: ' + e.message break except Exception as e: print 'Error: ' + e.message break fout.close() # Chiusura file a scrittura ultimata 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 = helpers.hashfile(open(fout.name, 'rb'), hashlib.md5()) # Controllo dell'integrità del file appena scarcato tramite md5 if file.md5 == downloaded_md5: print 'The downloaded file is intact' else: print 'Something is wrong. Check the downloaded file' else: print 'Error: unknown response from directory.\n'