def handleConnection(IPDatabase, localData, ms, addr): try: c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.bind(('', 0)) port = str(c.getsockname()[1]) utils.throw(ms, port) c.listen(1) s, addr = c.accept() key = encrypt.genKey(s, 'RECV') #print('receiving nickname') data=utils.catch(s) nick=encrypt.refract(data, key) myNick = encrypt.encrypt(localData.nickName,key) utils.throw(s, myNick) #print('sending connected nodes') master, connections = IPDatabase.currentConnections() s.send(utils.formatNumber(len(connections)).encode()) for ip in connections: element = encrypt.encrypt( connections[ip], key) utils.throw(s , element) IPDatabase.addIP(addr[0], key, nick) except(socket.error): pass
def download(IPDatabase, localData, fileInfo): #file info = (filename , filepath , ip) ip=fileInfo[2] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) i=0 while i<=5: try: s.connect((ip, 44450)) break except (socket.error): print('socket error') i+=1 if i==5: return None if True: utils.throw(s, '-3') port = int(utils.catch(s)) s.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) filePath = encrypt.encrypt(str(fileInfo[1]), IPDatabase.table[ip].key) utils.throw(s, filePath) download = localData.newDownload(fileInfo) FTS.recvFile(localData, download, s, fileInfo[0][3:], IPDatabase.table[ip].key)
def handleSearch(IPDatabase, localData, ms, addr): user = IPDatabase.table[addr[0]] c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.bind(('', 0)) port = str(c.getsockname()[1]) utils.throw(ms, port) c.listen(1) s, addr = c.accept() term = encrypt.refract( utils.catch(s) , user.key) master='' for key in localData.files.keys(): try: if term.lower() in localData.files[key].lower() or term.lower() in key.lower(): master= master+localData.files[key]+','+key+"|" except UnicodeEncodeError: pass if len(master) >0: master=master[:-1] master=encrypt.encrypt(master, user.key) packetSize=1024 segments = math.ceil(len(master)/packetSize) s.send(utils.formatNumber(segments).encode()) position=0 index=0 while index<segments: segment=master[position:position+packetSize] s.send(segment.encode()) position+=packetSize index+=1
def sendSearch(IPDatabase, ip, term): user = IPDatabase.table[ip] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) i=0 while i<=5: try: s.connect((ip, 44450)) break except (socket.error): print('socket error') i+=1 if i==5: return [] try: temp='-2' utils.throw(s, temp) port = utils.catch(s) #get the new port s.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, int(port))) #Connect eTerm = encrypt.encrypt(term, IPDatabase.table[ip].key) utils.throw(s, eTerm) #Send the term packets = int(s.recv(4).decode()) #get the total number of packets master='' index =0 packetSize = 1024 while index < packets: data= s.recv(packetSize) while len(data)< packetSize: if index == packets-1: break temp = s.recv(packetSize-len(data)) data =data+temp master=master+data.decode() index+=1 master = encrypt.refract(master, user.key) res=[] if master=='': return [] for packet in master.split('|'): mid = packet.find(",") temp=(packet[:mid], packet[mid+1:]) res.append(temp) s.close() return res except (socket.error): print("Connection Failed") s.close() return []
def setUpConnection(IPDatabase, localData, ip, auto=False): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) i=0 while i < 5: try: s.connect((ip, 44450)) utils.throw(s, '-0') break except (socket.error): i+=1 if auto == False: ip = input("Oops.. the IP that you entered was incorrect or the peer is not responding \nPlease enter a new IP or [0]' to exit: ") if auto == True: pass if ip.lower() == "0": return [] if i >5: return [] try: port = utils.catch(s) s.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) #print('connecting') s.connect((ip, int(port))) ip =s.getpeername()[0] #('making key') key = encrypt.genKey(s) #print('sending nickname') myNick = encrypt.encrypt(localData.nickName,key) utils.throw(s, myNick) #print('receiving nickname') data=utils.catch(s) nick=encrypt.refract(data, key) peerList=[] data=s.recv(4) for i in range(int(data.decode())): peerList.append(encrypt.refract(utils.catch(s),key)) result= IPDatabase.addIP(ip, key, nick) if auto == False: if result == 0: print('IP Table: Added \''+ IPDatabase.table[ip].nick +'\' with IP [' + IPDatabase.table[ip].ip+ '] correctly') else: print('IP Table: \'' +IPDatabase.table[ip].nick+'\' Already in table') s.close() return peerList s.close() except(socket.error): if auto== False: print('Connection failded: not adding new node') return []
def SaveToAnalyticsOLD(funcName): """SaveToAnalytics(funcName) Inputs: funcName(str): The functions name returns: None """ try: fileLocations = config.GetDict() filepath = fileLocations['Analytics'] #filepath = 'data\Analytics.csv' with open(filepath, 'rb') as File: reader = csv.reader(File) data = list(reader) #Update date data[0][1] = 'Last Updated: ' + GetDatePrefix() #Username userName = encrypt.encrypt(getpass.getuser()) #Update Column colPos = None for i,item in enumerate(data[1]): if item == funcName: colPos = i if colPos is None: colPos = len(data[1]) data[1].append(funcName) rowPos = None for i,item in enumerate(data): if item[0] == userName: rowPos = i if rowPos is None: rowPos = len(data) data.append([userName]) newCells = (colPos+1) - len(data[rowPos]) for i in range(newCells): data[rowPos].append('') try: data[rowPos][colPos] = int(data[rowPos][colPos]) + 1 except: data[rowPos][colPos] = 1 myFile = open(filepath, 'wb') with myFile: csvwriter = csv.writer(myFile) csvwriter.writerows(data) except: print "Analytics failed"
def SaveFunctionData(funcName, funcData): """ SaveFunctionData(funcName, funcData) funcName = name of function(str) funcData = data to save [list] """ try: now=datetime.datetime.now() monthString=('%02d%02d'%(now.year, now.month))[2:] fileLocations = config.GetDict() filepath = fileLocations['Data Folder'] fileName = monthString + '_' + funcName + '.csv' fullName = os.path.join(filepath, fileName) userName = encrypt.encrypt(getpass.getuser()) now=datetime.datetime.now() dateString='%02d-%02d-%02d'%(now.year, now.month, now.day) timeString= '%02d:%02d:%02d'%(now.hour, now.minute,now.second) if not os.path.isfile(fullName): data = [[funcName],['Date', 'Time', 'User', 'Version']] myFile = open(fullName, 'wb') with myFile: csvwriter = csv.writer(myFile) csvwriter.writerows(data) with open(fullName, 'rb') as File: reader = csv.reader(File) data = list(reader) row = [dateString, timeString, userName] + funcData data.append(row) myFile = open(fullName, 'wb') with myFile: csvwriter = csv.writer(myFile) csvwriter.writerows(data) except: print "SaveFunctionData failed"
def SaveToAnalytics(funcName): """SaveToAnalytics(funcName) Inputs: funcName(str): The functions name returns: None """ try: now=datetime.datetime.now() monthString=('%02d%02d'%(now.year, now.month))[2:] fileLocations = config.GetDict() filepath = fileLocations['Data Folder'] fileName = monthString + '_Analytics.csv' fullName = os.path.join(filepath, fileName) dateString='%02d-%02d-%02d'%(now.year, now.month, now.day) if not os.path.isfile(fullName): data = [[funcName , 'Last Updated']] myFile = open(fullName, 'wb') with myFile: csvwriter = csv.writer(myFile) csvwriter.writerows(data) myFile.close() with open(fullName, 'rb') as File: reader = csv.reader(File) data = list(reader) File.close() #Update date data[0][1] = 'Last Updated: ' + GetDatePrefix() #Username userName = encrypt.encrypt(getpass.getuser()) #Update Column colPos = None if len(data)>1: #If there is a second row: for i,item in enumerate(data[1]): if item == funcName: colPos = i if colPos is None: colPos = len(data[1]) data[1].append(funcName) else: #If there is not a second row colPos = 1 data.append(['User', funcName]) rowPos = None for i,item in enumerate(data): if item[0] == userName: rowPos = i if rowPos is None: rowPos = len(data) data.append([userName]) newCells = (colPos+1) - len(data[rowPos]) for i in range(newCells): data[rowPos].append('') try: data[rowPos][colPos] = int(data[rowPos][colPos]) + 1 except: data[rowPos][colPos] = 1 with open(fullName, 'wb') as myFile: csvwriter = csv.writer(myFile) csvwriter.writerows(data) except: pass