Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import sys
- import datetime
- import time
- import os
- CS_IP = socket.gethostbyname("lab8p3")
- CS_PORT = 58002
- MY_PORT = 59000
- MyIP=[l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
- if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)),
- s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET,
- socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
- #------------------------------------
- #| INIT |
- #------------------------------------
- for i in range(0,len(sys.argv)-1):
- if sys.argv[i] == "-n":
- CS_IP = socket.gethostbyname(sys.argv[i+1])
- if sys.argv[i] == "-p":
- CS_PORT = int(sys.argv[i+1])
- if sys.argv[i] == "-b":
- MY_PORT = int(sys.argv[i+1])
- s_udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
- s_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- s_udp.bind(("", MY_PORT))
- f = open("user_reg.txt","w")
- f.close()
- #---------------------------------------------------------
- # USER DATABASE
- #---------------------------------------------------------
- def create_user(user,password):
- f = open("user_reg.txt","a")
- f.write(user+"|"+password+"\n")
- f.close()
- def check_user(user,password):
- f = open("user_reg.txt","r")
- for line in f:
- if line.split("|")[0] == user:
- f.close()
- return "NOK"
- f.close()
- return "OK"
- def del_user(user):
- f = open("user_reg.txt","r")
- lines = f.readlines()
- f.close()
- f = open("user_reg.txt","w")
- for line in lines:
- if line.split("|")[0] != user:
- f.write(line)
- f.close()
- #---------------------------------------------------------
- # Interface de Envio de Mensagens: UDP
- #---------------------------------------------------------
- def send_udp(message):
- print datetime.datetime.now().strftime("[%H:%M:%S.%f")+"]UDP: Sending "+message+" to "+CS_IP+":",CS_PORT
- message.encode()
- s_udp.sendto(message, (CS_IP,CS_PORT))
- def receive_udp():
- data, addr = s_udp.recvfrom(1024)
- print datetime.datetime.now().strftime("[%H:%M:%S.%f")+"]UDP: Received "+ data+" from ",addr
- data.decode()
- return data
- #---------------------------------------------------------
- # Interface de Envio de Mensagens: TCP
- #---------------------------------------------------------
- def receive_tcp(conn, addr):
- print datetime.datetime.now().strftime("[%H:%M:%S.%f")+']TCP: Connection address:', addr
- data = conn.recv(BUFFER_SIZE)
- data.decode()
- print datetime.datetime.now().strftime("[%H:%M:%S.%f")+"]TCP: Received "+ data+" from ",addr
- return data
- def send_tcp(message, conn, addr):
- print datetime.datetime.now().strftime("[%H:%M:%S.%f")+"]TCP: Sending "+message+" to ",addr
- message.encode()
- conn.send(message)
- #---------------------------------------------------------
- # REG
- #---------------------------------------------------------
- def init(attempts):
- s_udp.settimeout(5)
- try:
- attempts += 1
- send_udp(reg_CS(MyIP,MY_PORT))
- if(receive_udp() == "RGR NOK\n" and attempts < 5):
- time.sleep(5)
- init(attempts)
- elif attempts == 5:
- print "Maximum attempts reached."
- sys.exit(1)
- else:
- s_udp.settimeout(None)
- except socket.timeout as e:
- init(attempts)
- def reg_CS(ip,port):
- return "REG "+ip+" "+str(port)
- #---------------------------------------------------------
- # UNR
- #---------------------------------------------------------
- def unr_CS(ip,port):
- return"UNR "+ip+" "+str(port)
- #---------------------------------------------------------
- # createFile/Dir
- #---------------------------------------------------------
- def createDir(dir):
- if not os.path.isdir(os.getcwd()+"/"+dir):
- os.mkdir(dir)
- def createFile(file,dir):
- f = open(dir+"/"+file.getName(), "w")
- f.write(file.getData())
- f.close()
- #---------------------------------------------------------
- # UPR
- #---------------------------------------------------------
- class File:
- def __init__(self, name, date, time, size, data):
- self.name = name
- self.datetime = datetime.datetime(int(date.split(".")[2]),int(date.split(".")[1]),int(date.split(".")[0]),int(time.split(":")[0]),int(time.split(":")[1]),int(time.split(":")[2]))
- self.size=int(size)
- def __str__(self):
- return "{0:s} {1:02d}.{2:02d}.{3:04d} {4:02d}.{5:02d}.{6:02d} {7:d}".format(self.name, self.datetime.day, self.datetime.month, self.datetime.year, self.datetime.hour, self.datetime.minute, self.datetime.second, self.size)
- def read_file(string):
- #print "name is "+string.split(" ")[0]+" ,"
- name = string.split(" ")[0]
- #print "date is "+string.split(" ")[1]+" ,"
- date = string.split(" ")[1]
- #print "time is "+string.split(" ")[2]+" ,"
- time = string.split(" ")[2]
- #print "size is "+string.split(" ")[3]+" ,"
- size = string.split(" ")[3]
- data_index = len(name) + 1 + len(date) + 1 + len(time) + 1 + len(size) + 1
- size = int(size)
- data = string[data_index:data_index+size]
- #print "data is "+data+" ,"
- file = File(name,date,time,size,data)
- #print "Remaining:"+string[data_index+size+1:]
- return file, string[data_index+size+1:]
- def command_parser(command,stage):
- if stage == "init" and command[:4] == "UPL ":
- return command_parser(command[4:],"dir")
- elif stage == "dir":
- dir = command.split(" ")[0]
- return command_parser(command[len(dir)+1:], "nFiles"), dir
- elif stage == "nFiles":
- try:
- files=[]
- n = int(command.split(" ")[0])
- file_string = command[len(command.split(" ")[0])+1:]
- for i in range(0,n):
- myfile , file_string = read_file(file_string)
- files.append(myfile)
- return files
- except ValueError:
- return "UPR ERR\n"
- else:
- return "UPR ERR\n"
- def UPR(stri, user):
- try:
- files, dir = command_parser(stri,"init")
- createDir(user)
- createDir(user + "/" + dir)
- for file in files:
- createFile(file, user + "/" + dir)
- return "UPR OK\n"
- except IOError, ValueError:
- return "UPR NOK\n"
- #---------------------------------------------------------
- # RBR
- #---------------------------------------------------------
- #TODO
- #falta o err
- def RBR(stri, user):
- dir_path = os.getcwd()+"/"+user+"/"+dir
- files = ""
- N = 0;
- try:
- for filename in os.listdir(dir_path):
- if os.path.isfile(dir_path+"/"+filename):
- mtime = time.gmtime(os.path.getmtime(dir_path+"/"+filename))
- f = open(dir_path + "/" + filename, "r")
- data = f.read()
- f.close()
- files = files + " " + filename + " " + "{0:02d}.{1:02d}.{2:04d} {3:02d}:{4:02d}:{5:02d}".format(mtime.tm_mday, mtime.tm_mon,
- mtime.tm_year, mtime.tm_hour, mtime.tm_min, mtime.tm_sec)+ " "+ str(int(os.stat(dir_path+"/"+filename).st_size)) + " " + data
- N += 1
- files = files[1:]
- print "RBR " + " " + str(N) + " " + files + "\n"
- send("RBR " + " " + str(N) + " " + files + "\n")
- except:
- send("RBR EOF\n")
- #---------------------------------------------------------
- # AUR
- #---------------------------------------------------------
- def user_aut(user,password): #Autenticacao de users
- if check_user(user,password)=="OK":
- return "AUR OK\n"
- else:
- return "AUR NOK\n"
- #---------------------------------------------------------
- # LUR
- #---------------------------------------------------------
- def user_reg(user,password): #Registo de users
- check = check_user(user,password)
- print "[DEBUG]"+check
- if check == "OK":
- create_user(user,password)
- return "LUR OK\n"
- elif check =="NOK":
- return "LUR NOK\n"
- else:
- return "LUR ERR\n"
- #---------------------------------------------------------
- # DLB ------------------------------------------------------------ TO TEST
- #---------------------------------------------------------
- def delete_dir(user,dir):
- work_dir=os.getcwd()
- if os.path.isdir(work_dir+"/"+user+"/"+dir):
- if len(os.dirlist())==1:
- os.rmdir(dir)
- os.rmdir(work_dir+"/"+user)
- return "DBR OK\n"
- else:
- os.rmdir(dir)
- return "DBR OK\n"
- else:
- return "DBR NOK\n"
- #---------------------------------------------------------
- # UNR
- #---------------------------------------------------------
- def unr_CS(ip,port):
- return"UNR "+ip+" "+str(port)
- #---------------------------------------------------------
- # Directories
- #---------------------------------------------------------
- def createDir(dir):
- if not os.path.isdir(os.getcwd()+"/"+dir):
- os.mkdir(dir)
- #---------------------------------------------------------
- # CHILD
- #---------------------------------------------------------
- def child():
- s_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- s_tcp.bind(("", MY_PORT))
- s_tcp.listen(1)
- while True:
- conn , addr = s_tcp.accept()
- receipt = receive_tcp(conn, addr)
- if receipt.split(" ")[0]=="AUT":
- user= receipt.split(" ")[1]
- password=receipt.split(" ")[2]
- AUR = user_aut(user,password)
- send_tcp(AUR, conn, addr)
- if AUR == "AUR OK\n":
- receipt = receive_tcp(conn, addr)
- if receipt.split(" ")[0] == "UPL":
- send_tcp(UPR(receipt,user), conn, addr)
- elif receipt.split(" ")[0] == "RSB":
- send_tcp(RBR(receipt.split(" ")[1],user), conn, addr)
- #---------------------------------------------------------
- # main
- #---------------------------------------------------------
- try:
- init(0)
- pid = os.fork()
- if pid==0:
- child()
- while True:
- command=receive_udp()
- print command
- if command.split(" ")[0]=="AUT":
- user= command.split(" ")[1]
- password=command.split(" ")[2]
- send(user_aut(user,password))
- elif command.split(" ")[0]=="LSU":
- user= command.split(" ")[1]
- password=command.split(" ")[2]
- send_udp(user_reg(user,password))
- elif command.split(" ")[0]=="DLB":
- user=command.split(" ")[1]
- dir=command.split(" ")[2]
- send_udp(delete_dir(user,dir))
- else:
- send("ERROR")
- except KeyboardInterrupt: #CTRL+C Interrupt
- send_udp(unr_CS(MyIP,MY_PORT))
- sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement