def logout(ip, sessionID, SN, SN_host): print("\n>>> LOGOUT") pk = pack.request_logout(sessionID) s = func.create_socket_client(func.roll_the_dice(SN_host[0]), SN_host[1]) if s is None: func.error("Errore nel logout dal super nodo, vabbè") else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) nDelete = ricevutoByte[4:] func.success( "Logout eseguito con successo dal super nodo, eliminati " + str(nDelete, "ascii") + " elementi") s.close() pk = pack.close() s = func.create_socket_client(func.roll_the_dice(ip), const.PORT) if s is None: func.error("Errore nella chiusura del demone") else: s.sendall(pk) s.close() print("Chiusura del peer eseguito con successo, arrivederci.\n\n") if SN: s = func.create_socket_client(func.roll_the_dice(ip), const.PORT_SN) if s is None: func.error("Errore nella chiusura del demone super nodo") else: s.sendall(pk) s.close() print( "Chiusura del supernodo eseguita con successo, arrivederci.\n\n" )
def logout(ip, sessionID, SN, SN_host): print ("\n>>> LOGOUT") pk = pack.request_logout(sessionID) s = func.create_socket_client(func.roll_the_dice(SN_host[0]), SN_host[1]); if s is None: func.error("Errore nel logout dal super nodo, vabbè") else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) nDelete = ricevutoByte[4:] func.success("Logout eseguito con successo dal super nodo, eliminati " + str(nDelete, "ascii") + " elementi") s.close() pk = pack.close() s = func.create_socket_client(func.roll_the_dice(ip), const.PORT); if s is None: func.error("Errore nella chiusura del demone") else: s.sendall(pk) s.close() print ("Chiusura del peer eseguito con successo, arrivederci.\n\n") if SN: s = func.create_socket_client(func.roll_the_dice(ip), const.PORT_SN); if s is None: func.error("Errore nella chiusura del demone super nodo") else: s.sendall(pk) s.close() print ("Chiusura del supernodo eseguita con successo, arrivederci.\n\n")
def logout(ip55, t_host, sessionID): tfunc.warning("\n>>> LOGOUT") result = -1 pk = pack.request_logout(sessionID) s = sFunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]); if s is None: tfunc.error("Errore nella creazione della socket per il logout.") else: try: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) if str(ricevutoByte[:4], "ascii") == pack.CODE_LOGOUT_DENIED: tfunc.error("Siamo spiacenti ma il logout risulta impossibile poichè si è in possesso di parti di file uniche.\n" + \ "Sono state scaricate " + str(int(ricevutoByte[4:])) + " parti del file, fatevi il conto di quante ne mancano.") elif str(ricevutoByte[:4], "ascii") == pack.CODE_ANSWER_LOGOUT: tfunc.success("Logout eseguito con successo.\nAvevi " + str(int(ricevutoByte[4:])) + " parti, peccato tu te ne vada, addio.\nAttendi " + str(const.TIME_TO_UPDATE) + " secondi e potrai scomparire.") time.sleep(const.TIME_TO_UPDATE) pk = pack.close() sD = sFunc.create_socket_client(func.roll_the_dice(ip55), const.PORT); if sD is None: pass #tfunc.error("Errore nella chiusura del demone") else: sD.sendall(pk) sD.close() tfunc.success("Chiusura del peer eseguito con successo, arrivederci.\n\n") result = 1 else: tfunc.error("Errore nel codice di logout.") s.close() except: tfunc.error("Errore nel logout a causa del tracker.") s.close() return result
def __onView(self): # get the packet content from the client bt = self.pack_manager.client.received_bytes pack = Package() pack.setData(bt) self.display.setText(str(pack)) self.viewButton.setHidden(True) self.sendButton.setHidden(False)
def add_file_to_list(fileName, lenFile, lenPart, sessionIDUploader, md5, listFile, name, addr): if md5 not in listFile: fileToAdd = fs.FileStruct(fileName, lenFile, lenPart, sessionIDUploader) fileToAdd.add_owner_total() listFile[md5] = fileToAdd tfunc.write_daemon_success(name, addr[0], "ADD FILE " + str(fileName, "ascii").strip()) return pack.answer_add_file(fileToAdd.nPart) else: return pack.answer_add_file(listFile[md5].nPart)
def try_logout(sessionID, listFile, listUsers, name, addr): nPart, ndPart = fs.get_part_for_logout(sessionID, listFile) if ndPart != 0: tfunc.write_daemon_error(name, addr[0], "Logout rejected, " + str(nPart - ndPart) + " parts not already downloaded.") return pack.reject_logout(nPart - ndPart) else: remove_user(sessionID, listFile, listUsers) tfunc.write_daemon_success(name, addr[0], "Logout accepted, " + str(nPart) + " parts removed.") return pack.answer_logout(nPart)
def update_network(host, SN, listPkt): func.warning("\nP2P >> CREATION NETWORK") while True: nGroup = input("Inserire il numero del gruppo: ") nElement = input("Inserire il numero dell'elemento del gruppo: ") nPort = input("Inserire il numero della porta: ") Fhost = [ ("172.030." + func.format_string(nGroup, const.LENGTH_SECTION_IPV4, "0") + "." + func.format_string(nElement, const.LENGTH_SECTION_IPV4, "0") + "|fc00:0000:0000:0000:0000:0000:" + func.format_string(nGroup, const.LENGTH_SECTION_IPV6, "0") + ":" + func.format_string(nElement, const.LENGTH_SECTION_IPV6, "0")), nPort ] if SN: pk = pack.request_sn(host, const.PORT_SN) func.add_pktid(pk[4:20], listPkt, const.PORT_SN) else: pk = pack.request_sn(host, const.PORT) func.add_pktid(pk[4:20], listPkt, const.PORT) s = func.create_socket_client(func.roll_the_dice(Fhost[0]), Fhost[1]) if s is None: func.error( "Errore nella scelta del primo nodo vicino, scegline un altro." ) else: s.sendall(pk) s.close() break # Caricamento print("Loading...") for i in range(0, int(const.MAX_TIME / 1000)): print("|", end="") print("|||" * i + " " * ((int(const.MAX_TIME / 1000) * 3) - (i * 3)) + "|") time.sleep(1) print("|" + "|||" * int(const.MAX_TIME / 1000) + "|") if SN: func.success("NETWORK CREATED:") for h in sn_network: func.gtext(h[0] + " - " + h[1]) if SN: SN_host = [host, const.PORT_SN] else: SN_host = func.choose_SN(sn_network) return SN_host
def CheckUTBot(ctx, required=True): env = ctx.env ctx.Message('Checking for UTBot ... ') Package.check_options(env, 'UTBot') res = Package.CheckPkg(ctx, 'UTBot', utbot_text, utbot_libs, ext='.cc') Package.Required('UTBot', res[0], required) ctx.Result(res[0]) return res[0]
def CheckMETIS(ctx, required=True): env = ctx.env ctx.Message('Checking for METIS ... ') Package.check_options(env, 'METIS') res = Package.CheckPkg(ctx, 'METIS', metis_text, metis_libs) Package.Required('METIS', res[0], required) ctx.Result(res[0]) return res[0]
def CheckKLEE(ctx, required=True): env = ctx.env ctx.Message('Checking for KLEE ... ') Package.check_options(env, 'KLEE') res = Package.CheckPkg(ctx, 'KLEE', klee_text, klee_libs, auto_add_libs=False, run=False) Package.Required('KLEE', res[0], required) ctx.Result(res[0]) return res[0]
def CheckPETSc(ctx, required=True): env = ctx.env ctx.Message('Checking for PETSc ... ') Package.check_options(env, 'PETSc') res = Package.CheckPkg(ctx, 'PETSc', petsc_text, petsc_libs, petsc_extra_libs, loc_callback=find_conf) Package.Required('PETSc', res[0], required) ctx.Result(res[0]) return res[0]
def add_file_to_list(fileName, lenFile, lenPart, sessionIDUploader, md5, listFile, name, addr): if md5 not in listFile: fileToAdd = fs.FileStruct(fileName, lenFile, lenPart, sessionIDUploader) fileToAdd.add_owner_total() listFile[md5] = fileToAdd tfunc.write_daemon_success( name, addr[0], "ADD FILE " + str(fileName, "ascii").strip()) return pack.answer_add_file(fileToAdd.nPart) else: return pack.answer_add_file(listFile[md5].nPart)
def generate(env): cwd = os.getcwd() if cwd[-13:] in ['build/release', 'build/debug64']: os.chdir(cwd[:-13]) print "Loading plug-in: ra_scons" print "#####################################################" InitEnv.generate(env) Package.generate(env) Test.generate(env) GenerateFile.generate(env) AInstall.generate(env) CompileAndInstall.generate(env)
def try_logout(sessionID, listFile, listUsers, name, addr): nPart, ndPart = fs.get_part_for_logout(sessionID, listFile) if ndPart != 0: tfunc.write_daemon_error( name, addr[0], "Logout rejected, " + str(nPart - ndPart) + " parts not already downloaded.") return pack.reject_logout(nPart - ndPart) else: remove_user(sessionID, listFile, listUsers) tfunc.write_daemon_success( name, addr[0], "Logout accepted, " + str(nPart) + " parts removed.") return pack.answer_logout(nPart)
def predefined_package(treatment_list): package_list = [ packg.Package('PK001', 'Skin Luxury', 250.00, treatment_list[5], treatment_list[6]), packg.Package('PK002', 'Relaxation Indulgence', 200.00, treatment_list[8], treatment_list[10]), packg.Package('PK003', 'Hair Essentials (Women)', 80.00, treatment_list[0], treatment_list[1]), packg.Package('PK004', 'Woman\'s Big Day', 3200.00, treatment_list[12], treatment_list[13]) ] # Return the package_list return package_list
def get_info(self,pkg_id): action="info" self.store.execute_action(action,pkg_id) while self.store.is_action_running(action): time.sleep(0.2) ret=self.store.get_status(action) if ret["status"]==0: data=self.store.get_result(action) try: p=Package.Package(data["info"][0]) except: return(Package.Package()) categories=copy.deepcopy(p["categories"]) banned=set() for item in self.core.categories_manager.categories: if item in categories and len(categories) > 1: categories.remove(item) for item in self.core.categories_manager.banned_categories: if item in categories and len(categories) > 1: categories.remove(item) ''' if len(categories)>0: random_id=int(random.random()*len(categories)) random_category=categories[random_id] pkgs,categories=self.get_package_list_from_category(random_category,10) if len(pkgs) >=10: samples=10 else: samples=len(pkgs) for item in random.sample(pkgs,samples): if item["package"]!=pkg_id: p["related_packages"].append(item) p.fix_info() ''' return p
def update_network(host, SN, listPkt): func.warning("\nP2P >> CREATION NETWORK") while True: nGroup = input("Inserire il numero del gruppo: ") nElement = input("Inserire il numero dell'elemento del gruppo: ") nPort = input("Inserire il numero della porta: ") Fhost = [("172.030." + func.format_string(nGroup, const.LENGTH_SECTION_IPV4, "0") + "." + func.format_string(nElement, const.LENGTH_SECTION_IPV4, "0") + "|fc00:0000:0000:0000:0000:0000:" + func.format_string(nGroup, const.LENGTH_SECTION_IPV6, "0") + ":" + func.format_string(nElement, const.LENGTH_SECTION_IPV6, "0")), nPort] if SN: pk = pack.request_sn(host, const.PORT_SN) func.add_pktid(pk[4:20], listPkt, const.PORT_SN) else: pk = pack.request_sn(host, const.PORT) func.add_pktid(pk[4:20], listPkt, const.PORT) s = func.create_socket_client(func.roll_the_dice(Fhost[0]), Fhost[1]); if s is None: func.error("Errore nella scelta del primo nodo vicino, scegline un altro.") else: s.sendall(pk) s.close() break # Caricamento print("Loading...") for i in range(0, int(const.MAX_TIME / 1000)): print("|", end = "") print("|||" * i + " " * ((int(const.MAX_TIME / 1000) * 3) - (i * 3)) + "|") time.sleep(1) print("|" + "|||" * int(const.MAX_TIME / 1000) + "|") if SN: func.success("NETWORK CREATED:") for h in sn_network: func.gtext(h[0] + " - " + h[1]) if SN: SN_host = [host, const.PORT_SN] else: SN_host = func.choose_SN(sn_network) return SN_host
def importPackageFile(content, path, useCompression = False): """ Import a .tpk file into the repository. @since: 1.3 @type content: buffer string, encoded in mime64 @param content: the content of the tpk file @type path: string @param path: a document-root path where the package should be "unpacked". Must NOT exist. @type useCompression: bool @param useCompression: if set to True, the content has been gziped before being mime64-encoded. @rtype: bool @returns: True if OK, False otherwise """ getLogger().info(">> importPackageFile(%s, %s)" % (path, useCompression)) res = False try: content = base64.decodestring(content) if useCompression: content = zlib.decompress(content) res = Package.importPackageFile(content, path) except Exception, e: e = Exception("Unable to perform operation: %s\n%s" % (str(e), Tools.getBacktrace())) getLogger().info("<< importPackageFile(...): Fault:\n" + str(e)) raise(e)
def importPackageFile(content, path, useCompression=False): """ Import a .tpk file into the repository. @since: 1.3 @type content: buffer string, encoded in mime64 @param content: the content of the tpk file @type path: string @param path: a document-root path where the package should be "unpacked". Must NOT exist. @type useCompression: bool @param useCompression: if set to True, the content has been gziped before being mime64-encoded. @rtype: bool @returns: True if OK, False otherwise """ getLogger().info(">> importPackageFile(%s, %s)" % (path, useCompression)) res = False try: content = base64.decodestring(content) if useCompression: content = zlib.decompress(content) res = Package.importPackageFile(content, path) except Exception as e: e = Exception("Unable to perform operation: %s\n%s" % (str(e), Tools.getBacktrace())) getLogger().info("<< importPackageFile(...): Fault:\n" + str(e)) raise (e) getLogger().info("<< importPackageFile(): %s" % str(res)) return res
def createpackage(name, lastname): global travel_package travel_package = Package.Package() # create new travel package name = name.title() lastname = lastname.title() travel_package.create(name, lastname) return "Travel package for " + name + " " + lastname + " created successfully!"
def reconnect_user(ip, listUsers): pk = const.ERROR_PKT for user in listUsers: if user[0] == ip: pk = pack.answer_login()[:4] + user[2] break return pk
def search(sessionID, query, SN, SN_host, host, listPkt): ricevutoByteRam = b'' ricevutoByte = b'' pk = pack.request_search(sessionID, query) s = func.create_socket_client(func.roll_the_dice(SN_host[0]), SN_host[1]); if s is None: func.error("Super nodo non attivo.") update_network(host, SN, listPkt) else: s.sendall(pk) ricevutoByte = s.recv(4 * const.LENGTH_PACK) if str(ricevutoByte[0:4],"ascii") == const.CODE_ANSWER_SEARCH: print(ricevutoByte) nIdmd5 = int(ricevutoByte[4:7]) if(nIdmd5 != 0): func.success("Ricerca completata.") pointer = 7 id = 0 listFile = [] for j in range(0, nIdmd5): md5 = ricevutoByte[pointer:pointer + 32] nomeFile = ricevutoByte[pointer + 32:pointer + 132] nCopy = int(ricevutoByte[pointer + 132:pointer + 135]) pointer = pointer + 135 for i in range(0, nCopy): ip = ricevutoByte[pointer:pointer + 55] port = ricevutoByte[pointer + 55:pointer + 60] id = id + 1 pointer = pointer + 60 fixList = [id, md5, nomeFile, ip, port] listFile.append(fixList) print("\nScegli file da quelli disponibili (0 per uscire): \n") print("FILE \t\tID\tIP\n") lastFileName = b'' for row in listFile: if lastFileName != row[2]: nomeFile = func.reverse_format_string((str(row[2], "ascii").strip() + ":"), const.LENGTH_FORMAT, " ") print(nomeFile + str(row[0]) + "\t" + str(row[3], "ascii")) else: print("\t\t\t" + str(row[0]) + "\t" + str(row[3], "ascii")) lastFileName = row[2] selectId = input("\nInserire il numero di file che vuoi scaricare (0 per uscire): ") if(selectId != "0"): for i in range (0, id): if listFile[i][0] == int(selectId): selectFile = listFile[i] break func.download(selectFile) else: func.error("Non sono presenti file con questa query nel nome: " + query) s.close()
def getOrCreatePackage(self, packageName): try: return self.packages[packageName] except KeyError: newPackage = Package.Package(packageName) self.packages[packageName] = newPackage return newPackage
def add(ip55, sessionID, t_host, listPartOwned): tfunc.warning("\n>>> ADD FILE") fileName = input("Quale file vuoi inserire?\n") if fileName != "0": if os.path.exists(const.FILE_COND + fileName): fileToRead = open((const.FILE_COND + fileName),'rb') lenFile = os.stat(const.FILE_COND + fileName).st_size m = hashlib.md5() for x in range(0, pfunc.calculate_part(lenFile, const.LENGTH_PART)): m.update(fileToRead.read(const.LENGTH_PART)) m.update(bytes(ip55, "ascii")) md5File = m.hexdigest() fileToRead.close() pk = pack.request_add_file(sessionID, lenFile, md5File, tfunc.format_string(fileName, const.LENGTH_FILENAME, " ")) s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]); if s is None: tfunc.error("Errore, tracker non attivo.") else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) if(ricevutoByte[:4].decode("ascii") == pack.CODE_ANSWER_ADDFILE): tfunc.success("Il file " + fileName + " è stato aggiunto con successo.\nÈ stato diviso in " + str(int(ricevutoByte[4:])) + " parti.") pfunc.add_to_list_owner(md5File, lenFile, const.LENGTH_PART, listPartOwned, fileName) else: tfunc.error("Errore nella ricezione del codice di aggiunta file.") s.close() else: tfunc.error("Errore: file non esistente.")
def get(self, package, version, scope=None): package = str(refstring.Package(scope, package)) try: version = semver.Selector(version) except ValueError as exc: flask.abort(404) # Check our database of available packages. package_obj = Package.objects(name=package).first() if not package_obj: return self.not_found(package, version) # Find a matching version. versions = PackageVersion.objects(package=package_obj) key = lambda x: semver.Version(x.version) best = version.best_of(versions, key=key) if not best: return self.not_found(package, version) try: return json.loads(best.manifest) except json.JSONDecodeError: app.logger.error("invalid manifest found: {}@{}".format(best.package.name, best.version)) flask.abort(505)
def schedulePackage(path, username, session, at, script=None, profileName=None): """ Schedules a package to start at <at>. If script is provided, the package's default-script attribute is ignored and script is used instead. @since: 1.3 """ getLogger().info(">> schedulePackage(%s, script = %s)" % (path, script)) if not path.startswith('/'): path = '/' + path try: metadata = Package.getPackageMetadata(path) if not script: script = metadata['default-script'] scriptFilename = "%s/src/%s" % (path, script) scriptPath = scriptFilename label = "%s:%s" % ('/'.join(path.split('/')[2:]), script) getLogger().info("Using package script filename %s, path %s" % (scriptFilename, scriptPath)) if script.endswith(".campaign"): res = scheduleCampaign(FileSystemManager.instance().read( scriptFilename).decode('utf-8'), label, username, session, at=at, path=scriptPath) elif script.endswith(".ats"): res = scheduleAts(FileSystemManager.instance().read( scriptFilename).decode('utf-8'), label, username, session, at=at, path=scriptPath) else: raise Exception( "Invalid script/default script for package execution (unrecognized job type based on extension - %s)" % script) except Exception as e: e = Exception("Scheduling error: %s" % (str(e))) getLogger().info("<< schedulePackage(...): Fault:\n%s" % Tools.getBacktrace()) raise (e) getLogger().info("<< schedulePackage(...): %s" % str(res)) return res
def createPackage(path): """ Creates a new package tree somewhere in the docroot. @since: 1.3 @type path: string @param path: docroot path to the package root @throws Exception on error @rtype: bool @returns: True if OK, False otherwise """ getLogger().info(">> createPackage(%s)" % (path)) if not path.startswith('/'): path = '/' + path res = False try: res = Package.createPackage(path) except Exception as e: e = Exception("Unable to perform operation: %s\n%s" % (str(e), Tools.getBacktrace())) getLogger().info("<< createPackage(...): Fault:\n" + str(e)) raise (e) getLogger().info("<< createPackage(): %s" % str(res)) return res
def login(host, t_host): if t_host[0] == "": nGroup = input("Inserire il numero del gruppo del tracker: ") nElement = input( "Inserire il numero dell'elemento del gruppo del tracker: ") t_host = [ ("172.030." + tfunc.format_string(nGroup, const.LENGTH_SECTION_IPV4, "0") + "." + tfunc.format_string(nElement, const.LENGTH_SECTION_IPV4, "0") + "|fc00:0000:0000:0000:0000:0000:" + tfunc.format_string(nGroup, const.LENGTH_SECTION_IPV6, "0") + ":" + tfunc.format_string(nElement, const.LENGTH_SECTION_IPV6, "0")), const.TPORT ] tfunc.warning("\n>>> LOGIN") s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]) pk = pack.request_login(host) if s is None: tfunc.error("Errore nell'apertura della socket per il login") return t_host, bytes(const.ERROR_LOG, "ascii") else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) sessionID = ricevutoByte[4:20] s.close() return t_host, sessionID
def run(self): global mutex sP = sfunc.create_socket_client(func.roll_the_dice(self.peer[0]), self.peer[1]) if sP is None: #tfunc.error('Error: could not open socket in download') var = "" # giusto per fargli fare qualcosa else: try: if mutex.acquire(timeout = const.TIME_TO_UPDATE): dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "2") mutex.release() #tfunc.gtext("Start download della parte " + str(self.partN) + " da " + str(self.peer[0], "ascii")) pk = pack.request_download(self.md5, self.partN) sP.sendall(pk) ricevutoByte = sP.recv(const.LENGTH_HEADER) if str(ricevutoByte[0:4], "ascii") == pack.CODE_ANSWER_DOWNLOAD: nChunk = int(ricevutoByte[4:10]) ricevutoByte = b'' i = 0 while i != nChunk: ricevutoLen = sP.recv(const.LENGTH_NCHUNK) while (len(ricevutoLen) < const.LENGTH_NCHUNK): ricevutoLen = ricevutoLen + sP.recv(const.LENGTH_NCHUNK - len(ricevutoLen)) buff = sP.recv(int(ricevutoLen)) while(len(buff) < int(ricevutoLen)): buff = buff + sP.recv(int(ricevutoLen) - len(buff)) ricevutoByte = ricevutoByte + buff i = i + 1 sP.close() # Modifico nel file la parte che ho appena scaricato, se il file non esiste lo creo (es b'00000') dnl.create_part(ricevutoByte, self.fileName, self.partN, self.lenFile, self.lenPart) if mutex.acquire(timeout = const.TIME_TO_UPDATE): # Aggiorno la mia memoria dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "1") mutex.release() pfunc.part_all(self.listPartOwned[self.md5][0]) # Invio l'update al tracker send_update(self.t_host, self.sessionID, self.md5, self.partN, self.listPartOwned, self.peer) else: raise Exception("Error Download Code") else: raise Exception("Error Download Code") else: raise Exception("Error Download Code") except Exception as e: #tfunc.write_daemon_error(self.name, str(self.peer[0], "ascii"), "ERRORE DOWNLOAD: {0}".format(e)) dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "0")
def try_connection(host): s = sfunc.create_socket_client(func.roll_the_dice(host), const.TPORT) pk = pack.confirm() if s is None: sys.exit(-1) else: s.sendall(pk) s.close()
def test(): bob = Boxholder("bob") mailbox = Mailbox(123) bob.assignMailbox(mailbox) package = Package("123421341234", "bob", "thing") mailbox.addPackage(package) bob.retrievePackage()
def findAllPackages(args): pkgs = [] fws = os.listdir(args.pkgroot) fws = map(lambda x: Package("%s/%s/%s.spec" % (args.pkgroot, x, x), args), fws) pkgs += fws return pkgs
def find_hitpeer(listFile, listUsers, sessionID, md5, name, addr): listFounded = fs.find_hitpeer_from_md5(listFile, listUsers, sessionID, md5) if len(listFounded) == 0: tfunc.write_daemon_error( name, addr[0], "REQUEST FILEPART - Nessun file con md5: " + str(md5, "ascii")) pk = pack.answer_hitpeer(listFounded) return pk
def search_in_list_file(listFile, sessionID, query, name, addr): listFounded = fs.find_file_from_string(listFile, sessionID, str(query, "ascii")) if len(listFounded) == 0: tfunc.write_daemon_error( name, addr[0], "SEARCH FILE - Nessun file con " + str(query, "ascii").strip() + " nel nome.") pk = pack.answer_look(listFounded) return pk
def reconnect_user(ip, port, listUsers, name, addr): pk = const.ERROR_PKT listaUtenti = [] if [ip, port] in listUsers.values(): listaUtenti = list(listUsers.items()) for i in listaUtenti: if i[1] == [ip,port]: pk = pack.answer_login_old_user(i[0]) break if pk == const.ERROR_PKT: pk = pack.answer_login() tfunc.write_daemon_success(name, addr[0], "LOGIN OK: " + str(pk[4:20], "ascii")) else: tfunc.write_daemon_success(name, addr[0], "RECONNECT OK: " + str(pk[4:20], "ascii")) listUsers[pk[4:]] = [ip, port] return pk
def updateNeighbor(myHost, listNeighbor): del listNeighbor[:] pk = pack.neighbor(myHost) # Se avevo già dei vicini vado a testare se sono ancora attivi """if len(listNeighbor) != 0: for neighbor in listNeighbor: s = func.create_socket_client(func.roll_the_dice(neighbor[0]), neighbor[1]); # Se non sono più attivi lo segnalo e li cancello dalla lista if s is None: func.error(str(neighbor[0], "ascii") + " non è più attivo.") del neighbor else: func.success(str(neighbor[0], "ascii") + " ancora attivo.") s.close() # Se prima ero al completo e sono ancora tutti attivi lo segnalo e esco if len(listNeighbor) == const.NUM_NEIGHBOR: func.success("Lista vicini completa!") # Se invece dopo il controllo ho meno vicini del numero massimo mando a ogni vicino una richiesta di vicinato elif len(listNeighbor) > 0: for neighbor in listNeighbor: s = func.create_socket_client(func.roll_the_dice(neighbor[0]), neighbor[1]); if s is None: func.error("Mamma che sfiga, sto vicino è andato giù proprio ora.") else: s.sendall(pk) s.close() # Alla fine gestisco la possibilità che tutti i vicini che avevo siano andati giù e quindi passo all'inserimento manuale. if len(listNeighbor) == 0: """ while True: print("\n>>> SCELTA PEER VICINO") nGroup = input("Numero del gruppo: ") if nGroup is 0: break nElement = input("Numero dell'elemento del gruppo: ") if nElement is 0: break nPort = input("Inserire la porta su cui il vicino è in ascolto: ") if nPort is 0: break hostN = func.roll_the_dice( "172.030." + func.format_string(nGroup, const.LENGTH_SECTION_IPV4, "0") + "." + func.format_string(nElement, const.LENGTH_SECTION_IPV4, "0") + "|fc00:0000:0000:0000:0000:0000:" + func.format_string(nGroup, const.LENGTH_SECTION_IPV6, "0") + ":" + func.format_string(nElement, const.LENGTH_SECTION_IPV6, "0")) s = func.create_socket_client(hostN, nPort) if s is None: func.error( "Errore nella scelta del primo peer vicino, scegline un altro." ) break else: s.sendall(pk) s.close() break
def create_package(ID): """ Creates a package and appends it to the list of packages :return: the initialized package """ source = rand.choice(graph.nodes()) destination = rand.choice(graph.nodes()) package = Package(source, destination, ID, graph) add_time_spent_searching(package.time_spent_on_search) return package
def request_memory_of_hitpeer(t_host, sessionID, md5): s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]); if s is None: #tfunc.error("Tracker non attivo.") return bytes(const.ERROR_PKT, "ascii") else: pk = pack.request_hitpeer(sessionID, md5) s.sendall(pk) return s.recv(4 * const.LENGTH_PACK)
def quit(ip55): tfunc.warning("\n>>> QUIT") pk = pack.close() s = sFunc.create_socket_client(func.roll_the_dice(ip55), const.TPORT); if s is None: tfunc.error("Errore nella chiusura del demone tracker") else: s.sendall(pk) s.close() tfunc.success("Chiusura del demone tracker eseguito con successo, arrivederci.\n\n")
def logout(ip55, t_host, sessionID): tfunc.warning("\n>>> LOGOUT") result = -1 pk = pack.request_logout(sessionID) s = sFunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]) if s is None: tfunc.error("Errore nella creazione della socket per il logout.") else: try: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) if str(ricevutoByte[:4], "ascii") == pack.CODE_LOGOUT_DENIED: tfunc.error("Siamo spiacenti ma il logout risulta impossibile poichè si è in possesso di parti di file uniche.\n" + \ "Sono state scaricate " + str(int(ricevutoByte[4:])) + " parti del file, fatevi il conto di quante ne mancano.") elif str(ricevutoByte[:4], "ascii") == pack.CODE_ANSWER_LOGOUT: tfunc.success( "Logout eseguito con successo.\nAvevi " + str(int(ricevutoByte[4:])) + " parti, peccato tu te ne vada, addio.\nAttendi " + str(const.TIME_TO_UPDATE) + " secondi e potrai scomparire.") time.sleep(const.TIME_TO_UPDATE) pk = pack.close() sD = sFunc.create_socket_client(func.roll_the_dice(ip55), const.PORT) if sD is None: pass #tfunc.error("Errore nella chiusura del demone") else: sD.sendall(pk) sD.close() tfunc.success( "Chiusura del peer eseguito con successo, arrivederci.\n\n" ) result = 1 else: tfunc.error("Errore nel codice di logout.") s.close() except: tfunc.error("Errore nel logout a causa del tracker.") s.close() return result
def update_memory(sessionID, md5, partN, listFile, name, addr): file = listFile[md5] if not sessionID in file.listOwner: file.listOwner[sessionID] = create_empty_part(file.lenFile, file.lenPart) listToUpdate = list(file.listOwner[sessionID]) listToUpdate[int(partN)] = "1" file.listOwner[sessionID] = "".join(listToUpdate) nPart = count_part(file.listOwner[sessionID]) tfunc.write_daemon_success(name, addr[0], "Parte " + str(int(partN)) + " scaricata. (" + str(int((100 * nPart)/len(file.listOwner[sessionID]))) + "%)") return pack.answer_update_tracker(nPart)
def reconnect_user(ip, port, listUsers, name, addr): pk = const.ERROR_PKT listaUtenti = [] if [ip, port] in listUsers.values(): listaUtenti = list(listUsers.items()) for i in listaUtenti: if i[1] == [ip, port]: pk = pack.answer_login_old_user(i[0]) break if pk == const.ERROR_PKT: pk = pack.answer_login() tfunc.write_daemon_success(name, addr[0], "LOGIN OK: " + str(pk[4:20], "ascii")) else: tfunc.write_daemon_success(name, addr[0], "RECONNECT OK: " + str(pk[4:20], "ascii")) listUsers[pk[4:]] = [ip, port] return pk
def send_update(t_host, sessionID, md5, partN, listPartOwned, peer): s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]) if s is None: tfunc.error('Error: could not open socket to update Tracker') else: pk = pack.request_update_tracker(sessionID, md5, partN) s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) if str(ricevutoByte[0:4], "ascii") == pack.CODE_ANSWER_UPDATE_PART: tfunc.dnl_success("Download eseguito della parte " + str(partN) + " da " + str(peer[0], "ascii") + "\nAttualmente in possesso di " + str(int(ricevutoByte[4:])) + "/" + str(len(listPartOwned[md5][0])) + " parti del file.") s.close()
def login(host, SN, SN_host, listPkt): s = func.create_socket_client(func.roll_the_dice(SN_host[0]), SN_host[1]) pk = pack.request_login(host) if s is None: func.error("Errore nell'apertura della socket per il login") update_network(host, SN, listPkt) else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) sessionID = ricevutoByte[4:20] s.close() return sessionID
def updateNeighbor(myHost, listNeighbor): del listNeighbor[:] pk = pack.neighbor(myHost) # Se avevo già dei vicini vado a testare se sono ancora attivi """if len(listNeighbor) != 0: for neighbor in listNeighbor: s = func.create_socket_client(func.roll_the_dice(neighbor[0]), neighbor[1]); # Se non sono più attivi lo segnalo e li cancello dalla lista if s is None: func.error(str(neighbor[0], "ascii") + " non è più attivo.") del neighbor else: func.success(str(neighbor[0], "ascii") + " ancora attivo.") s.close() # Se prima ero al completo e sono ancora tutti attivi lo segnalo e esco if len(listNeighbor) == const.NUM_NEIGHBOR: func.success("Lista vicini completa!") # Se invece dopo il controllo ho meno vicini del numero massimo mando a ogni vicino una richiesta di vicinato elif len(listNeighbor) > 0: for neighbor in listNeighbor: s = func.create_socket_client(func.roll_the_dice(neighbor[0]), neighbor[1]); if s is None: func.error("Mamma che sfiga, sto vicino è andato giù proprio ora.") else: s.sendall(pk) s.close() # Alla fine gestisco la possibilità che tutti i vicini che avevo siano andati giù e quindi passo all'inserimento manuale. if len(listNeighbor) == 0: """ while True: print ("\n>>> SCELTA PEER VICINO") nGroup = input("Numero del gruppo: ") if nGroup is 0: break nElement = input("Numero dell'elemento del gruppo: ") if nElement is 0: break nPort = input("Inserire la porta su cui il vicino è in ascolto: ") if nPort is 0: break hostN = func.roll_the_dice("172.030." + func.format_string(nGroup, const.LENGTH_SECTION_IPV4, "0") + "." + func.format_string(nElement, const.LENGTH_SECTION_IPV4, "0") + "|fc00:0000:0000:0000:0000:0000:" + func.format_string(nGroup, const.LENGTH_SECTION_IPV6, "0") + ":" + func.format_string(nElement, const.LENGTH_SECTION_IPV6, "0")) s = func.create_socket_client(hostN, nPort); if s is None: func.error("Errore nella scelta del primo peer vicino, scegline un altro.") break else: s.sendall(pk) s.close() break
def remove_file(fileName, sessionID, SN, SN_host, host, listPkt): if os.path.exists("FileCondivisi/" + fileName): md5File = hashlib.md5(open(("FileCondivisi/" + fileName),'rb').read()).hexdigest() pk = pack.request_remove_file(sessionID, md5File) s = func.create_socket_client(func.roll_the_dice(SN_host[0]), SN_host[1]); if s is None: func.error("Errore, super nodo non attivo.") update_network(host, SN, listPkt) else: s.sendall(pk) s.close() else: func.error("Errore: file non esistente.")
def download(selectFile): print ("\n>>> DOWNLOAD") md5 = selectFile[1] nomeFile = selectFile[2].decode("ascii").strip() ip = selectFile[3] port = selectFile[4] # Con probabilità 0.5 invio su IPv4, else IPv6 ip = func.roll_the_dice(ip.decode("ascii")) print("Connessione con:", ip) # Mi connetto al peer sP = func.create_socket_client(ip, port) if sP is None: print ('Error: could not open socket in download') else: pk = pack.request_download(md5) sP.sendall(pk) nChunk = int(sP.recv(const.LENGTH_HEADER)[4:10]) ricevutoByte = b'' i = 0 while i != nChunk: ricevutoLen = sP.recv(const.LENGTH_NCHUNK) while (len(ricevutoLen) < const.LENGTH_NCHUNK): ricevutoLen = ricevutoLen + sP.recv(const.LENGTH_NCHUNK - len(ricevutoLen)) buff = sP.recv(int(ricevutoLen)) while(len(buff) < int(ricevutoLen)): buff = buff + sP.recv(int(ricevutoLen) - len(buff)) ricevutoByte = ricevutoByte + buff i = i + 1 sP.close() # Salvare il file data open((const.FILE_COND + nomeFile),'wb').write(ricevutoByte) print("File scaricato correttamente, apertura in corso...") try: os.system("open " + const.FILE_COND + nomeFile) except: try: os.system("start " + const.FILE_COND + nomeFile) except: print("Apertura non riuscita")
def logout(ip): print ("\n>>> LOGOUT") i = 0 pk = pack.logout() s = func.create_socket_client(func.get_ipv4(ip), const.PORT); if s is None: func.error("Errore nella chiusura del demone:" + func.get_ipv4(ip)) else: s.sendall(pk) s.close() i = i + 1 s = func.create_socket_client(func.get_ipv6(ip), const.PORT); if s is None: func.error("Errore nella chiusura del demone:" + func.get_ipv6(ip)) else: s.sendall(pk) s.close() i = i + 1 if i is 2: print ("Logout eseguito con successo.")
def search(myHost, query, listNeighbor, listPkt): pk = pack.query(myHost, query) if len(listNeighbor) is 0: func.error("Nessun vicino presente, crea prima una rete virtuale") else: func.add_pktid(pk[4:20], listPkt) i = 0 for x in listNeighbor: s = func.create_socket_client(func.roll_the_dice(x[0]), x[1]); if s is None: func.error("Peer non attivo: " + str(x[0], "ascii")) else: func.success("Peer attivo: " + str(x[0], "ascii")) s.sendall(pk) s.close() i = i + 1 if i is 0: func.error("Nessun peer vicino attivo") else: print("\nScegli file da quelli disponibili (0 per uscire): \n") print("ID\tFILE\t\tIP\n") f = False while not f: try: print("\n") choose = int(input()) if choose != 0: if choose <= len(listResultQuery): f = True func.remove_pktid(pk, listPkt) download(listResultQuery[choose - 1]) del listResultQuery[:] else: func.error("Spiacente, numero inserito non valido.") else: break except ValueError: func.error("Spiacente, inserisci un numero.") func.remove_pktid(pk, listPkt) del listResultQuery[:]
def login(host, t_host): if t_host[0] == "": nGroup = input("Inserire il numero del gruppo del tracker: ") nElement = input("Inserire il numero dell'elemento del gruppo del tracker: ") t_host = [("172.030." + tfunc.format_string(nGroup, const.LENGTH_SECTION_IPV4, "0") + "." + tfunc.format_string(nElement, const.LENGTH_SECTION_IPV4, "0") + "|fc00:0000:0000:0000:0000:0000:" + tfunc.format_string(nGroup, const.LENGTH_SECTION_IPV6, "0") + ":" + tfunc.format_string(nElement, const.LENGTH_SECTION_IPV6, "0")), const.TPORT] tfunc.warning("\n>>> LOGIN") s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]) pk = pack.request_login(host) if s is None: tfunc.error("Errore nell'apertura della socket per il login") return t_host, bytes(const.ERROR_LOG, "ascii") else: s.sendall(pk) ricevutoByte = s.recv(const.LENGTH_PACK) sessionID = ricevutoByte[4:20] s.close() return t_host, sessionID
def exportPackage(path, useCompression = False): """ Creates and returns a testerman package file (.tpk) from a package whose root docroot-path is path. A tpk file is a tar.gz file containing all package files (the package.xml file is in the root folder of the package) @since: 1.3 @type path: string @param path: a docpath to a package root folder @type useCompression: bool @param useCompression: if True, the output is gziped before being mime64-encoded @rtype: string (utf-8 or buffer, encoded in base64), or None @returns: None if the package was not found, or the tpk file contents in base64 encoding, optionally compressed """ getLogger().info(">> createPackageFile(%s, %s)" % (path, useCompression)) if not path.startswith('/'): path = '/' + path ret = None try: # We have to get all files in the package folder (recursively) then create an archive contents = Package.createPackageFile(path) if contents is None: ret = None else: if useCompression: ret = base64.encodestring(zlib.compress(contents)) else: ret = base64.encodestring(contents) except Exception, e: e = Exception("Unable to perform operation: %s\n%s" % (str(e), Tools.getBacktrace())) getLogger().info("<< createPackageFile(...): Fault:\n%s" % str(e)) raise(e)
def createPackage(path): """ Creates a new package tree somewhere in the docroot. @since: 1.3 @type path: string @param path: docroot path to the package root @throws Exception on error @rtype: bool @returns: True if OK, False otherwise """ getLogger().info(">> createPackage(%s)" % (path)) if not path.startswith('/'): path = '/' + path res = False try: res = Package.createPackage(path) except Exception, e: e = Exception("Unable to perform operation: %s\n%s" % (str(e), Tools.getBacktrace())) getLogger().info("<< createPackage(...): Fault:\n" + str(e)) raise(e)
def schedulePackage(path, username, session, at, script = None, profileName = None): """ Schedules a package to start at <at>. If script is provided, the package's default-script attribute is ignored and script is used instead. @since: 1.3 """ getLogger().info(">> schedulePackage(%s, script = %s)" % (path, script)) if not path.startswith('/'): path = '/' + path try: metadata = Package.getPackageMetadata(path) if not script: script = metadata['default-script'] scriptFilename = "%s/src/%s" % (path, script) scriptPath = os.path.split(scriptFilename)[0] label = "%s:%s" % ('/'.join(path.split('/')[2:]), script) getLogger().info("Using package script filename %s, path %s" % (scriptFilename, scriptPath)) if script.endswith(".campaign"): res = scheduleCampaign(FileSystemManager.instance().read(scriptFilename).decode('utf-8'), label, username, session, at = at, path = scriptPath) elif script.endswith(".ats"): res = scheduleAts(FileSystemManager.instance().read(scriptFilename).decode('utf-8'), label, username, session, at = at, path = scriptPath) else: raise Exception("Invalid script/default script for package execution (unrecognized job type based on extension - %s)" % script) except Exception, e: e = Exception("Scheduling error: %s" % (str(e))) getLogger().info("<< schedulePackage(...): Fault:\n%s" % Tools.getBacktrace()) raise(e)