def Main(): address = "" port = 50001 serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSock.bind((address, port)) serverSock.listen(5) flag = False while not flag: conn, addr = serverSock.accept() rc = os.fork() if not rc: try: fileName = framedReceive(conn, False) data = framedReceive(conn, False) if data: fileName = os.path.basename(fileName.decode()) fileWrite(fileName, data, conn) except Exception as e: print(f"[+] Error {e} ") flag = True
def send_message(): while True: user_input = input("Enter Message\n> ") if re.match("put\s[\w\W]+", user_input): trash, file = user_input.split(" ", 1) if os.path.exists("%s/%s" % (os.getcwd(), file)): msg = "put " + file.rsplit('/', 1)[-1] framedSend(s, msg.encode()) framedSend(s, open(file, "rb").read(), 1) else: print("File Doesn't Exist.") elif re.match("get\s[\w\W]+", user_input): framedSend(s, user_input.encode()) payload = framedReceive(s) if payload.decode() == "true": trash, file = user_input.split(" ", 1) writer = open("%s/%s" % (os.getcwd(), file), "wb+") payload = framedReceive(s) writer.write(payload) writer.close() print("Transfer Done.") else: print("File not Found.") elif user_input == "quit": print("Killing Server...") framedSend(s, "quit".encode()) print("Response:", framedReceive(s)) sys.exit(0) else: framedSend(s, user_input.encode()) print("Response:", framedReceive(s))
def server_protocols(): while True: payload = framedReceive(sock) print("Received: ", payload.decode()) if re.match("put\s[\w\W]+", payload.decode()): trash, file = payload.decode().split(" ", 1) if not os.path.exists("%s/server_files/%s" % (os.getcwd(), file)): writer = open("%s/server_files/%s" % (os.getcwd(), file), "wb+") framedSend(sock, "start".encode()) payload = framedReceive(sock, 1) writer.write(payload) writer.close() print("Transfer Done.") else: framedSend(sock, "File Already Exists.".encode()) elif re.match("get\s[\w\W]+", payload.decode()): trash, file = payload.decode().split(" ", 1) if os.path.exists("%s/server_files/%s" % (os.getcwd(), file)): framedSend(sock, "true".encode()) framedSend( sock, open("%s/server_files/%s" % (os.getcwd(), file), "rb").read(), 1) print("Transfer Done.") else: framedSend(sock, "File Doesn't Exist.".encode()) elif payload == "quit".encode(): framedSend(sock, "Server Killed.".encode(), debug) print("Exiting...") sys.exit(0) else: framedSend(sock, "Received".encode(), debug)
def run(self): print(threadNum) global sLock sLock.acquire() checkRecv = framedReceive(sock, debug) # Check the first thing the server sends! if checkRecv == b"ERROR": # Client sent an error message - stop! print("Something went wrong client-side. No files recieved.") sock.close() sys.exit(0) if checkRecv == b"exit": # Check for server terminate command. NON-FUNCTIONAL. print("Client terminated server. Shutting down...") sock.close() sys.exit(0) while checkRecv != b'': fileName = checkRecv.decode("utf-8") # Pull out the file name! checkRecv = framedReceive(sock, debug) filePath = os.getcwd() + "/server/" + fileName # Get path; server uploads fle to server folder. if os.path.isfile(filePath): # Don't let user overwrite files already on the server. print("ERROR: File already exists. %s not recieved." % fileName) framedSend(sock, b"exists", debug) sock.close() sys.exit(0) else: framedSend(sock,b"accept", debug) # Tell client that everything is fine! data = framedReceive(sock,debug) # Check out the data client sent. isZeroLen = False if (data == b"ERROR"): # Client sent an error - stop! print("ERROR: Something went wrong client-side. File not recieved.") sock.close() sys.exit(0) if data is None: # Check if file is zero length, and handle. print("WARNING: Zero-length file.") with open(filePath, 'w') as myFile: myFile.write("") isZeroLen = True if not isZeroLen: with open(filePath, 'wb') as myFile: # Otherwise, open a file to copy payload to. while True: myFile.write(data) # Read the data sent by the client and copy to the file. data = framedReceive(sock, debug) if not data: # When there's nothing more, stop taking payload. sys.exit(0) myFile.close() print("%s received. Exiting..." % fileName) sock.close() print("Closed connection", addr) sLock.release()
def main(): host,port = parseArguments() if host is None: print("Default IP address being used:127.0.0.1") host = "127.0.0.1" if port is None: print("Default port being used:50000") port = 50000 addrFamily = socket.AF_INET socktype = socket.SOCK_STREAM addrPort = (host,port) serverSocket = socket.socket(addrFamily,socktype) if serverSocket is None: print('could not open socket') sys.exit(1) serverSocket.bind(addrPort) serverSocket.listen(5) print("Listening on: ",addrPort) while True: sock, addr = serverSocket.accept() from framedSock import framedSend,framedReceive if not os.fork(): print("new cild process handling connection from",addr) #Used for debugging fileName = framedReceive(sock) try: newFile = open(fileName,"x") except : print("File already exists!") sys.exit(1) received = framedReceive(sock) if(received is None): os.remove(fileName) print("Something went wrong, the file could not be fully recieved") sys.exit(1) while received != b'DoneSending': newFile.write(received.decode()) received = framedReceive(sock) if(received is None): os.remove(fileName) print("Something went wrong, the file could not be fully recieved") sys.exit(1) print("Finished receiving") newFile.close() sys.exit(0)
def sendFile(sock, source, destination, debug, proxy): # Sends file based on source, destination and proxy if not os.path.exists(source): print('File %s does not exist' % source) return f = open(source) for line in f: payload = "{}:{}".format(destination, line).encode() framedSend(sock, payload, debug) callback = framedReceive(sock, debug) f.close() framedSend(sock, b'', debug) # Letting server know file transfered completely print(framedReceive(sock, debug).decode())
def recieveFile(fileName, lsocket, fileSize): file = open(fileName, 'wb') #data = lsocket.recv(100) data = framedReceive(lsocket, debug) size = len(data) file.write(data) while size < int(fileSize): data = framedReceive(lsocket, debug) #data = s.recv(100) size += len(data) file.write(data) print("Download Complete!")
def run(self): time.sleep(30) self.lock.acquire() try: fileName = framedReceive(self.sock, False) data = framedReceive(self.sock, False) if data: fileName = os.path.basename(fileName.decode()) fileWrite(fileName, data, self.sock) self.lock.release() return True except Exception as e: print(f"[+] Error: {e}") return False
def run(self): """ First get file name. Check if exists, if not get the rest of the file contents. """ if DEBUG: time.sleep(5) print("New thread handling connection from", self.addr) file_name = framedReceive(self.sock, debug=DEBUG) if not file_name: framedSend(self.sock, "File name not found".encode(), debug=DEBUG) return file_name = "results/" + file_name.decode() # lock thread, to begin writing file. thread_lock.acquire() if not os.path.exists(file_name) and file_name not in active_files: file = open(file_name, "w+b") active_files.add(file_name) else: framedSend(self.sock, "File already found!".encode(), debug=DEBUG) # Do nothing. return thread_lock.release() message = framedReceive(self.sock, debug=DEBUG) if not message: framedSend(self.sock, "Had trouble with contents of file".encode(), debug=DEBUG) return # Finish file operation. file.write(message) file.close() # Remove from active_files thread_lock.acquire() active_files.remove(file_name) thread_lock.release() print("File closed. Success!") framedSend(self.sock, "Success".encode(), debug=DEBUG)
def file_name(sock): file_name_flag = True start_flag = False file_name_start = b'title_start' # start of file name flag file_name_end = b'title_end' # end of file name flag file_name = "" while file_name_flag: file_flag = framedReceive(sock, debug) # get file name data file_name = file_name + " " + file_flag.decode() if start_flag: pass else: if file_flag == file_name_start: start_flag = True file_name = file_name.replace('title_start','') # removes title_start flag file_name = file_name.replace(' ','') file_name = file_name.replace('\n','') else: print("Error: Not name of file") sock.close() sys.exit(0) sock.close() if file_flag == file_name_end: file_name = file_name.replace('title_end','') # removes title_end flag file_name = file_name.replace(' ','') file_name = file_name.replace('\n','') file_name_flag = False return file_name
def receiveFile(): print("Starting new thread") try: fileName, contents = framedReceive(conn, debug) except: print("Error: File transfer was not successful!") #Informs the client conn.sendall(str(0).encode()) sys.exit(1) if not os.path.exists(path): os.makedirs(path) fileName = fileName.decode() #Thread safe existant file check. lock.acquire() #Checks if file file already transferred if (fileName in filesTransferred) or (os.path.exists(path + fileName)): print("File already transferred to server") conn.sendall(str(0).encode()) #Informs client lock.release() #Release lock before dying sys.exit() else: filesTransferred.append( fileName) #If it's a new file add to list of filesTransferred lock.release() with open(path + fileName, 'w+b') as f: f.write(contents) conn.sendall(str(1).encode()) print("File successfully transfered") sys.exit()
def puts(c): s.send(b'PUTS') #f = input("Enter file to put in server") txtfile = c[1].encode('utf-8') framedSend(s, txtfile, debug) message = framedReceive(s, debug) if message == b'begin': getruns = open(c[1], "rb") #open file for reading bytes s.send(b'LETSGO') #Lets drive this file to the end zone.. football references while True: run = getruns.read(100) s.send(run) print("sent ") #sent 100 bytes if not run: print("Done") #s.shutdown(socket.SHUT_WR) #s.send(b'TDBABY') break s.send(b'TDBABY') #Touchdown you're done getruns.close() s.close() else: print("File already exists in server") s.close()
def receive(): take = framedReceive(sock, debug) print(take) f = take.decode('utf-8') if os.path.isfile(f): print("This file already exists in directory") sock.send(b'wrrong') sys.exit(0) else: framedSend(sock, b'begin', debug) #txtfile = f.encode('utf-8') #framedSend(sock, txtfile, debug) txtfile = f with open("copy " + txtfile, 'wb') as r: while True: a = sock.recv(100) if a == b'LETSGO': continue #lets begin reading file elif a == b'TDBABY': print("Done writing") break elif a == b'WRONG': #wrong and tdbaby serve the similar purposes, but are different print("File does not exist exiting") break else: # print(a.decode('utf-8')) r.write(a) r.close() print("All done") sock.close()
def run(self): print("new thread handling connection from", self.addr) while True: print("listening on:", bindAddr) print("connection rec'd from", self.addr) lock.acquire() payload = framedReceive(self.sock, debug) if debug: print("rec'd: ", payload) if not payload: lock.release() sys.exit(1) payload = payload.decode() name = payload.split("<")[0] content = payload.split("<")[1].encode() try: if not os.path.isfile(name): file = open(name, 'wb+') file.write(content) file.close() else: print("File with name", name, "already exists on server. exiting...") except FileNotFoundError: print("Fail") lock.release()
def sendFile(fileName): print("sending " + fileName + " file") dataToSend = "fileName=" + fileName framedSend(s, dataToSend.encode(), debug) f = open(fileName, "rb").read() framedSend(s, f, debug) print("received:", framedReceive(s, debug).decode())
def server(): switchesVarDefaults = ( (('-l', '--listenPort'), 'listenPort', 50001), (('-d', '--debug'), "debug", False), # boolean (set if present) (('-?', '--usage'), "usage", False), # boolean (set if present) ) paramMap = params.parseParams(switchesVarDefaults) debug, listenPort = paramMap['debug'], paramMap['listenPort'] if paramMap['usage']: params.usage() bind_addr = (HOST, listenPort) # creating listening socket listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # associating socket with host and port number listen_socket.bind(bind_addr) # "makes" listening socket with max connection to 5 listen_socket.listen(5) print("listening on: ", bind_addr) # move to directory to receive files if not os.path.exists(PATH_FILES): os.makedirs(PATH_FILES) os.chdir(PATH_FILES) while True: # connection and tuple for client address (host, port) conn, addr = listen_socket.accept() # check connection and client address exist otherwise exit if not conn or not addr: sys.exit(1) if not os.fork(): print("connection rec'd from", addr) try: # receiving files sent from client filename, file_content = framedReceive(conn, debug) except: print("ERROR: file transfer failed") # send failed status conn.sendall(str(0).encode()) sys.exit(1) # attempt to save files into ReceivedFiles folder filename = filename.decode() write_file(filename, file_content, conn, addr) # send success status conn.sendall(str(1).encode()) sys.exit(0)
def send(name, size, info): sock = serverConnect(info) buff = int(size) framedSend(sock, name.encode(), False) with open(name, "rb") as f: payload = f.read(buff) framedSend(sock, payload, False) f.close() return framedReceive(sock, False)
def fileServer(): switchesVarDefaults = ( (('1', '--listenPort'), 'listenPort', 50001), (('?', '--usage'), 'usage', False), (('d', '--debug'), 'debug', False), ) # Sets Parameters based on demos parameterMap = params.parseParams(switchesVarDefaults) listenPort, debug = parameterMap['listenPort'], parameterMap['debug'] if parameterMap['usage']: params.usage() bindAddress = (HOST, listenPort) # Creates Listening Socket listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listenSocket.bind(bindAddress) # Can have up to 10 connections listenSocket.listen(10) print("Listening on: ", bindAddress) # check if dir exists to receive files, if not, create it anyway, then move to it if not os.path.exists(PATH): os.makedirs(PATH) os.chdir(PATH) while 1: connection, address = listenSocket.accept() # if no connection or no address, get out of there if not connection or not address: sys.exit(1) if not os.fork(): print("Connected by: ", address) # receive files from client connection try: fileName, contents = framedReceive(connection, debug) except: print("Error: File transfer was not successful!") connection.sendAll(str(0).encode()) sys.exit(1) # save files to 'receive' dir fileName = fileName.decode() writeFile(connection, address, fileName, contents) # return message of success connection.sendall(str(1).encode()) sys.exit(0)
def recv_file(filename): ''' Receive file from client and write to folder/filename. ''' global folder fname = folder + '/' + filename with open(fname, 'w') as f: while True: payload = framedReceive(sock, debug) if debug: print("fileServer rec'd: ", payload) if not payload: print("empty payload") break f.write(payload.decode())
def recv_file_name(): ''' Get file name from client and check if exists.''' global folder payload = framedReceive(sock, debug) fname = folder + '/' + payload.decode() if os.path.exists(fname): framedSend(sock, b"file already exists") print("file already exists, terminating") exit() else: framedSend(sock, b"OK") return payload.decode() return None
def fileServer(): switchesVarDefaults = ( (('1', '--listenPort'), 'listenPort', 50001), (('?', '--usage'), 'usage', False), (('d', '--debug'), 'debug', False), ) paramMap = params.parseParams(switchesVarDefaults) listenPort, usage, debug = paramMap['listenPort'], paramMap[ 'usage'], paramMap['debug'] if usage: params.usage() bind = (HOST, listenPort) listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listenSocket.bind(bind) listenSocket.listen(10) # 10 connections print("Listening on: ", bind) if not os.path.exists( PATH): # check if directory exists or create a new one os.makedirs(PATH) os.chdir(PATH) # move to directory while 50001: connection, address = listenSocket.accept() if not connection or not address: sys.exit(1) #exit loop if not os.fork(): print("Connected by: ", address) # receive files try: fileName, contents = framedReceive(connection, debug) except: print("Error: File transfer was not successful!") connection.sendall(str(0).encode()) sys.exit(1) # save files fileName = fileName.decode() writeFile(connection, address, fileName, contents) connection.sendall(str(1).encode()) # success sys.exit(0)
def write_to_file(file_name, sock): is_connected = True # flag for file_interuption while is_connected: with open(file_name, 'wb') as file: print("\nWriting data.\n") while is_connected: try: t_file_data = framedReceive(sock, debug) # get the data being sent #print(t_file_data.decode()) file.write(t_file_data) except: is_connected = False sock.close() print("File received.") print("\n--------------------------------------------------------------\n")
def cmd(): command=input(">>$ ") while(command !="q"): if ("put" in command): fileData= command.split(" ") fileName= fileData[1] data=readFile(fileName) size=getFileSize(fileName) print("encoding file...") name = bytearray(fileName+"/n", 'utf-8') framedSend(s, name, debug) framedSend(s, data, debug) print("message from server:", framedReceive(s, debug)) command=input(">>$ ")
def server(): switchesVarDefaults = ( (('1', '--listenPort'), 'listenPort', 50001), (('?', '--usage'), 'usage', False), (('d', '--debug'), 'debug', False), ) parameterMap = params.parseParams(switchesVarDefaults) listenPort, debug = parameterMap['listenPort'], parameterMap['debug'] if parameterMap['usage']: params.usage() bindAddress = (HOST, listenPort) # listening socket created listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listenSocket.bind(bindAddress) listenSocket.listen(10) print("Listening on: ", bindAddress) # check if files arebeing received, if not found then create it if not os.path.exists(PATH): os.makedirs(PATH) os.chdir(PATH) while 1: connection, address = listenSocket.accept() if not connection or not address: sys.exit(1) if not os.fork(): print("connect by: ", address) try: fileName, contents = framedReceive(connection, debug) except: print("Error: File transfer was not successful!") connection.send(str(0).encode()) sys.exit(1) fileName = fileName.decode() writeFile(connection, address, fileName, contents) connection.send(str(1).encode()) sys.exit(0)
def main(): # lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # listener socket bindAddr = ("127.0.0.1", listenPort) lsock.bind(bindAddr) lsock.listen(5) print("listening on:", bindAddr) while True: sock, addr = lsock.accept() from framedSock import framedSend, framedReceive if not os.fork(): #fork process to receive multiple connections print("new child process handling connection from", addr) payload = "" #receive file name and contents fileName, fileContents = framedReceive(sock, debug) if debug: print("rec'd: ", payload) if payload is None: print("File contents were empty, exiting...") sys.exit(1) #receive fileName fileName = fileName.decode() if fileName == "exit": sys.exit(0) try: #write file to transfer dir if not os.path.isfile("./transfer/" + fileName): file = open("./transfer/" + fileName, 'w+b') file.write(fileContents) file.close() print("File:", fileName, "successfully accepted!") sys.exit(0) else: print("File: ", fileName, "already exists.") sys.exit(1) except FileNotFoundError: print("File Not Found") sys.exit(1)
def run(self): while True: from framedSock import framedSend, framedReceive print("new child process handling connection from", self.addr) payload = "" lock.acquire() #receive file name and contents fileName, fileContents = framedReceive(self.sock, debug) if debug: print("rec'd: ", payload) if payload is None: print("File contents were empty, exiting...") lock.release() sys.exit(1) #receive fileName fileName = fileName.decode() if fileName == "exit": lock.release() sys.exit(0) try: #write file to transfer dir if not os.path.isfile("./transfer/" + fileName): file = open("./transfer/" + fileName, 'w+b') file.write(fileContents) file.close() print("File:", fileName, "successfully accepted!") lock.release() sys.exit(0) else: print("File: ", fileName, "already exists.") lock.release() sys.exit(1) except FileNotFoundError: print("File Not Found") lock.release() sys.exit(1)
def send(): payload = framedReceive(sock, debug) if debug: print("rec'd: ", payload) payload = payload.decode('utf-8') print("sending " + payload) if os.path.isfile(payload): getruns = open(payload, "rb") #open file for reading bytes sock.send( b'LETSGO' ) #Lets drive this file to the end zone.. football references while True: run = getruns.read(100) sock.send(run) print("sent ") #sent 100 bytes if not run: print("Done") break sock.send(b'TDBABY') #Touchdown you're done getruns.close() sys.exit(0) else: print("File does not exist informing client and exiting program") sock.send(b'WRONG') sys.exit(0)
params.usage() lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # listener socket bindAddr = ("127.0.0.1", listenPort) lsock.bind(bindAddr) lsock.listen(5) print("listening on:", bindAddr) from framedSock import framedSend, framedReceive while True: sock, addr = lsock.accept() print("connection rc'd from", addr) if not os.fork(): while True: payload = framedReceive(sock, debug) if not payload: break payload = payload.decode() if exists(payload): framedSend(sock, b"True", debug) else: framedSend(sock, b"False", debug) try: payload2 = framedReceive(sock, debug) except: print("connection lost while receiving, exiting") sys.exit(0) if not payload2: break
addrPort = (serverHost, serverPort) s = socket.socket(addrFamily, socktype) if s is None: print('could not open socket') sys.exit(1) s.connect(addrPort) file_to_send = input("type file to send : ") def utf8len(s): return len(s.encode('utf-8')) if exists(file_to_send): print("hello") file_copy = open(file_to_send, 'r') #open file file_data = file_copy.read() #save contents of file #print(file_data) if utf8len(file_data) == 0: sys.exit(0) else: framedSend(s, file_data.encode(), debug) print("received:", framedReceive(s, debug)) else: sys.exit(0)
print('error zero length file') sys.exit(0) else: #splitting the file name by the period and adding enumeration to the end splitFileName = transferFile.split('.') copiedFileEnumeration = '_copy.' fileNameForCopy = splitFileName[ 0] + copiedFileEnumeration + splitFileName[1] fileNameForCopy = fileNameForCopy.strip() #send file name to server to check if already on server framedSend(s, fileNameForCopy.encode(), debug) #response from server fileAlreadyOnServer = framedReceive(s, debug) #decode response fileAlreadyOnServer = fileAlreadyOnServer.decode() #if file is already on server exit if fileAlreadyOnServer == 'True': print('File is already on server!') sys.exit(0) #file is not on server, continue else: try: #send file framedSend(s, fileContents, debug) except: print('error while sending')